Use Case Scenario (C#)

You need to replace Resources.WebscantestSqlinj with your config file.

csharp
1
using System;
2
using System.Diagnostics;
3
using System.IO;
4
using System.Net;
5
using System.Text;
6
using System.Threading;
7
using Newtonsoft.Json.Linq;
8
namespace NTOERestApiTest.Console
9
{
10
public class Program
11
{
12
private const string RootPath = "http://localhost:54073/AppSpiderEnterpriserest/v1/"; private const string Username = "wstclient";
13
private const string Password = "wstclient";
14
public static void Main(string[] args)
15
{
16
// login
17
var authResult = PostRequest("authentication/login", string.Format("{{ name: \"{0}\", password: \"{1}\" }}", Username, Password));
18
if (authResult.IsSuccess == null || !authResult.IsSuccess.Value)
19
{
20
System.Console.WriteLine(authResult.ErrorMessage.Value);
21
return;
22
}
23
string token = authResult.Token.Value;
24
System.Console.WriteLine("Logged in successfully.");
25
// get configs and check config with name WebscantestSqlInj doesn't exist(unable to create 2 configs with the same name)
26
var configsResult = GetRequest("config/getconfigs", token);
27
if (configsResult.IsSuccess == null || !configsResult.IsSuccess.Value)
28
{
29
System.Console.WriteLine(configsResult.ErrorMessage.Value);
30
return;
31
}
32
Guid? configId = null;
33
bool isConfigWithWebscantestSqlInjNameExist = false;
34
foreach (dynamic config in configsResult.Configs)
35
{
36
if (config.Name == "WebscantestSqlInj")
37
{
38
isConfigWithWebscantestSqlInjNameExist = true;
39
configId = config.Id;
40
System.Console.WriteLine("Config with name WebscantestSqlInj found.");
41
break;
42
} }
43
// Create new config if config with the same name doesn't exist
44
if (!isConfigWithWebscantestSqlInjNameExist)
45
{
46
string errorMessage;
47
configId = CreateConfig(token, out errorMessage);
48
if (configId == null)
49
{
50
System.Console.WriteLine(errorMessage);
51
return;
52
}
53
System.Console.WriteLine("Config with name WebscantestSqlInj created.");
54
}
55
// run scan
56
var runScanResult = PostRequest("scan/runscan", string.Format("{{\"configId\":
57
\"{0}\" }}", configId), token);
58
if (runScanResult.IsSuccess == null || !runScanResult.IsSuccess.Value)
59
{
60
System.Console.WriteLine(runScanResult.ErrorMessage.Value);
61
return;
62
}
63
var scanId = runScanResult.Scan.Id;
64
System.Console.WriteLine("Scan started. Scan ID: {0}", scanId);
65
// waiting for scan finished
66
var stopwatch = new Stopwatch(); stopwatch.Start();
67
bool isScanFinished = false; while (!isScanFinished)
68
{
69
System.Console.Write("{0} minutes and {1} seconds elapsed.",
70
stopwatch.Elapsed.Minutes, stopwatch.Elapsed.Seconds);
71
System.Console.Write("\r");
72
Thread.Sleep(5000);
73
var isScanFinishedResult =
74
GetRequest(string.Format("scan/isscanfinished?scanId={0}", scanId), token);
75
if (isScanFinishedResult.IsSuccess == null ||
76
!isScanFinishedResult.IsSuccess.Value)
77
{
78
System.Console.WriteLine(isScanFinishedResult.ErrorMessage.Value);
79
return;
80
}
81
isScanFinished = isScanFinishedResult.Result;
82
}
83
stopwatch.Stop();
84
System.Console.WriteLine();
85
System.Console.WriteLine("Scan finished.");
86
// check finished scan has report
87
var scanHasReportResult = GetRequest(string.Format("scan/hasreport?scanId={0}",
88
scanId), token);
89
if (scanHasReportResult.IsSuccess == null || !scanHasReportResult.IsSuccess.Value)
90
{
91
System.Console.WriteLine(scanHasReportResult.ErrorMessage.Value);
92
return;
93
}
94
if (!scanHasReportResult.Result.Value)
95
{
96
System.Console.WriteLine("Scan finished and has no report.");
97
return;
98
}
99
SaveFile(string.Format("report/getreportzip?scanid={0}", scanId),
100
"ReportAllFiles.zip", token);
101
System.Console.WriteLine("Report saved with name ReportAllFiles.zip.");
102
}
103
private static Guid? CreateConfig(string token, out string errorMessage)
104
{
105
token);
106
errorMessage = null;
107
var engineGroupsResult = GetRequest("enginegroup/getenginegroupsforclient",
108
if (engineGroupsResult.EngineGroups == null)
109
{
110
errorMessage = engineGroupsResult.ErrorMessage.Value;
111
return null;
112
}
113
if (engineGroupsResult.EngineGroups.Count == 0)
114
{
115
errorMessage = "Where are no engine groups assigned to current client.";
116
return null;
117
}
118
var engineGroupId = engineGroupsResult.EngineGroups[0].Id;
119
var configJson = string.Format(@"{{
120
'DefendEnabled': true,
121
'MonitoringDelay': 0,
122
'MonitoringTriggerScan': true,
123
'Id': null,
124
'Name': 'WebscantestSqlInj',
125
'ClientId': null,
126
'EngineGroupId': '{0}',
127
'Monitoring': true,
128
'IsApproveRequired': false,
129
'Xml': '{1}'
130
}}", engineGroupId, Resources.WebscantestSqlInj /* TODO: replace with your config
131
string (scfg file) */); // ', ", \ symbols must be escaped in config string (\', \", \\)
132
var createConfigResult = PostMultipartRequest("config/saveconfig", "config",
133
configJson, token);
134
if (createConfigResult.IsSuccess == null || !createConfigResult.IsSuccess.Value)
135
{
136
errorMessage = createConfigResult.ErrorMessage.Value;
137
return null;
138
}
139
return createConfigResult.Config.Id;
140
}
141
private static void SaveFile(string url, string fileName, string token)
142
{
143
using (var webClient = new WebClient())
144
{
145
webClient.Headers["Authorization"] = "Basic " + token;
146
webClient.DownloadFile(RootPath + url, fileName);
147
}
148
}
149
private static dynamic GetRequest(string url, string token)
150
{
151
string responseStr;
152
try
153
{
154
var httpRequest = (HttpWebRequest)WebRequest.Create(RootPath + url);
155
httpRequest.Accept = "application/json";
156
httpRequest.ContentType = "application/json";
157
httpRequest.Method = "GET";
158
httpRequest.Headers["Authorization"] = "Basic " + token;
159
var response = httpRequest.GetResponse();
160
using (Stream data = response.GetResponseStream()) using (var reader = new StreamReader(data))
161
{
162
responseStr = reader.ReadToEnd();
163
}
164
}
165
catch (WebException e)
166
{
167
using (WebResponse response = e.Response)
168
{
169
} }
170
using (Stream data = response.GetResponseStream())
171
using (var reader = new StreamReader(data))
172
{
173
responseStr = reader.ReadToEnd();
174
}
175
return JObject.Parse(responseStr);
176
}
177
private static dynamic PostRequest(string url, string jsonData, string token = "") {
178
string responseStr;
179
try
180
{
181
var httpRequest = (HttpWebRequest)WebRequest.Create(RootPath + url);
182
httpRequest.Accept = "application/json";
183
httpRequest.ContentType = "application/json";
184
httpRequest.Method = "POST";
185
httpRequest.Headers["Authorization"] = "Basic " + token;
186
string jsonContent = jsonData;
187
var encoding = new ASCIIEncoding();
188
byte[] bytes = encoding.GetBytes(jsonContent);
189
Stream newStream = httpRequest.GetRequestStream();
190
newStream.Write(bytes, 0, bytes.Length);
191
newStream.Close();
192
var response = httpRequest.GetResponse();
193
using (Stream data = response.GetResponseStream()) using (var reader = new StreamReader(data))
194
{
195
responseStr = reader.ReadToEnd();
196
}
197
}
198
catch (WebException e)
199
{
200
using (WebResponse response = e.Response)
201
{
202
using (Stream data = response.GetResponseStream())
203
} }
204
using (var reader = new StreamReader(data))
205
{
206
responseStr = reader.ReadToEnd();
207
}
208
return JObject.Parse(responseStr);
209
}
210
private static dynamic PostMultipartRequest(string url, string fileName, string
211
fileData, string token = "")
212
{
213
string responseStr;
214
try
215
{
216
newLine +
217
var boundary = "------------------------" + DateTime.Now.Ticks;
218
var newLine = Environment.NewLine;
219
var propFormat = "--" + boundary + newLine +
220
"Content-Disposition: form-data; name=\"{0}\"" + newLine +
221
"{1}" + newLine;
222
var httpRequest = (HttpWebRequest)WebRequest.Create(RootPath + url);
223
httpRequest.Accept = "application/json";
224
httpRequest.ContentType = "multipart/form-data; boundary=" + boundary;
225
httpRequest.Method = "POST";
226
httpRequest.Headers["Authorization"] = "Basic " + token;
227
using (var reqStream = httpRequest.GetRequestStream())
228
{
229
var reqWriter = new StreamWriter(reqStream);
230
var tmp = string.Format(propFormat, fileName, fileData);
231
reqWriter.Write(tmp);
232
reqWriter.Write("--" + boundary + "--");
233
reqWriter.Write("\r\n");
234
reqWriter.Flush();
235
}
236
var response = httpRequest.GetResponse();
237
using (Stream data = response.GetResponseStream()) using (var reader = new StreamReader(data))
238
{
239
responseStr = reader.ReadToEnd();
240
}
241
}
242
catch (WebException e)
243
{
244
using (WebResponse response = e.Response)
245
{
246
using (Stream data = response.GetResponseStream())
247
using (var reader = new StreamReader(data))
248
{
249
} }
250
} }
251
responseStr = reader.ReadToEnd();
252
}
253
return JObject.Parse(responseStr);