-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
366 lines (321 loc) · 11 KB
/
Program.cs
File metadata and controls
366 lines (321 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
using System.ComponentModel;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text.Json;
namespace VirusTotalCheck
{
internal class Program
{
static string? filePath = "";
static string? apikey = "";
private static HttpClient httpClient = new HttpClient();
// <summary>
/// A simple console scanner sending file to VirusTotal API and displays the results. Created for Education
/// </summary>
static async Task Main(string[] args)
{
// Check args
if (args.Length != 2)
{
Console.WriteLine("File path: ");
filePath = Console.ReadLine();
if (string.IsNullOrWhiteSpace(filePath))
{
Console.WriteLine("File path is required.");
Console.ReadKey();
return;
}
Console.WriteLine("API key (or the path to the file containing the API key): ");
apikey = Console.ReadLine();
if (string.IsNullOrWhiteSpace(apikey))
{
Console.WriteLine("API key is required.");
Console.ReadKey();
return;
}
}
else
{
filePath = args[0];
apikey = args[1];
}
if (!File.Exists(filePath))
{
if (!File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath)))
{
Console.WriteLine("Incorrect file path.");
Console.ReadKey();
return;
}
filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
}
try
{
if (!File.Exists(apikey))
{
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, apikey)))
{
apikey = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, apikey)).Trim();
}
}
else if (File.Exists(apikey))
{
apikey = File.ReadAllText(apikey).Trim();
}
}
catch
{
Console.WriteLine("No access to API key file");
Console.ReadKey();
return;
}
try
{
using (FileStream fs = File.OpenRead(filePath)) { }
}
catch
{
Console.WriteLine("No access to file.");
Console.ReadKey();
return;
}
//Send
if (!VirusTotalClient(apikey))
{
Console.WriteLine("Internet Error");
Console.ReadKey();
return;
}
try
{
string hash = CalculateFileHash(filePath);
var checkResult = await CheckHashAsync(hash);
if (checkResult.Exist)
{
Present(ParseResults(checkResult.Data!), true);
Console.ReadKey();
return;
}
}
catch (Exception ex)
{
Console.WriteLine("CheckHash Error");
Console.WriteLine(ex.Message);
Console.ReadKey();
return;
}
try
{
var uploadResult = await UploadFileAsync(filePath);
if (!uploadResult.IsCompleted)
{
Console.WriteLine("Scan error");
Console.ReadKey();
return;
// Może trzeba dodać sprawdzenie ponowne id. czy to ma sens?
}
Present(ParseResults(uploadResult.Data!), false);
Console.ReadKey();
return;
}
catch (Exception ex)
{
Console.WriteLine("UploadFile Error");
Console.WriteLine(ex.Message);
Console.ReadKey();
return;
}
}
/// <summary>
/// Present Result in Console
/// </summary>
/// <param name="summary">ScanSummary</param>
/// <param name="noted">bool whether the scanned file has already been noted</param>
public static void Present(ScanSummary summary, bool noted)
{
Console.WriteLine("\n═══════════════════════════════════════════════════════");
Console.WriteLine("VIRUSTOTAL SCAN RESULTS");
Console.WriteLine("═══════════════════════════════════════════════════════\n");
Console.WriteLine($"Noted: {noted}");
Console.WriteLine($"Status: {(summary.IsMalicious ? "MALICIOUS" : "CLEAN")}");
Console.WriteLine($"Malicious: {summary.MaliciousCount}");
Console.WriteLine($"Suspicious: {summary.SuspiciousCount}");
Console.WriteLine($"Total detections:{summary.MaliciousCount + summary.SuspiciousCount}");
if (summary.Detections.Any())
{
Console.WriteLine("\nDetections:");
Console.WriteLine("───────────────────────────────────────────────────────");
int count = 0;
foreach (var det in summary.Detections)
{
count++;
Console.WriteLine($"{count}. [{det.Category.ToUpper()}] {det.Engine}: {det.Result}");
}
}
Console.WriteLine("═══════════════════════════════════════════════════════");
}
/// <summary>
/// Asynchronously sending a file hash
/// </summary>
/// <param name="hash">hash scan file</param>
/// <returns></returns>
public static async Task<CheckResult> CheckHashAsync(string hash)
{
var response = await httpClient.GetAsync(
$"https://www.virustotal.com/api/v3/files/{hash}"
);
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return new CheckResult { Exist = false };
}
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
return new CheckResult
{
Exist = true,
Data = json
};
}
/// <summary>
/// Asynchronously sending a file
/// </summary>
/// <param name="filePath">Path to scan file</param>
/// <returns></returns>
public static async Task<UploadResult> UploadFileAsync(string filePath)
{
using var form = new MultipartFormDataContent();
using var fileStream = File.OpenRead(filePath);
using var fileContent = new StreamContent(fileStream);
form.Add(fileContent, "file", Path.GetFileName(filePath));
var response = await httpClient.PostAsync(
"https://www.virustotal.com/api/v3/files",
form
);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
return ParseUploadResponse(json);
}
/// <summary>
/// httpClient
/// </summary>
/// <param name="apikey">VirusTotal API Key</param>
/// <returns></returns>
public static bool VirusTotalClient(string apikey)
{
try
{
httpClient.DefaultRequestHeaders.Add("x-apikey", apikey);
httpClient.Timeout = TimeSpan.FromMinutes(5);
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("VirusTotalCheck/1.0");
return true;
}
catch { return false; }
}
/// <summary>
/// Convetr data from JSON to ScanSummary
/// </summary>
/// <param name="json">JSON data</param>
/// <returns></returns>
public static ScanSummary ParseResults(string json)
{
var summary = new ScanSummary();
using var doc = JsonDocument.Parse(json);
var data = doc.RootElement.GetProperty("data");
var attrs = data.GetProperty("attributes");
JsonElement stats;
if (attrs.TryGetProperty("stats", out stats))
{
summary.MaliciousCount = stats.GetProperty("malicious").GetInt32();
summary.SuspiciousCount = stats.GetProperty("suspicious").GetInt32();
}
else if (attrs.TryGetProperty("last_analysis_stats", out stats))
{
summary.MaliciousCount = stats.GetProperty("malicious").GetInt32();
summary.SuspiciousCount = stats.GetProperty("suspicious").GetInt32();
}
summary.IsMalicious = summary.MaliciousCount > 0;
JsonElement results;
if (attrs.TryGetProperty("results", out results) ||
attrs.TryGetProperty("last_analysis_results", out results))
{
foreach (var engine in results.EnumerateObject())
{
var scan = engine.Value;
var category = scan.GetProperty("category").GetString();
if (category == "malicious" || category == "suspicious")
{
summary.Detections.Add(new Detection
{
Engine = engine.Name,
Result = scan.GetProperty("result").GetString()!,
Category = category
});
}
}
}
return summary;
}
/// <summary>
/// Calculate scan file hash
/// </summary>
/// <param name="filePath">Path to scan file</param>
/// <returns></returns>
public static string CalculateFileHash(string filePath)
{
using var sha256 = SHA256.Create();
using var stream = File.OpenRead(filePath);
var hashBytes = sha256.ComputeHash(stream);
return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
}
/// <summary>
/// Convetr upload file data from JSON to UploadResult
/// </summary>
/// <param name="json">JSON data</param>
/// <returns></returns>
public static UploadResult ParseUploadResponse(string json)
{
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
var analysisId = root
.GetProperty("data")
.GetProperty("id")
.GetString();
var status = root
.GetProperty("data")
.GetProperty("attributes")
.GetProperty("status")
.GetString();
return new UploadResult
{
AnalysisId = analysisId!,
IsCompleted = status == "completed",
Data = status == "completed" ? json : null
};
}
public class CheckResult
{
public bool Exist { get; set; }
public string? Data { get; set; }
}
public class UploadResult
{
public required string AnalysisId { get; set; }
public required bool IsCompleted { get; set; }
public string? Data { get; set; }
}
public class ScanSummary
{
public bool IsMalicious { get; set; }
public int MaliciousCount { get; set; }
public int SuspiciousCount { get; set; }
public int TotalEngines { get; set; }
public List<Detection> Detections { get; set; } = new();
}
public class Detection
{
public required string Engine { get; set; }
public required string Result { get; set; }
public required string Category { get; set; }
}
}
}