Use Case Scenario (C#)
⚠️
You need to replace Resources.WebscantestSqlinj with your config file.
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using Newtonsoft.Json.Linq;
namespace NTOERestApiTest.Console
{
public class Program
{
private const string RootPath = "http://localhost:54073/AppSpiderEnterpriserest/v1/"; private const string Username = "wstclient";
private const string Password = "wstclient";
public static void Main(string[] args)
{
// login
var authResult = PostRequest("authentication/login", string.Format("{{ name: \"{0}\", password: \"{1}\" }}", Username, Password));
if (authResult.IsSuccess == null || !authResult.IsSuccess.Value)
{
System.Console.WriteLine(authResult.ErrorMessage.Value);
return;
}
string token = authResult.Token.Value;
System.Console.WriteLine("Logged in successfully.");
// get configs and check config with name WebscantestSqlInj doesn't exist(unable to create 2 configs with the same name)
var configsResult = GetRequest("config/getconfigs", token);
if (configsResult.IsSuccess == null || !configsResult.IsSuccess.Value)
{
System.Console.WriteLine(configsResult.ErrorMessage.Value);
return;
}
Guid? configId = null;
bool isConfigWithWebscantestSqlInjNameExist = false;
foreach (dynamic config in configsResult.Configs)
{
if (config.Name == "WebscantestSqlInj")
{
isConfigWithWebscantestSqlInjNameExist = true;
configId = config.Id;
System.Console.WriteLine("Config with name WebscantestSqlInj found.");
break;
} }
// Create new config if config with the same name doesn't exist
if (!isConfigWithWebscantestSqlInjNameExist)
{
string errorMessage;
configId = CreateConfig(token, out errorMessage);
if (configId == null)
{
System.Console.WriteLine(errorMessage);
return;
}
System.Console.WriteLine("Config with name WebscantestSqlInj created.");
}
// run scan
var runScanResult = PostRequest("scan/runscan", string.Format("{{\"configId\":
\"{0}\" }}", configId), token);
if (runScanResult.IsSuccess == null || !runScanResult.IsSuccess.Value)
{
System.Console.WriteLine(runScanResult.ErrorMessage.Value);
return;
}
var scanId = runScanResult.Scan.Id;
System.Console.WriteLine("Scan started. Scan ID: {0}", scanId);
// waiting for scan finished
var stopwatch = new Stopwatch(); stopwatch.Start();
bool isScanFinished = false; while (!isScanFinished)
{
System.Console.Write("{0} minutes and {1} seconds elapsed.",
stopwatch.Elapsed.Minutes, stopwatch.Elapsed.Seconds);
System.Console.Write("\r");
Thread.Sleep(5000);
var isScanFinishedResult =
GetRequest(string.Format("scan/isscanfinished?scanId={0}", scanId), token);
if (isScanFinishedResult.IsSuccess == null ||
!isScanFinishedResult.IsSuccess.Value)
{
System.Console.WriteLine(isScanFinishedResult.ErrorMessage.Value);
return;
}
isScanFinished = isScanFinishedResult.Result;
}
stopwatch.Stop();
System.Console.WriteLine();
System.Console.WriteLine("Scan finished.");
// check finished scan has report
var scanHasReportResult = GetRequest(string.Format("scan/hasreport?scanId={0}",
scanId), token);
if (scanHasReportResult.IsSuccess == null || !scanHasReportResult.IsSuccess.Value)
{
System.Console.WriteLine(scanHasReportResult.ErrorMessage.Value);
return;
}
if (!scanHasReportResult.Result.Value)
{
System.Console.WriteLine("Scan finished and has no report.");
return;
}
SaveFile(string.Format("report/getreportzip?scanid={0}", scanId),
"ReportAllFiles.zip", token);
System.Console.WriteLine("Report saved with name ReportAllFiles.zip.");
}
private static Guid? CreateConfig(string token, out string errorMessage)
{
token);
errorMessage = null;
var engineGroupsResult = GetRequest("enginegroup/getenginegroupsforclient",
if (engineGroupsResult.EngineGroups == null)
{
errorMessage = engineGroupsResult.ErrorMessage.Value;
return null;
}
if (engineGroupsResult.EngineGroups.Count == 0)
{
errorMessage = "Where are no engine groups assigned to current client.";
return null;
}
var engineGroupId = engineGroupsResult.EngineGroups[0].Id;
var configJson = string.Format(@"{{
'DefendEnabled': true,
'MonitoringDelay': 0,
'MonitoringTriggerScan': true,
'Id': null,
'Name': 'WebscantestSqlInj',
'ClientId': null,
'EngineGroupId': '{0}',
'Monitoring': true,
'IsApproveRequired': false,
'Xml': '{1}'
}}", engineGroupId, Resources.WebscantestSqlInj /* TODO: replace with your config
string (scfg file) */); // ', ", \ symbols must be escaped in config string (\', \", \\)
var createConfigResult = PostMultipartRequest("config/saveconfig", "config",
configJson, token);
if (createConfigResult.IsSuccess == null || !createConfigResult.IsSuccess.Value)
{
errorMessage = createConfigResult.ErrorMessage.Value;
return null;
}
return createConfigResult.Config.Id;
}
private static void SaveFile(string url, string fileName, string token)
{
using (var webClient = new WebClient())
{
webClient.Headers["Authorization"] = "Basic " + token;
webClient.DownloadFile(RootPath + url, fileName);
}
}
private static dynamic GetRequest(string url, string token)
{
string responseStr;
try
{
var httpRequest = (HttpWebRequest)WebRequest.Create(RootPath + url);
httpRequest.Accept = "application/json";
httpRequest.ContentType = "application/json";
httpRequest.Method = "GET";
httpRequest.Headers["Authorization"] = "Basic " + token;
var response = httpRequest.GetResponse();
using (Stream data = response.GetResponseStream()) using (var reader = new StreamReader(data))
{
responseStr = reader.ReadToEnd();
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
} }
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
responseStr = reader.ReadToEnd();
}
return JObject.Parse(responseStr);
}
private static dynamic PostRequest(string url, string jsonData, string token = "") {
string responseStr;
try
{
var httpRequest = (HttpWebRequest)WebRequest.Create(RootPath + url);
httpRequest.Accept = "application/json";
httpRequest.ContentType = "application/json";
httpRequest.Method = "POST";
httpRequest.Headers["Authorization"] = "Basic " + token;
string jsonContent = jsonData;
var encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes(jsonContent);
Stream newStream = httpRequest.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = httpRequest.GetResponse();
using (Stream data = response.GetResponseStream()) using (var reader = new StreamReader(data))
{
responseStr = reader.ReadToEnd();
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
using (Stream data = response.GetResponseStream())
} }
using (var reader = new StreamReader(data))
{
responseStr = reader.ReadToEnd();
}
return JObject.Parse(responseStr);
}
private static dynamic PostMultipartRequest(string url, string fileName, string
fileData, string token = "")
{
string responseStr;
try
{
newLine +
var boundary = "------------------------" + DateTime.Now.Ticks;
var newLine = Environment.NewLine;
var propFormat = "--" + boundary + newLine +
"Content-Disposition: form-data; name=\"{0}\"" + newLine +
"{1}" + newLine;
var httpRequest = (HttpWebRequest)WebRequest.Create(RootPath + url);
httpRequest.Accept = "application/json";
httpRequest.ContentType = "multipart/form-data; boundary=" + boundary;
httpRequest.Method = "POST";
httpRequest.Headers["Authorization"] = "Basic " + token;
using (var reqStream = httpRequest.GetRequestStream())
{
var reqWriter = new StreamWriter(reqStream);
var tmp = string.Format(propFormat, fileName, fileData);
reqWriter.Write(tmp);
reqWriter.Write("--" + boundary + "--");
reqWriter.Write("\r\n");
reqWriter.Flush();
}
var response = httpRequest.GetResponse();
using (Stream data = response.GetResponseStream()) using (var reader = new StreamReader(data))
{
responseStr = reader.ReadToEnd();
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
} }
} }
responseStr = reader.ReadToEnd();
}
return JObject.Parse(responseStr);