-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathVirusTotal.m
executable file
·636 lines (503 loc) · 17.4 KB
/
VirusTotal.m
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
//
// VirusTotal.m
// KnockKnock
//
// Created by Patrick Wardle on 3/8/15.
// Copyright (c) 2015 Objective-See. All rights reserved.
//
#import "File.h"
#import "ItemBase.h"
#import "Utilities.h"
#import "PluginBase.h"
#import "VirusTotal.h"
#import "AppDelegate.h"
/* GLOBALS */
//cmdline flag
extern BOOL cmdlineMode;
@implementation VirusTotal
//thread function
// runs in the background to get virus total info about a plugin's items
-(void)getInfo:(PluginBase*)plugin
{
//plugin file items
// in dictionary w/ SHA1 hash as key
NSMutableDictionary* uniqueItems = nil;
//File object
File* item = nil;
//item data
NSMutableDictionary* itemData = nil;
//items
NSMutableArray* items = nil;
//VT query URL
NSURL* queryURL = nil;
//results
NSDictionary* results = nil;
//alloc dictionary for plugin file items
uniqueItems = [NSMutableDictionary dictionary];
//alloc list for items
items = [NSMutableArray array];
//init query URL
queryURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", VT_QUERY_URL, VT_API_KEY]];
//sync
// ->since array will be reset if user clicks 'stop' scan
@synchronized(plugin.allItems)
{
//place all plugin file items into dictionary
// ->key: hash, filter's out dups for queries
for(ItemBase* item in plugin.allItems)
{
//skip non-file items
if(YES != [item isKindOfClass:[File class]])
{
//skip
continue;
}
//skip item's without hashes
// ...not sure how this could ever happen
if(nil == ((File*)item).hashes[KEY_HASH_SHA1])
{
//skip
continue;
}
//add item
uniqueItems[((File*)item).hashes[KEY_HASH_SHA1]] = item;
}
}//sync
//iterate over all hashes
// ->create item dictionary (JSON), and add it to list
for(NSString* itemKey in uniqueItems)
{
//sanitized path
NSString* sanitizedPath = nil;
//current user
NSString* currentUser = nil;
//alloc item data
itemData = [NSMutableDictionary dictionary];
//exit if thread was cancelled
// ->i.e. user pressed 'stop' scan
if(YES == [[NSThread currentThread] isCancelled])
{
//exit
[NSThread exit];
}
//get current user
currentUser = getConsoleUser();
//sanitize path
sanitizedPath = [item.path stringByReplacingOccurrencesOfString:currentUser withString:@"user"];
//extract item
item = uniqueItems[itemKey];
//auto start location
itemData[@"autostart_location"] = plugin.name;
//set item name
itemData[@"autostart_entry"] = item.name;
//set item path
itemData[@"image_path"] = sanitizedPath;
//set hash
itemData[@"hash"] = item.hashes[KEY_HASH_SHA1];
//set creation times
itemData[@"creation_datetime"] = [item.attributes.fileCreationDate description];
//add item info to list
[items addObject:itemData];
//less then 25 items
// ->just keep collecting items
if(VT_MAX_QUERY_COUNT != items.count)
{
//next
continue;
}
//make query to VT
results = [self postRequest:queryURL parameters:items];
if(200 == (long)[(NSHTTPURLResponse *)results[VT_HTTP_RESPONSE] statusCode])
{
//process results
[self processResults:plugin.allItems results:results];
}
//remove all items
// since they've been processed
[items removeAllObjects];
}
//process any remaining items
if(0 != items.count)
{
//query virus total
results = [self postRequest:queryURL parameters:items];
if(200 == (long)[(NSHTTPURLResponse *)results[VT_HTTP_RESPONSE] statusCode])
{
//process results
[self processResults:plugin.allItems results:results];
}
}
//exit if thread was cancelled
// ->i.e. user pressed 'stop' scan
if(YES == [[NSThread currentThread] isCancelled])
{
//exit
[NSThread exit];
}
//tell UI all plugin's items have all be processed
if(YES != cmdlineMode)
{
//on main thread
dispatch_async(dispatch_get_main_queue(), ^{
//call up into UI
[((AppDelegate*)[[NSApplication sharedApplication] delegate]) itemsProcessed:plugin];
});
}
return;
}
//item data
//(NSMutableDictionary*)covertItemToRequest:(Item*)
//get VT info for a single item
// will then callback into AppDelegate to reload item in UI
-(BOOL)getInfoForItem:(File*)fileObj scanID:(NSString*)scanID
{
//result
BOOL gotInfo = NO;
//VT query URL
NSURL* queryURL = nil;
//results
NSDictionary* results = nil;
//alert
__block NSAlert* alert = nil;
//init query URL
queryURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@?apikey=%@&resource=%@", VT_REQUERY_URL, VT_API_KEY, scanID]];
//make queries until response is recieved
while(YES)
{
//make query to VT
results = [self postRequest:queryURL parameters:nil];
if(200 != (long)[(NSHTTPURLResponse *)results[VT_HTTP_RESPONSE] statusCode])
{
//update status msg
dispatch_async(dispatch_get_main_queue(), ^{
//alloc/init alert
alert = [NSAlert alertWithMessageText:[NSString stringWithFormat:NSLocalizedString(@"ERROR:\nVirusTotal query for '%@' failed", @"ERROR:\nVirusTotal query for '%@' failed"), fileObj.name] defaultButton:NSLocalizedString(@"OK", @"OK") alternateButton:nil otherButton:nil informativeTextWithFormat:NSLocalizedString(@"HTTP reponse: %ld", @"HTTP reponse: %ld"), (long)[(NSHTTPURLResponse *)results[VT_HTTP_RESPONSE] statusCode]];
//show it
[alert runModal];
});
break;
}
//check if scan is complete
if( (nil != results) &&
(1 == [results[VT_RESULTS_RESPONSE] integerValue]) )
{
//save result
fileObj.vtInfo = results;
//if its flagged save in File's plugin
if(0 != [results[VT_RESULTS_POSITIVES] unsignedIntegerValue])
{
//sync
// ->since array will be reset if user clicks 'stop' scan
@synchronized(fileObj.plugin.flaggedItems)
{
//save
[fileObj.plugin.flaggedItems addObject:fileObj];
}
}
//if its unknown save
if(nil == results[VT_RESULTS_URL])
{
//sync
// since array will be reset if user clicks 'stop' scan
@synchronized(fileObj.plugin.unknownItems)
{
//save
[fileObj.plugin.unknownItems addObject:fileObj];
}
}
//update status msg
dispatch_async(dispatch_get_main_queue(), ^{
//callback up into UI to reload item
[((AppDelegate*)[[NSApplication sharedApplication] delegate]) itemProcessed:fileObj];
});
//happy
gotInfo = YES;
//exit loop
break;
}
//nap
[NSThread sleepForTimeInterval:10.0f];
}
return gotInfo;
}
//make the (POST)query to VT
-(NSDictionary*)postRequest:(NSURL*)url parameters:(id)params
{
//results
NSMutableDictionary* results = nil;
//request
NSMutableURLRequest* request = nil;
//http response
NSURLResponse* httpResponse = nil;
//post data
// ->JSON'd items
NSData* postData = nil;
//error var
NSError* error = nil;
//data from VT
NSData* vtData = nil;
//alloc/init request
request = [[NSMutableURLRequest alloc] initWithURL:url];
//init
results = [NSMutableDictionary dictionary];
//set user agent
[request setValue:VT_USER_AGENT forHTTPHeaderField:@"User-Agent"];
//serialize JSON
if(nil != params)
{
//convert items to JSON'd data for POST request
@try
{
//convert items
postData = [NSJSONSerialization dataWithJSONObject:params options:kNilOptions error:nil];
if(nil == postData)
{
//err msg
NSLog(@"ERROR: failed to convert request %@ to JSON", postData);
goto bail;
}
}
//bail on exceptions
@catch(NSException *exception)
{
//set error
goto bail;
}
//set content type
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//set content length
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[postData length]] forHTTPHeaderField:@"Content-length"];
//add POST data
[request setHTTPBody:postData];
}
//set method type
[request setHTTPMethod:@"POST"];
//send request
// synchronous, so will block
vtData = [NSURLConnection sendSynchronousRequest:request returningResponse:&httpResponse error:&error];
//save http response
results[VT_HTTP_RESPONSE] = httpResponse;
//sanity check(s)
if( (nil == vtData) ||
(nil != error) ||
(200 != (long)[(NSHTTPURLResponse *)httpResponse statusCode]) )
{
//err msg
NSLog(@"ERROR: failed to query VirusTotal (%@, %@)", error, httpResponse);
goto bail;
}
//serialize response into NSData obj
// wrap since we are serializing JSON
@try
{
//serialized
results = [[NSJSONSerialization JSONObjectWithData:vtData options:kNilOptions error:nil] mutableCopy];
if(YES != [results isKindOfClass:[NSDictionary class]])
{
//bail
goto bail;
}
//(re)add http response
results[VT_HTTP_RESPONSE] = httpResponse;
}
//bail on any exceptions
@catch (NSException *exception)
{
//err msg
NSLog(@"ERROR: converting response %@ to JSON threw %@", vtData, exception);
goto bail;
}
//sanity check
if(nil == results)
{
//err msg
NSLog(@"ERROR: failed to convert response %@ to JSON", vtData);
goto bail;
}
//bail
bail:
return results;
}
//submit a file to VT
-(NSDictionary*)submit:(File*)fileObj
{
//results
NSMutableDictionary* results = nil;
//submit URL
NSURL* submitURL = nil;
//request
NSMutableURLRequest* request = nil;
//body of request
NSMutableData* body = nil;
//file data
NSData* fileContents = nil;
//error var
NSError* error = nil;
//data from Vt
NSData* vtData = nil;
//response (HTTP) from VT
NSURLResponse* httpResponse = nil;
//init
results = [NSMutableDictionary dictionary];
//init submit URL
submitURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@?apikey=%@&resource=%@", VT_SUBMIT_URL, VT_API_KEY, fileObj.hashes[KEY_HASH_MD5]]];
//init request
request = [[NSMutableURLRequest alloc] initWithURL:submitURL];
//set boundary string
NSString *boundary = @"qqqq___knockknock___qqqq";
//set HTTP method (POST)
[request setHTTPMethod:@"POST"];
//set the HTTP header 'Content-type' to the boundary
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField: @"Content-Type"];
//set HTTP header, 'User-Agent'
[request setValue:VT_USER_AGENT forHTTPHeaderField:@"User-Agent"];
//init body
body = [NSMutableData data];
//load file into memory
fileContents = [NSData dataWithContentsOfFile:fileObj.pathForFinder];
//sanity check
if(nil == fileContents)
{
//err msg
NSLog(@"ERROR: failed to load %@ into memory for submission", fileObj.path);
goto bail;
}
//append boundary
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//append 'Content-Disposition' file name, etc
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", fileObj.name] dataUsingEncoding:NSUTF8StringEncoding]];
//append 'Content-Type'
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//append file's contents
[body appendData:fileContents];
//append '\r\n'
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//append final boundary
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//set body
[request setHTTPBody:body];
//set content length
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[body length]] forHTTPHeaderField:@"Content-length"];
//send request
// synchronous, so will block
vtData = [NSURLConnection sendSynchronousRequest:request returningResponse:&httpResponse error:&error];
//save http response
results[VT_HTTP_RESPONSE] = httpResponse;
//sanity check(s)
if( (nil == vtData) ||
(nil != error) ||
(200 != (long)[(NSHTTPURLResponse *)httpResponse statusCode]) )
{
//err msg
NSLog(@"ERROR: failed to query VirusTotal (%@, %@)", error, httpResponse);
goto bail;
}
//serialize response into NSData obj
// ->wrap since we are serializing JSON
@try
{
//serialize
results = [[NSJSONSerialization JSONObjectWithData:vtData options:kNilOptions error:nil] mutableCopy];
if(YES != [results isKindOfClass:[NSDictionary class]])
{
//bail
goto bail;
}
//(re)add http response
results[VT_HTTP_RESPONSE] = httpResponse;
}
//bail on any exceptions
@catch (NSException *exception)
{
//err msg
NSLog(@"ERROR: converting response %@ to JSON threw %@", vtData, exception);
goto bail;
}
//sanity check
if(nil == results)
{
//err msg
NSLog(@"ERROR: failed to convert response %@ to JSON", vtData);
goto bail;
}
bail:
return results;
}
//submit a rescan request
-(NSDictionary*)reScan:(File*)fileObj
{
//result data
NSDictionary* results = nil;
//scan url
NSURL* reScanURL = nil;
//http response
NSURLResponse* httpResponse = nil;
//init scan url
reScanURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@?apikey=%@&resource=%@", VT_RESCAN_URL, VT_API_KEY, fileObj.hashes[KEY_HASH_MD5]]];
//make request to VT
results = [self postRequest:reScanURL parameters:nil];
if(200 != (long)[(NSHTTPURLResponse *)httpResponse statusCode])
{
//err msg
NSLog(@"ERROR: failed to re-scan %@", fileObj.name);
goto bail;
}
bail:
return results;
}
//process results
// save VT info into each File obj and all flagged files
-(void)processResults:(NSArray*)items results:(NSDictionary*)results
{
//process all results
// save VT result dictionary into File obj
for(NSDictionary* result in results[VT_RESULTS])
{
//sync
// ->since array will be reset if user clicks 'stop' scan
@synchronized(items)
{
//find all items that match
// ->might be dupes, which is fine
for(ItemBase* item in items)
{
//skip non-file items
if(YES != [item isKindOfClass:[File class]])
{
//skip
continue;
}
//for matches, save vt info
if(YES == [result[@"hash"] isEqualToString:((File*)item).hashes[KEY_HASH_SHA1]])
{
//save
((File*)item).vtInfo = result;
//if its flagged save in File's plugin
if(0 != [result[VT_RESULTS_POSITIVES] unsignedIntegerValue])
{
//sync
// ->since array will be reset if user clicks 'stop' scan
@synchronized(item.plugin.flaggedItems)
{
//save
[item.plugin.flaggedItems addObject:item];
}
}
//if its unknown save
if(nil == result[VT_RESULTS_URL])
{
//sync
// ->since array will be reset if user clicks 'stop' scan
@synchronized(item.plugin.unknownItems)
{
//save
[item.plugin.unknownItems addObject:item];
}
}
}
}
}//sync
}
return;
}
@end