diff --git a/code/AmIVulnerable/AmIVulnerable/Controllers/DbController.cs b/code/AmIVulnerable/AmIVulnerable/Controllers/DbController.cs
index 055f91f..35d1211 100644
--- a/code/AmIVulnerable/AmIVulnerable/Controllers/DbController.cs
+++ b/code/AmIVulnerable/AmIVulnerable/Controllers/DbController.cs
@@ -1,406 +1,408 @@
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.CodeAnalysis;
-using Modells;
-using MySql.Data.MySqlClient;
-using Newtonsoft.Json;
-using SerilogTimings;
-using System.Data;
-using System.Diagnostics;
-using System.Text.RegularExpressions;
-using CM = System.Configuration.ConfigurationManager;
-
-namespace AmIVulnerable.Controllers {
-
- /// Interact direct with the database, like create the cve-table or request packages.
- [Route("api/[controller]")]
- [ApiController]
- public class DbController : ControllerBase {
-
- #region Config
- private readonly IConfiguration Configuration;
-
- public DbController(IConfiguration configuration) {
- Configuration = configuration;
- }
- #endregion
-
- #region Controller
-
- /// Update the Database, if it exists already.
- ///
- [HttpPost]
- [Route("update")]
- public IActionResult UpdateCveDatabase() {
- using (Operation.Time("UpdateCveDatabase")) {
- try {
- // MySql Connection
- MySqlConnection connection = new MySqlConnection(Configuration["ConnectionStrings:cvedb"]);
-
- MySqlCommand cmdTestIfTableExist = new MySqlCommand($"" +
- $"SELECT COUNT(*) " +
- $"FROM information_schema.TABLES " +
- $"WHERE (TABLE_SCHEMA = 'cve') AND (TABLE_NAME = 'cve');", connection);
+//using Microsoft.AspNetCore.Mvc;
+//using Microsoft.CodeAnalysis;
+//using Modells;
+//using MySql.Data.MySqlClient;
+//using Newtonsoft.Json;
+//using SerilogTimings;
+//using System.Data;
+//using System.Diagnostics;
+//using System.Text.RegularExpressions;
+//using CM = System.Configuration.ConfigurationManager;
+
+//namespace AmIVulnerable.Controllers {
+
+// /// Interact direct with the database, like create the cve-table or request packages.
+// //[Route("api/[controller]")]
+// //[ApiController]
+// public class DbController : ControllerBase {
+
+// #region Config
+// private readonly IConfiguration Configuration;
+
+// public DbController(IConfiguration configuration) {
+// Configuration = configuration;
+// }
+// #endregion
+
+// #region Controller
+
+// /// Update the Database, if it exists already.
+// ///
+// //[HttpPost]
+// //[Route("update")]
+// public IActionResult UpdateCveDatabase() {
+// using (Operation.Time("UpdateCveDatabase")) {
+// try {
+// // MySql Connection
+// MySqlConnection connection = new MySqlConnection(Configuration["ConnectionStrings:cvedb"]);
+
+// MySqlCommand cmdTestIfTableExist = new MySqlCommand($"" +
+// $"SELECT COUNT(*) " +
+// $"FROM information_schema.TABLES " +
+// $"WHERE (TABLE_SCHEMA = 'cve') AND (TABLE_NAME = 'cve');", connection);
- connection.Open();
- int count = cmdTestIfTableExist.ExecuteNonQuery();
- connection.Close();
-
- if (count == 0) {
- return BadRequest("Table does not exist!\nPlease download cve data and create the database before trying to update it using the update route!");
- }
-
- //start update process
- try {
- ProcessStartInfo process = new ProcessStartInfo {
- FileName = "bash",
- RedirectStandardInput = true,
- WorkingDirectory = $"",
- };
-
- Process runProcess = Process.Start(process)!;
- runProcess.StandardInput.WriteLine($"git " +
- $"clone {CM.AppSettings["StandardCveUrlPlusTag"]!} " + // git url
- $"raw"); // target dir
- runProcess.StandardInput.WriteLine($"exit");
- runProcess.WaitForExit();
- }
- catch (Exception ex) {
- return BadRequest(ex.StackTrace);
- }
-
- //read the file List
- List fileList = new List();
- List indexToDelete = new List();
- string path = "raw";
- ExploreFolder(path, fileList);
-
- //filter for json files
- foreach (int i in Enumerable.Range(0, fileList.Count)) {
- if (!Regex.IsMatch(fileList[i], @"CVE-[-\S]+.json")) {
- indexToDelete.Add(i);
- }
- }
- foreach (int i in Enumerable.Range(0, indexToDelete.Count)) {
- fileList.RemoveAt(indexToDelete[i] - i);
- }
-
- // Drop Index for faster insert
- MySqlCommand cmdIndexDrop = new MySqlCommand("CALL drop_index_on_designation_if_exists();", connection);
+// connection.Open();
+// int count = cmdTestIfTableExist.ExecuteNonQuery();
+// connection.Close();
+
+// if (count == 0) {
+// return BadRequest("Table does not exist!\nPlease download cve data and create the database before trying to update it using the update route!");
+// }
+
+// //start update process
+// try {
+// ProcessStartInfo process = new ProcessStartInfo {
+// FileName = "bash",
+// RedirectStandardInput = true,
+// WorkingDirectory = $"",
+// };
+
+// Process runProcess = Process.Start(process)!;
+// runProcess.StandardInput.WriteLine($"git " +
+// $"clone {CM.AppSettings["StandardCveUrlPlusTag"]!} " + // git url
+// $"raw"); // target dir
+// runProcess.StandardInput.WriteLine($"exit");
+// runProcess.WaitForExit();
+// }
+// catch (Exception ex) {
+// return BadRequest(ex.StackTrace);
+// }
+
+// //read the file List
+// List fileList = new List();
+// List indexToDelete = new List();
+// string path = "raw";
+// ExploreFolder(path, fileList);
+
+// //filter for json files
+// foreach (int i in Enumerable.Range(0, fileList.Count)) {
+// if (!Regex.IsMatch(fileList[i], @"CVE-[-\S]+.json")) {
+// indexToDelete.Add(i);
+// }
+// }
+// foreach (int i in Enumerable.Range(0, indexToDelete.Count)) {
+// fileList.RemoveAt(indexToDelete[i] - i);
+// }
+
+// // Drop Index for faster insert
+// MySqlCommand cmdIndexDrop = new MySqlCommand("CALL drop_index_on_designation_if_exists();", connection);
- connection.Open();
- cmdIndexDrop.ExecuteNonQuery();
- connection.Close();
-
- //start insert/update in MySQL
- int insertAndUpdateIndex = 0;
- foreach (string x in fileList) {
- string insertIntoString = "INSERT INTO cve(cve_number, designation, version_affected, full_text) " +
- "VALUES(@cve, @des, @ver, @ful) " +
- "ON DUPLICATE KEY UPDATE " +
- "version_affected = @ver, " +
- "full_text = @ful;" ;
- MySqlCommand cmdInsert = new MySqlCommand(insertIntoString, connection);
-
- string json = System.IO.File.ReadAllText(x);
- CVEcomp cve = JsonConvert.DeserializeObject(json)!;
-
- string affected = "";
- foreach (Affected y in cve.containers.cna.affected) {
- foreach (Modells.Version z in y.versions) {
- affected += z.version + $"({z.status}) |";
- }
- }
- if (affected.Length > 25_000) {
- affected = "to long -> view full_text";
- }
- string product = "n/a";
- try {
- product = cve.containers.cna.affected[0].product;
- if (product.Length > 500) {
- product = product[0..500];
- }
- if (product.Equals("")) {
- product = "n/a";
- }
- }
- catch {
- product = "n/a";
- }
- cmdInsert.Parameters.AddWithValue("@cve", cve.cveMetadata.cveId);
- cmdInsert.Parameters.AddWithValue("@des", product);
- cmdInsert.Parameters.AddWithValue("@ver", affected);
- cmdInsert.Parameters.AddWithValue("@ful", JsonConvert.SerializeObject(cve, Formatting.None));
-
- connection.Open();
- insertAndUpdateIndex += cmdInsert.ExecuteNonQuery();
- connection.Close();
- }
-
- connection.Open();
- MySqlCommand cmdIndexCreated = new MySqlCommand("CREATE INDEX idx_designation ON cve (designation);", connection);
- cmdIndexCreated.ExecuteNonQuery();
- connection.Close();
-
- return Ok(insertAndUpdateIndex);
- }
- catch (Exception ex) {
- return BadRequest(ex.StackTrace + "\n\n" + ex.Message);
- }
- }
- }
-
- /// Return the full text of a cve, when it is requested.
- ///
- ///
- [HttpGet]
- [Route("getFullTextFromCveNumber")]
- public IActionResult GetFullTextCve([FromQuery] string? cve_number) {
- if (!(this.Request.Headers.Accept.Equals("application/json") || this.Request.Headers.Accept.Equals("*/*"))) {
- return StatusCode(406);
- }
- using (Operation.Time("GetFullTextCve")) {
- if (cve_number is null) {
- return BadRequest("Empty cve_number");
- }
- try {
- // MySql Connection
- MySqlConnection connection = new MySqlConnection(Configuration["ConnectionStrings:cvedb"]);
-
- connection.Open();
- MySqlCommand cmdIndexCreated = new MySqlCommand($"" +
- $"SELECT full_text " +
- $"FROM cve.cve " +
- $"WHERE cve_number = '{cve_number}';", connection);
- MySqlDataReader reader = cmdIndexCreated.ExecuteReader();
- DataTable resDataTable = new DataTable();
- resDataTable.Load(reader);
- connection.Close();
-
- if (resDataTable.Rows.Count == 0) {
- return NoContent();
- }
-
- CVEcomp? cVEcomp = JsonConvert.DeserializeObject(resDataTable.Rows[0]["full_text"].ToString()!);
-
- return Ok(cVEcomp);
- }
- catch (Exception ex) {
- return BadRequest(ex.StackTrace + "\n\n" + ex.Message);
-
- }
- }
- }
-
- /// Check for an cve entry of a package with all its versions
- /// Name of package to search
- /// true: search db, false: search raw-json
- /// Version of package to search
- /// Ok with result. NoContent if empty.
- [HttpGet]
- [Route("checkSinglePackage")]
- public IActionResult CheckSinglePackage([FromQuery] string PackageName,
- [FromQuery] string? PackageVersion) {
- if (!(this.Request.Headers.Accept.Equals("application/json") || this.Request.Headers.Accept.Equals("*/*"))) {
- return StatusCode(406);
- }
- using (Operation.Time($"Complete Time for Query-SingleSearch after Package \"{PackageName}\"")) {
- List results = [];
- DataTable dtResult = SearchInMySql(PackageName);
- // convert the result
- foreach (DataRow x in dtResult.Rows) {
- CveResult y = new CveResult() {
- CveNumber = x["cve_number"].ToString() ?? "",
- Designation = x["designation"].ToString() ?? "",
- Version = x["version_affected"].ToString() ?? ""
- };
- CVEcomp temp = JsonConvert.DeserializeObject(x["full_text"].ToString() ?? string.Empty) ?? new CVEcomp();
- try {
- if (temp.containers.cna.metrics.Count != 0) {
- y.CvssV31 = temp.containers.cna.metrics[0].cvssV3_1;
- }
- if (temp.containers.cna.descriptions.Count != 0) {
- y.Description = temp.containers.cna.descriptions[0];
- }
- }
- finally {
- results.Add(y);
- }
- }
- // return's
- if (results.Count > 0) {
- JsonLdObject resultAsJsonLd = new JsonLdObject() {
- Context = "https://localhost:7203/views/cveResult",
- Data = results
- };
- return Ok(resultAsJsonLd);
- }
- else {
- return NoContent();
- }
- }
- }
-
- ///
- /// Search for a list of packages.
- /// Not useable in swagger because of body - but curl works fine.
- ///
- /// List of tuple: package, version
- /// OK, if exists. OK, if no package list searched. NoContent if not found.
- [HttpGet]
- [Route("checkPackageList")]
- public async Task CheckPackageListAsync([FromBody] List packages) {
- if (!(this.Request.Headers.Accept.Equals("application/json") || this.Request.Headers.Accept.Equals("*/*"))) {
- return StatusCode(406);
- }
- List results = [];
- using (Operation.Time($"Complete Time for Query-Search after List of Packages")) {
- foreach (PackageForApi x in packages) {
- DataTable dtResult = SearchInMySql(x.PackageName);
- // convert the result
- foreach (DataRow y in dtResult.Rows) {
- CveResult z = new CveResult() {
- CveNumber = y["cve_number"].ToString() ?? "",
- Designation = y["designation"].ToString() ?? "",
- Version = y["version_affected"].ToString() ?? ""
- };
- CVEcomp temp = JsonConvert.DeserializeObject(y["full_text"].ToString() ?? string.Empty) ?? new CVEcomp();
- try {
- if (temp.containers.cna.metrics.Count != 0) {
- z.CvssV31 = temp.containers.cna.metrics[0].cvssV3_1;
- }
- if (temp.containers.cna.descriptions.Count != 0) {
- z.Description = temp.containers.cna.descriptions[0];
- }
- }
- finally {
- results.Add(z);
- }
- }
- }
- }
-
- JsonLdObject resultAsJsonLd = new JsonLdObject() {
- Context = "https://localhost:7203/views/cveResult",
- Data = results
- };
- return Ok(results.Count == 0 ? "No result" : resultAsJsonLd);
- }
-
- [HttpGet]
- [Route("checkGuid")]
- public IActionResult CheckDownloadedProjectWithGuid([FromQuery] Guid projectGuid) {
- // MySql Connection
- MySqlConnection connection = new MySqlConnection(Configuration["ConnectionStrings:cvedb"]);
-
- MySqlCommand cmd = new MySqlCommand($"" +
- $"SELECT * " +
- $"FROM repositories " +
- $"WHERE guid='{projectGuid}';", connection);
-
- DataTable dataTable = new DataTable();
- connection.Open();
- MySqlDataReader reader = cmd.ExecuteReader();
- dataTable.Load(reader);
- connection.Close();
-
- if (dataTable.Rows.Count == 1) {
- object res = new {
- guid = dataTable.Rows[0]["guid"].ToString(),
- repoUrl = dataTable.Rows[0]["repoUrl"].ToString(),
- repoOwner = dataTable.Rows[0]["repoOwner"].ToString(),
- repoDesignation = dataTable.Rows[0]["repoDesignation"].ToString(),
- tag = dataTable.Rows[0]["tag"].ToString()
- };
- return Ok(res);
- }
- else {
- return NotFound("Not found");
- }
- }
- #endregion
-
- #region Internal function(s)
- ///
- /// Adds file names of all files of a folder and its subfolders to a list
- ///
- /// path to target folder
- /// list of files
- private static void ExploreFolder(string folderPath, List fileList) {
- try {
- fileList.AddRange(Directory.GetFiles(folderPath));
-
- foreach (string subfolder in Directory.GetDirectories(folderPath)) {
- ExploreFolder(subfolder, fileList);
- }
- }
- catch (Exception ex) {
- Console.WriteLine($"{ex.Message}");
- }
- }
-
- /// Search package in raw-json data
- /// Name of package to search
- /// List of CveResults
- private List SearchInJson(string packageName) {
- List fileList = new List();
- List indexToDelete = new List();
- string path = $"{AppDomain.CurrentDomain.BaseDirectory}raw";
- ExploreFolder(path, fileList);
-
- foreach (int i in Enumerable.Range(0, fileList.Count)) {
- if (!Regex.IsMatch(fileList[i], @"CVE-[-\S]+.json")) {
- indexToDelete.Add(i);
- }
- }
- foreach (int i in Enumerable.Range(0, indexToDelete.Count)) {
- fileList.RemoveAt(indexToDelete[i] - i);
- }
- // search in the files
- List results = [];
- using (Operation.Time($"Package \"{packageName}\"")) {
- int start = 0;
- foreach (int i in Enumerable.Range(start, fileList.Count - start)) {
- CVEcomp item = JsonConvert.DeserializeObject(System.IO.File.ReadAllText(fileList[i]))!;
- if (i % 100 == 0) {
- Console.WriteLine(fileList[i] + " - " + i);
- }
- if (item.containers.cna.affected is null || item.containers.cna.affected.Any(x => x.product is null)) {
- continue;
- }
- if (item.containers.cna.affected.Any(y => y.product.Equals(packageName))) {
- foreach (int j in Enumerable.Range(0, item.containers.cna.affected.Count)) {
- foreach (Modells.Version version in item.containers.cna.affected[j].versions) {
- results.Add(new CveResult() {
- CveNumber = item.cveMetadata.cveId,
- Version = version.version,
- });
- }
- }
- }
- }
- }
- return results;
- }
-
- private DataTable SearchInMySql(string packageName) {
- // MySql Connection
- MySqlConnection connection = new MySqlConnection(Configuration["ConnectionStrings:cvedb"]);
-
- MySqlCommand cmd = new MySqlCommand($"" +
- $"SELECT cve_number, designation, version_affected, full_text " +
- $"FROM cve.cve " +
- $"WHERE designation='{packageName}';", connection);
-
- DataTable dataTable = new DataTable();
- using (Operation.Time($"Query-Time for Package \"{packageName}\"")) {
- // read the result
- connection.Open();
- MySqlDataReader reader = cmd.ExecuteReader();
- dataTable.Load(reader);
- connection.Close();
- }
- return dataTable;
- }
- #endregion
- }
-}
+// connection.Open();
+// cmdIndexDrop.ExecuteNonQuery();
+// connection.Close();
+
+// //start insert/update in MySQL
+// int insertAndUpdateIndex = 0;
+// foreach (string x in fileList) {
+// string insertIntoString = "INSERT INTO cve(cve_number, designation, version_affected, full_text) " +
+// "VALUES(@cve, @des, @ver, @ful) " +
+// "ON DUPLICATE KEY UPDATE " +
+// "version_affected = @ver, " +
+// "full_text = @ful;" ;
+// MySqlCommand cmdInsert = new MySqlCommand(insertIntoString, connection);
+
+// string json = System.IO.File.ReadAllText(x);
+// CVEcomp cve = JsonConvert.DeserializeObject(json)!;
+
+// string affected = "";
+// foreach (Affected y in cve.containers.cna.affected) {
+// foreach (Modells.Version z in y.versions) {
+// affected += z.version + $"({z.status}) |";
+// }
+// }
+// if (affected.Length > 25_000) {
+// affected = "to long -> view full_text";
+// }
+// string product = "| ";
+// try {
+// foreach (Affected singleProduct in cve.containers.cna.affected) {
+// product += singleProduct.product + " | ";
+// }
+// if (product.Length > 1000) {
+// product = product[0..1000];
+// }
+// if (product.Equals("| ")) {
+// product = "n/a";
+// }
+// }
+// catch {
+// product = "n/a";
+// }
+// cmdInsert.Parameters.AddWithValue("@cve", cve.cveMetadata.cveId);
+// cmdInsert.Parameters.AddWithValue("@des", product);
+// cmdInsert.Parameters.AddWithValue("@ver", affected);
+// cmdInsert.Parameters.AddWithValue("@ful", JsonConvert.SerializeObject(cve, Formatting.None));
+
+// connection.Open();
+// insertAndUpdateIndex += cmdInsert.ExecuteNonQuery();
+// connection.Close();
+// }
+
+// //connection.Open();
+// //MySqlCommand cmdIndexCreated = new MySqlCommand("CREATE INDEX idx_designation ON cve (designation);", connection);
+// //cmdIndexCreated.ExecuteNonQuery();
+// //connection.Close();
+
+// return Ok(insertAndUpdateIndex);
+// }
+// catch (Exception ex) {
+// return BadRequest(ex.StackTrace + "\n\n" + ex.Message);
+// }
+// }
+// }
+
+// /// Return the full text of a cve, when it is requested.
+// ///
+// ///
+// //[HttpGet]
+// //[Route("getFullTextFromCveNumber")]
+// public IActionResult GetFullTextCve([FromQuery] string? cve_number) {
+// if (!(this.Request.Headers.Accept.Equals("application/json") || this.Request.Headers.Accept.Equals("*/*"))) {
+// return StatusCode(406);
+// }
+// using (Operation.Time("GetFullTextCve")) {
+// if (cve_number is null) {
+// return BadRequest("Empty cve_number");
+// }
+// try {
+// // MySql Connection
+// MySqlConnection connection = new MySqlConnection(Configuration["ConnectionStrings:cvedb"]);
+
+// connection.Open();
+// MySqlCommand cmdIndexCreated = new MySqlCommand($"" +
+// $"SELECT full_text " +
+// $"FROM cve.cve " +
+// $"WHERE cve_number = '{cve_number}';", connection);
+// MySqlDataReader reader = cmdIndexCreated.ExecuteReader();
+// DataTable resDataTable = new DataTable();
+// resDataTable.Load(reader);
+// connection.Close();
+
+// if (resDataTable.Rows.Count == 0) {
+// return NoContent();
+// }
+
+// CVEcomp? cVEcomp = JsonConvert.DeserializeObject(resDataTable.Rows[0]["full_text"].ToString()!);
+
+// return Ok(cVEcomp);
+// }
+// catch (Exception ex) {
+// return BadRequest(ex.StackTrace + "\n\n" + ex.Message);
+
+// }
+// }
+// }
+
+// /// Check for an cve entry of a package with all its versions
+// /// Name of package to search
+// /// true: search db, false: search raw-json
+// /// Version of package to search
+// /// Ok with result. NoContent if empty.
+// //[HttpGet]
+// //[Route("checkSinglePackage")]
+// public IActionResult CheckSinglePackage([FromQuery] string PackageName,
+// [FromQuery] string? PackageVersion) {
+// if (!(this.Request.Headers.Accept.Equals("application/json") || this.Request.Headers.Accept.Equals("*/*"))) {
+// return StatusCode(406);
+// }
+// using (Operation.Time($"Complete Time for Query-SingleSearch after Package \"{PackageName}\"")) {
+// List results = [];
+// DataTable dtResult = SearchInMySql(PackageName);
+// // convert the result
+// foreach (DataRow x in dtResult.Rows) {
+// CveResult y = new CveResult() {
+// CveNumber = x["cve_number"].ToString() ?? "",
+// Designation = x["designation"].ToString() ?? "",
+// Version = x["version_affected"].ToString() ?? ""
+// };
+// CVEcomp temp = JsonConvert.DeserializeObject(x["full_text"].ToString() ?? string.Empty) ?? new CVEcomp();
+// try {
+// if (temp.containers.cna.metrics.Count != 0) {
+// y.CvssV31 = temp.containers.cna.metrics[0].cvssV3_1;
+// }
+// if (temp.containers.cna.descriptions.Count != 0) {
+// y.Description = temp.containers.cna.descriptions[0];
+// }
+// }
+// finally {
+// results.Add(y);
+// }
+// }
+// // return's
+// if (results.Count > 0) {
+// JsonLdObject resultAsJsonLd = new JsonLdObject() {
+// Context = "https://localhost:7203/views/cveResult",
+// Data = results
+// };
+// return Ok(resultAsJsonLd);
+// }
+// else {
+// return NoContent();
+// }
+// }
+// }
+
+// ///
+// /// Search for a list of packages.
+// /// Not useable in swagger because of body - but curl works fine.
+// ///
+// /// List of tuple: package, version
+// /// OK, if exists. OK, if no package list searched. NoContent if not found.
+// //[HttpGet]
+// //[Route("checkPackageList")]
+// public async Task CheckPackageListAsync([FromBody] List packages) {
+// if (!(this.Request.Headers.Accept.Equals("application/json") || this.Request.Headers.Accept.Equals("*/*"))) {
+// return StatusCode(406);
+// }
+// List results = [];
+// using (Operation.Time($"Complete Time for Query-Search after List of Packages")) {
+// foreach (PackageForApi x in packages) {
+// DataTable dtResult = SearchInMySql(x.PackageName);
+// // convert the result
+// foreach (DataRow y in dtResult.Rows) {
+// CveResult z = new CveResult() {
+// CveNumber = y["cve_number"].ToString() ?? "",
+// Designation = y["designation"].ToString() ?? "",
+// Version = y["version_affected"].ToString() ?? ""
+// };
+// CVEcomp temp = JsonConvert.DeserializeObject(y["full_text"].ToString() ?? string.Empty) ?? new CVEcomp();
+// try {
+// if (temp.containers.cna.metrics.Count != 0) {
+// z.CvssV31 = temp.containers.cna.metrics[0].cvssV3_1;
+// }
+// if (temp.containers.cna.descriptions.Count != 0) {
+// z.Description = temp.containers.cna.descriptions[0];
+// }
+// }
+// finally {
+// results.Add(z);
+// }
+// }
+// }
+// }
+
+// JsonLdObject resultAsJsonLd = new JsonLdObject() {
+// Context = "https://localhost:7203/views/cveResult",
+// Data = results
+// };
+// return Ok(results.Count == 0 ? "No result" : resultAsJsonLd);
+// }
+
+// //[HttpGet]
+// //[Route("checkGuid")]
+// public IActionResult CheckDownloadedProjectWithGuid([FromQuery] Guid projectGuid) {
+// // MySql Connection
+// MySqlConnection connection = new MySqlConnection(Configuration["ConnectionStrings:cvedb"]);
+
+// MySqlCommand cmd = new MySqlCommand($"" +
+// $"SELECT * " +
+// $"FROM repositories " +
+// $"WHERE guid='{projectGuid}';", connection);
+
+// DataTable dataTable = new DataTable();
+// connection.Open();
+// MySqlDataReader reader = cmd.ExecuteReader();
+// dataTable.Load(reader);
+// connection.Close();
+
+// if (dataTable.Rows.Count == 1) {
+// object res = new {
+// guid = dataTable.Rows[0]["guid"].ToString(),
+// repoUrl = dataTable.Rows[0]["repoUrl"].ToString(),
+// repoOwner = dataTable.Rows[0]["repoOwner"].ToString(),
+// repoDesignation = dataTable.Rows[0]["repoDesignation"].ToString(),
+// tag = dataTable.Rows[0]["tag"].ToString()
+// };
+// return Ok(res);
+// }
+// else {
+// return NotFound("Not found");
+// }
+// }
+// #endregion
+
+// #region Internal function(s)
+// ///
+// /// Adds file names of all files of a folder and its subfolders to a list
+// ///
+// /// path to target folder
+// /// list of files
+// private static void ExploreFolder(string folderPath, List fileList) {
+// try {
+// fileList.AddRange(Directory.GetFiles(folderPath));
+
+// foreach (string subfolder in Directory.GetDirectories(folderPath)) {
+// ExploreFolder(subfolder, fileList);
+// }
+// }
+// catch (Exception ex) {
+// Console.WriteLine($"{ex.Message}");
+// }
+// }
+
+// /// Search package in raw-json data
+// /// Name of package to search
+// /// List of CveResults
+// private List SearchInJson(string packageName) {
+// List fileList = new List();
+// List indexToDelete = new List();
+// string path = $"{AppDomain.CurrentDomain.BaseDirectory}raw";
+// ExploreFolder(path, fileList);
+
+// foreach (int i in Enumerable.Range(0, fileList.Count)) {
+// if (!Regex.IsMatch(fileList[i], @"CVE-[-\S]+.json")) {
+// indexToDelete.Add(i);
+// }
+// }
+// foreach (int i in Enumerable.Range(0, indexToDelete.Count)) {
+// fileList.RemoveAt(indexToDelete[i] - i);
+// }
+// // search in the files
+// List results = [];
+// using (Operation.Time($"Package \"{packageName}\"")) {
+// int start = 0;
+// foreach (int i in Enumerable.Range(start, fileList.Count - start)) {
+// CVEcomp item = JsonConvert.DeserializeObject(System.IO.File.ReadAllText(fileList[i]))!;
+// if (i % 100 == 0) {
+// Console.WriteLine(fileList[i] + " - " + i);
+// }
+// if (item.containers.cna.affected is null || item.containers.cna.affected.Any(x => x.product is null)) {
+// continue;
+// }
+// if (item.containers.cna.affected.Any(y => y.product.Equals(packageName))) {
+// foreach (int j in Enumerable.Range(0, item.containers.cna.affected.Count)) {
+// foreach (Modells.Version version in item.containers.cna.affected[j].versions) {
+// results.Add(new CveResult() {
+// CveNumber = item.cveMetadata.cveId,
+// Version = version.version,
+// });
+// }
+// }
+// }
+// }
+// }
+// return results;
+// }
+
+// private DataTable SearchInMySql(string packageName) {
+// // MySql Connection
+// MySqlConnection connection = new MySqlConnection(Configuration["ConnectionStrings:cvedb"]);
+
+// MySqlCommand cmd = new MySqlCommand($"" +
+// $"SELECT cve_number, designation, version_affected, full_text " +
+// $"FROM cve.cve " +
+// $"WHERE designation='{packageName}';", connection);
+
+// DataTable dataTable = new DataTable();
+// using (Operation.Time($"Query-Time for Package \"{packageName}\"")) {
+// // read the result
+// connection.Open();
+// MySqlDataReader reader = cmd.ExecuteReader();
+// dataTable.Load(reader);
+// connection.Close();
+// }
+// return dataTable;
+// }
+// #endregion
+// }
+//}
diff --git a/code/AmIVulnerable/AmIVulnerable/Controllers/DependeciesController.cs b/code/AmIVulnerable/AmIVulnerable/Controllers/DependeciesController.cs
index bc1de8a..ff51634 100644
--- a/code/AmIVulnerable/AmIVulnerable/Controllers/DependeciesController.cs
+++ b/code/AmIVulnerable/AmIVulnerable/Controllers/DependeciesController.cs
@@ -1,309 +1,310 @@
-using Microsoft.AspNetCore.Mvc;
-using Modells;
-using Modells.Packages;
-using MySql.Data.MySqlClient;
-using Newtonsoft.Json;
-using SerilogTimings;
-using System.Data;
-using System.Diagnostics;
-using System.Text.Json;
-using F = System.IO.File;
+//using Microsoft.AspNetCore.Mvc;
+//using Modells;
+//using Modells.Packages;
+//using MySql.Data.MySqlClient;
+//using Newtonsoft.Json;
+//using SerilogTimings;
+//using System.Data;
+//using System.Diagnostics;
+//using System.Text.Json;
+//using F = System.IO.File;
-namespace AmIVulnerable.Controllers {
+//namespace AmIVulnerable.Controllers {
- [Route("api/[controller]")]
- [ApiController]
- public class DependeciesController : ControllerBase {
+// //[Route("api/[controller]")]
+// //[ApiController]
- #region Config
- private readonly IConfiguration Configuration;
+// public class DependeciesController : ControllerBase {
- public DependeciesController(IConfiguration configuration) {
- Configuration = configuration;
- }
- #endregion
+// #region Config
+// private readonly IConfiguration Configuration;
- ///
- /// Extract dependecies of different project types as json
- ///
- /// Type of project to extract dependencies from
- /// OK if known project type. BadRequest if unknown project type.
- [HttpPost]
- [Route("extractTree")]
- public IActionResult ExtractDependencies([FromQuery] ProjectType projectType,
- [FromQuery] Guid projectGuid) {
- if (!(this.Request.Headers.Accept.Equals("application/json") || this.Request.Headers.Accept.Equals("*/*"))) {
- return StatusCode(406);
- }
- if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + projectGuid.ToString())) {
- return BadRequest("ProjectGuid does not exist.");
- }
- switch (projectType) {
- case ProjectType.NodeJs: {
- ExecuteCommand("npm", "install", projectGuid.ToString());
- ExecuteCommand("rm", "tree.json", projectGuid.ToString());
- ExecuteCommand("npm", "list --all --json >> tree.json", projectGuid.ToString());
- List resTree = ExtractTree(AppDomain.CurrentDomain.BaseDirectory + projectGuid.ToString() + "/tree.json");
- F.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + projectGuid.ToString() + "/depTree.json", JsonConvert.SerializeObject(resTree));
+// public DependeciesController(IConfiguration configuration) {
+// Configuration = configuration;
+// }
+// #endregion
- JsonLdObject resultAsJsonLd = new JsonLdObject() {
- Context = "https://localhost:7203/views/nodePackageResult",
- Data = resTree
- };
- return Ok(resultAsJsonLd);
- }
- default: {
- return BadRequest();
- }
- }
- }
+// ///
+// /// Extract dependecies of different project types as json
+// ///
+// /// Type of project to extract dependencies from
+// /// OK if known project type. BadRequest if unknown project type.
+// //[HttpPost]
+// //[Route("extractTree")]
+// public IActionResult ExtractDependencies([FromQuery] ProjectType projectType,
+// [FromQuery] Guid projectGuid) {
+// if (!(this.Request.Headers.Accept.Equals("application/json") || this.Request.Headers.Accept.Equals("*/*"))) {
+// return StatusCode(406);
+// }
+// if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + projectGuid.ToString())) {
+// return BadRequest("ProjectGuid does not exist.");
+// }
+// switch (projectType) {
+// case ProjectType.NodeJs: {
+// ExecuteCommand("npm", "install", projectGuid.ToString());
+// ExecuteCommand("rm", "tree.json", projectGuid.ToString());
+// ExecuteCommand("npm", "list --all --json >> tree.json", projectGuid.ToString());
+// List resTree = ExtractTree(AppDomain.CurrentDomain.BaseDirectory + projectGuid.ToString() + "/tree.json");
+// F.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + projectGuid.ToString() + "/depTree.json", JsonConvert.SerializeObject(resTree));
- ///
- /// Extract dependecies of different project types as json and extract resulting dependency trees of vulnerabilities
- ///
- /// Type of project to extract dependencies from
- /// OK if vulnerability found. 299 if no vulnerability found. BadRequest if unknown project type is searched.
- [HttpPost]
- [Route("extractAndAnalyzeTree")]
- public async Task ExtractAndAnalyzeTreeAsync([FromQuery] ProjectType projectType,
- [FromQuery] Guid projectGuid) {
- if (!(this.Request.Headers.Accept.Equals("application/json") || this.Request.Headers.Accept.Equals("*/*"))) {
- return StatusCode(406);
- }
- using (Operation.Time($"ExtractAndAnalyzeTreeAsync called with procjectType {projectType}")) {
- if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + projectGuid.ToString())) {
- return BadRequest("ProjectGuid does not exist.");
- }
- switch (projectType) {
- case ProjectType.NodeJs: {
- ExecuteCommand("npm", "install", projectGuid.ToString());
- ExecuteCommand("rm", "tree.json", projectGuid.ToString());
- ExecuteCommand("npm", "list --all --json >> tree.json", projectGuid.ToString());
- List depTree = ExtractTree(AppDomain.CurrentDomain.BaseDirectory + projectGuid.ToString() + "/tree.json");
- List resTree = await AnalyzeTreeAsync(depTree) ?? [];
- if (resTree.Count != 0) {
- JsonLdObject resultAsJsonLd = new JsonLdObject() {
- Context = "https://localhost:7203/views/nodePackageResult",
- Data = resTree
- };
- return Ok(resultAsJsonLd);
- }
- else {
- return StatusCode(299, "Keine Schwachstelle gefunden.");
- }
- }
- default: {
- return BadRequest();
- }
- }
- }
- }
+// JsonLdObject resultAsJsonLd = new JsonLdObject() {
+// Context = "https://localhost:7203/views/nodePackageResult",
+// Data = resTree
+// };
+// return Ok(resultAsJsonLd);
+// }
+// default: {
+// return BadRequest();
+// }
+// }
+// }
- ///
- /// Starts a process that runs a command.
- ///
- /// Programm used for commands
- /// Command used for programm
- private void ExecuteCommand(string prog, string command, string dir) {
- ProcessStartInfo process = new ProcessStartInfo {
- FileName = "cmd",
- RedirectStandardInput = true,
- WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory + dir,
- };
- Process runProcess = Process.Start(process)!;
- runProcess.StandardInput.WriteLine($"{prog} {command}");
- runProcess.StandardInput.WriteLine($"exit");
- runProcess.WaitForExit();
- }
+// ///
+// /// Extract dependecies of different project types as json and extract resulting dependency trees of vulnerabilities
+// ///
+// /// Type of project to extract dependencies from
+// /// OK if vulnerability found. 299 if no vulnerability found. BadRequest if unknown project type is searched.
+// //[HttpPost]
+// //[Route("extractAndAnalyzeTree")]
+// public async Task ExtractAndAnalyzeTreeAsync([FromQuery] ProjectType projectType,
+// [FromQuery] Guid projectGuid) {
+// if (!(this.Request.Headers.Accept.Equals("application/json") || this.Request.Headers.Accept.Equals("*/*"))) {
+// return StatusCode(406);
+// }
+// using (Operation.Time($"ExtractAndAnalyzeTreeAsync called with procjectType {projectType}")) {
+// if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + projectGuid.ToString())) {
+// return BadRequest("ProjectGuid does not exist.");
+// }
+// switch (projectType) {
+// case ProjectType.NodeJs: {
+// ExecuteCommand("npm", "install", projectGuid.ToString());
+// ExecuteCommand("rm", "tree.json", projectGuid.ToString());
+// ExecuteCommand("npm", "list --all --json >> tree.json", projectGuid.ToString());
+// List depTree = ExtractTree(AppDomain.CurrentDomain.BaseDirectory + projectGuid.ToString() + "/tree.json");
+// List resTree = await AnalyzeTreeAsync(depTree) ?? [];
+// if (resTree.Count != 0) {
+// JsonLdObject resultAsJsonLd = new JsonLdObject() {
+// Context = "https://localhost:7203/views/nodePackageResult",
+// Data = resTree
+// };
+// return Ok(resultAsJsonLd);
+// }
+// else {
+// return StatusCode(299, "Keine Schwachstelle gefunden.");
+// }
+// }
+// default: {
+// return BadRequest();
+// }
+// }
+// }
+// }
- ///
- /// Extracts a tree from node project
- ///
- /// File path to rawAnalyze/tree.json
- /// List of vulnerable packages.
- private List ExtractTree(string filePath) {
- List packages = [];
- using (JsonDocument jsonDocument = JsonDocument.Parse(F.ReadAllText(filePath))) {
- if (jsonDocument.RootElement.TryGetProperty("dependencies", out JsonElement dependenciesElement) &&
- dependenciesElement.ValueKind == JsonValueKind.Object) {
- foreach (JsonProperty dependency in dependenciesElement.EnumerateObject()) {
- NodePackage nodePackage = ExtractDependencyInfo(dependency);
+// ///
+// /// Starts a process that runs a command.
+// ///
+// /// Programm used for commands
+// /// Command used for programm
+// private void ExecuteCommand(string prog, string command, string dir) {
+// ProcessStartInfo process = new ProcessStartInfo {
+// FileName = "cmd",
+// RedirectStandardInput = true,
+// WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory + dir,
+// };
+// Process runProcess = Process.Start(process)!;
+// runProcess.StandardInput.WriteLine($"{prog} {command}");
+// runProcess.StandardInput.WriteLine($"exit");
+// runProcess.WaitForExit();
+// }
- packages.Add(nodePackage);
- }
- }
- }
- return packages;
- }
+// ///
+// /// Extracts a tree from node project
+// ///
+// /// File path to rawAnalyze/tree.json
+// /// List of vulnerable packages.
+// private List ExtractTree(string filePath) {
+// List packages = [];
+// using (JsonDocument jsonDocument = JsonDocument.Parse(F.ReadAllText(filePath))) {
+// if (jsonDocument.RootElement.TryGetProperty("dependencies", out JsonElement dependenciesElement) &&
+// dependenciesElement.ValueKind == JsonValueKind.Object) {
+// foreach (JsonProperty dependency in dependenciesElement.EnumerateObject()) {
+// Package nodePackage = ExtractDependencyInfo(dependency);
- ///
- /// Extracts dependencies of a single dependency.
- ///
- /// Dependency that is searched for sundependencies and versions.
- /// NodePackage with all found dependencies and versions.
- private NodePackage ExtractDependencyInfo(JsonProperty dependency) {
- NodePackage nodePackage = new NodePackage {
- Name = dependency.Name
- };
- if (dependency.Value.TryGetProperty("version", out JsonElement versionElement) &&
- versionElement.ValueKind == JsonValueKind.String) {
- nodePackage.Version = versionElement.GetString() ?? "";
- }
- if (dependency.Value.TryGetProperty("dependencies", out JsonElement subDependenciesElement) &&
- subDependenciesElement.ValueKind == JsonValueKind.Object) {
- foreach (JsonProperty subDependency in subDependenciesElement.EnumerateObject()) {
- NodePackage subNodePackage = ExtractDependencyInfo(subDependency);
- nodePackage.Dependencies.Add(subNodePackage);
- }
- }
+// packages.Add(nodePackage);
+// }
+// }
+// }
+// return packages;
+// }
- return nodePackage;
- }
+// ///
+// /// Extracts dependencies of a single dependency.
+// ///
+// /// Dependency that is searched for sundependencies and versions.
+// /// NodePackage with all found dependencies and versions.
+// private Package ExtractDependencyInfo(JsonProperty dependency) {
+// Package nodePackage = new Package {
+// Name = dependency.Name
+// };
+// if (dependency.Value.TryGetProperty("version", out JsonElement versionElement) &&
+// versionElement.ValueKind == JsonValueKind.String) {
+// nodePackage.Version = versionElement.GetString() ?? "";
+// }
+// if (dependency.Value.TryGetProperty("dependencies", out JsonElement subDependenciesElement) &&
+// subDependenciesElement.ValueKind == JsonValueKind.Object) {
+// foreach (JsonProperty subDependency in subDependenciesElement.EnumerateObject()) {
+// Package subNodePackage = ExtractDependencyInfo(subDependency);
+// nodePackage.Dependencies.Add(subNodePackage);
+// }
+// }
- ///
- /// Analyse list of node packages, compare dependencies of each with cve and return list of NodePackageResult
- ///
- /// List of all top level node packages.
- /// List of NodePackageResult.
- private async Task> AnalyzeTreeAsync(List depTree) {
- List> nodePackages = [];
- // preperation list
- foreach (NodePackage x in depTree) {
- List y = AnalyzeSubtree(x);
- foreach (NodePackage z in y) {
- Tuple tuple = new Tuple(z.Name, z.Version);
- if (!nodePackages.Contains(tuple)) {
- nodePackages.Add(tuple);
- }
- }
- }
+// return nodePackage;
+// }
- // analyze list
- List cveResults = [];
- foreach (Tuple x in nodePackages) {
- DataTable dtResult = SearchInMySql(x.Item1);
- // convert the result
- foreach (DataRow y in dtResult.Rows) {
- CveResult z = new CveResult() {
- CveNumber = y["cve_number"].ToString() ?? "",
- Designation = y["designation"].ToString() ?? "",
- Version = y["version_affected"].ToString() ?? ""
- };
- CVEcomp temp = JsonConvert.DeserializeObject(y["full_text"].ToString() ?? string.Empty) ?? new CVEcomp();
- try {
- if (temp.containers.cna.metrics.Count != 0) {
- z.CvssV31 = temp.containers.cna.metrics[0].cvssV3_1;
- }
- if (temp.containers.cna.descriptions.Count != 0) {
- z.Description = temp.containers.cna.descriptions[0];
- }
- }
- finally {
- cveResults.Add(z);
- }
- }
- }
+// ///
+// /// Analyse list of node packages, compare dependencies of each with cve and return list of NodePackageResult
+// ///
+// /// List of all top level node packages.
+// /// List of NodePackageResult.
+// private async Task> AnalyzeTreeAsync(List depTree) {
+// List> nodePackages = [];
+// // preperation list
+// foreach (Package x in depTree) {
+// List y = AnalyzeSubtree(x);
+// foreach (Package z in y) {
+// Tuple tuple = new Tuple(z.Name, z.Version);
+// if (!nodePackages.Contains(tuple)) {
+// nodePackages.Add(tuple);
+// }
+// }
+// }
- // find the critical points
- if (cveResults.Count == 0) {
- return null;
- }
- List resulstList = [];
- foreach (NodePackage x in depTree) {
- NodePackageResult? temp = CheckVulnerabilities(x, cveResults);
- if (temp is not null) {
- resulstList.Add(temp);
- }
- }
- return resulstList;
- }
+// // analyze list
+// List cveResults = [];
+// foreach (Tuple x in nodePackages) {
+// DataTable dtResult = SearchInMySql(x.Item1);
+// // convert the result
+// foreach (DataRow y in dtResult.Rows) {
+// CveResult z = new CveResult() {
+// CveNumber = y["cve_number"].ToString() ?? "",
+// Designation = y["designation"].ToString() ?? "",
+// Version = y["version_affected"].ToString() ?? ""
+// };
+// CVEcomp temp = JsonConvert.DeserializeObject(y["full_text"].ToString() ?? string.Empty) ?? new CVEcomp();
+// try {
+// if (temp.containers.cna.metrics.Count != 0) {
+// z.CvssV31 = temp.containers.cna.metrics[0].cvssV3_1;
+// }
+// if (temp.containers.cna.descriptions.Count != 0) {
+// z.Description = temp.containers.cna.descriptions[0];
+// }
+// }
+// finally {
+// cveResults.Add(z);
+// }
+// }
+// }
- ///
- /// Searches for all node package dependencies of a single node package.
- ///
- /// Node package to search
- /// List of all node package dependencies of a single node package.
- private List AnalyzeSubtree(NodePackage nodePackage) {
- List res = [];
- foreach (NodePackage x in nodePackage.Dependencies) {
- res.AddRange(AnalyzeSubtree(x));
- }
- res.Add(nodePackage);
- return res;
- }
+// // find the critical points
+// if (cveResults.Count == 0) {
+// return null;
+// }
+// List resulstList = [];
+// foreach (Package x in depTree) {
+// PackageResult? temp = CheckVulnerabilities(x, cveResults);
+// if (temp is not null) {
+// resulstList.Add(temp);
+// }
+// }
+// return resulstList;
+// }
- ///
- /// Compares node package dependencies with cve data.
- ///
- /// Package to search for cve tracked dependencies.
- /// List of CveResult data.
- /// NodePackageResult with all dependencies and status if it is a cve tracked dependency.
- private NodePackageResult? CheckVulnerabilities(NodePackage package, List cveData) {
- NodePackageResult r = new NodePackageResult() {
- Name = "",
- isCveTracked = false
- };
- foreach (NodePackage x in package.Dependencies) {
- NodePackageResult? temp = CheckVulnerabilities(x, cveData);
- if (temp is not null) {
- r.Dependencies.Add(temp);
- }
- }
- foreach (CveResult x in cveData) { // check
- if (x.Designation.Equals(package.Name)) {
- r.isCveTracked = true;
- r.CvssV31 = x.CvssV31;
- r.Description = x.Description;
- }
- }
- if (r.isCveTracked == false && !DepCheck(r)) {
- return null;
- }
- r.Name = package.Name;
- r.Version = package.Version;
- return r;
- }
+// ///
+// /// Searches for all node package dependencies of a single node package.
+// ///
+// /// Node package to search
+// /// List of all node package dependencies of a single node package.
+// private List AnalyzeSubtree(Package nodePackage) {
+// List res = [];
+// foreach (Package x in nodePackage.Dependencies) {
+// res.AddRange(AnalyzeSubtree(x));
+// }
+// res.Add(nodePackage);
+// return res;
+// }
- ///
- /// If Package is cve tracked, return true. Check all dependencies recursively.
- ///
- ///
- /// True if any dependency is tracked. False if no dependencies are tracked.
- private bool DepCheck(NodePackageResult package) {
- foreach (NodePackageResult x in package.Dependencies) {
- bool isTracked = DepCheck(x);
- if (isTracked) {
- goto isTrue;
- }
- }
- if (package.isCveTracked) {
- return true;
- }
- else {
- return false;
- }
- isTrue:
- return true;
- }
+// ///
+// /// Compares node package dependencies with cve data.
+// ///
+// /// Package to search for cve tracked dependencies.
+// /// List of CveResult data.
+// /// NodePackageResult with all dependencies and status if it is a cve tracked dependency.
+// private PackageResult? CheckVulnerabilities(Package package, List cveData) {
+// PackageResult r = new PackageResult() {
+// Name = "",
+// isCveTracked = false
+// };
+// foreach (Package x in package.Dependencies) {
+// PackageResult? temp = CheckVulnerabilities(x, cveData);
+// if (temp is not null) {
+// r.Dependencies.Add(temp);
+// }
+// }
+// foreach (CveResult x in cveData) { // check
+// if (x.Designation.Equals(package.Name)) {
+// r.isCveTracked = true;
+// r.CvssV31 = x.CvssV31;
+// r.Description = x.Description;
+// }
+// }
+// if (r.isCveTracked == false && !DepCheck(r)) {
+// return null;
+// }
+// r.Name = package.Name;
+// r.Version = package.Version;
+// return r;
+// }
- private DataTable SearchInMySql(string packageName) {
- // MySql Connection
- MySqlConnection connection = new MySqlConnection(Configuration["ConnectionStrings:cvedb"]);
+// ///
+// /// If Package is cve tracked, return true. Check all dependencies recursively.
+// ///
+// ///
+// /// True if any dependency is tracked. False if no dependencies are tracked.
+// private bool DepCheck(PackageResult package) {
+// foreach (PackageResult x in package.Dependencies) {
+// bool isTracked = DepCheck(x);
+// if (isTracked) {
+// goto isTrue;
+// }
+// }
+// if (package.isCveTracked) {
+// return true;
+// }
+// else {
+// return false;
+// }
+// isTrue:
+// return true;
+// }
- MySqlCommand cmd = new MySqlCommand($"" +
- $"SELECT cve_number, designation, version_affected, full_text " +
- $"FROM cve.cve " +
- $"WHERE designation='{packageName}';", connection);
+// private DataTable SearchInMySql(string packageName) {
+// // MySql Connection
+// MySqlConnection connection = new MySqlConnection(Configuration["ConnectionStrings:cvedb"]);
- DataTable dataTable = new DataTable();
- using (Operation.Time($"Query-Time for Package \"{packageName}\"")) {
- // read the result
- connection.Open();
- MySqlDataReader reader = cmd.ExecuteReader();
- dataTable.Load(reader);
- connection.Close();
- }
- return dataTable;
- }
- }
-}
+// MySqlCommand cmd = new MySqlCommand($"" +
+// $"SELECT cve_number, designation, version_affected, full_text " +
+// $"FROM cve.cve " +
+// $"WHERE designation='{packageName}';", connection);
+
+// DataTable dataTable = new DataTable();
+// using (Operation.Time($"Query-Time for Package \"{packageName}\"")) {
+// // read the result
+// connection.Open();
+// MySqlDataReader reader = cmd.ExecuteReader();
+// dataTable.Load(reader);
+// connection.Close();
+// }
+// return dataTable;
+// }
+// }
+//}
diff --git a/code/AmIVulnerable/AmIVulnerable/Controllers/GitController.cs b/code/AmIVulnerable/AmIVulnerable/Controllers/GitController.cs
index 2578992..6282c42 100644
--- a/code/AmIVulnerable/AmIVulnerable/Controllers/GitController.cs
+++ b/code/AmIVulnerable/AmIVulnerable/Controllers/GitController.cs
@@ -1,348 +1,354 @@
-using Microsoft.AspNetCore.Mvc;
-using Modells;
-using MySql.Data.MySqlClient;
-using Newtonsoft.Json;
-using SerilogTimings;
-using System.Data;
-using System.Diagnostics;
-using System.Text.RegularExpressions;
-using CM = System.Configuration.ConfigurationManager;
-
-namespace AmIVulnerable.Controllers {
-
- [Route("api/[controller]")]
- [ApiController]
- public class GitController : ControllerBase {
-
- #region Config
- ///
- private readonly IConfiguration Configuration;
-
- ///
- ///
- public GitController(IConfiguration configuration) {
- Configuration = configuration;
- }
- #endregion
-
- #region Controller
-
- ///
- ///
- ///
- [HttpPost]
- [Route("repository")]
- public async Task CloneRepoToAnalyze([FromBody] RepoObject repoObject) {
- if (repoObject.RepoUrl is null) {
- return BadRequest();
- }
-
- // check if repo already cloned
- DataTable tempTable = ExecuteMySqlCommand($"" +
- $"SELECT * " +
- $"FROM cve.repositories " +
- $"WHERE repoUrl='{repoObject.RepoUrl}' AND tag='{repoObject.RepoTag}';");
-
- if (tempTable.Rows.Count > 0) {
- return Ok(tempTable.Rows[0]["guid"]);
- }
- else { // clone the repo
- Guid repoId = Guid.NewGuid();
- string trimmedUrl = repoObject.RepoUrl[(repoObject.RepoUrl.IndexOf("//") + 2)..(repoObject.RepoUrl.Length)];
- trimmedUrl = trimmedUrl[(trimmedUrl.IndexOf('/') + 1)..(trimmedUrl.Length)];
- string owner = trimmedUrl[0..trimmedUrl.IndexOf('/', 1)];
- string designation = trimmedUrl[(owner.Length + 1)..trimmedUrl.Length];
- if (designation.Contains('/')) {
- designation = designation[0..trimmedUrl.IndexOf('/', owner.Length + 1)];
- }
-
- ExecuteMySqlCommand($"" +
- $"INSERT INTO cve.repositories (guid, repoUrl, repoOwner, repoDesignation, tag) " +
- $"VALUES (" +
- $"'{repoId}'," +
- $"'{repoObject.RepoUrl}'," +
- $"'{owner}'," +
- $"'{designation}'," +
- $"'{repoObject.RepoTag ?? ""}');");
-
- await Clone(repoObject.RepoUrl, repoObject.RepoTag ?? "", repoId.ToString());
-
- return Ok(repoId);
- }
- }
-
- /// Gets guid, tag, ... of all Repositories that have been cloned
- /// Return all data of repos
- [HttpGet]
- [Route("allrepositories")]
- public async Task GetRepositories() {
- DataTable repositoryQuery = ExecuteMySqlCommand($"" +
- $"SELECT * " +
- $"FROM cve.repositories;");
-
- if (repositoryQuery.Rows.Count == 0) {
- return NoContent();
- }
-
- List