-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand-analyzer.ts
More file actions
1265 lines (1107 loc) · 62 KB
/
Copy pathcommand-analyzer.ts
File metadata and controls
1265 lines (1107 loc) · 62 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
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Command Analyzer - TypeScript Standalone Application
// Analisi di sicurezza per comandi da terminale
interface AnalysisResult {
command: string;
riskLevel: 'low' | 'medium' | 'high';
threats: string[];
detectedPatterns: string[];
urls: string[];
downloadedContent?: {
url: string;
content: string;
isBinary: boolean;
mimeType?: string;
size: number;
}[];
highlightedCode: string;
suggestions: string[];
}
interface BinaryResult {
type: string;
mime: string;
}
interface SecurityPattern {
pattern: RegExp;
threat: string;
severity: 'low' | 'medium' | 'high';
}
interface PackageManager {
pattern: RegExp;
name: string;
}
class CommandAnalyzer {
private command: string = '';
private result: AnalysisResult | null = null;
private isLoading: boolean = false;
private showSlowMessage: boolean = false;
private commandHistory: string[] = [];
private showAllHistory: boolean = false;
// Security patterns detection
private readonly dangerousPatterns: SecurityPattern[] = [
{ pattern: /rm\s+-rf\s+\//, threat: 'Rimozione ricorsiva forzata della root directory', severity: 'high' },
{ pattern: /sudo\s+(rm|chmod|chown)/, threat: 'Comandi di sistema privilegiati', severity: 'high' },
{ pattern: /\|\s*(bash|sh|zsh|fish)\s*$/, threat: 'Esecuzione diretta di codice scaricato', severity: 'high' },
{ pattern: /curl.*\|\s*(bash|sh)/, threat: 'Download ed esecuzione immediata', severity: 'high' },
{ pattern: /wget.*-O-.*\|\s*(bash|sh)/, threat: 'Download ed esecuzione via wget', severity: 'high' },
{ pattern: /(iwr|irm|Invoke-WebRequest|Invoke-RestMethod).*\|\s*iex/, threat: 'PowerShell download ed esecuzione', severity: 'high' },
// Obfuscated code execution patterns
{ pattern: /\[System\.Text\.Encoding\]::\w+\.GetString\(\[Convert\]::FromBase64String/, threat: 'Esecuzione di codice PowerShell offuscato tramite Base64', severity: 'high' },
{ pattern: /&\(\[ScriptBlock\]::Create\(.*\.DownloadString\(/, threat: 'Esecuzione remota di codice PowerShell offuscato', severity: 'high' },
{ pattern: /\[ScriptBlock\]::Create\(\(New-Object Net\.WebClient\)\.DownloadString/, threat: 'Esecuzione remota di codice PowerShell via ScriptBlock', severity: 'high' },
{ pattern: /&\(\[ScriptBlock\]::Create\(\$[a-zA-Z_][a-zA-Z0-9_]*\)\)/, threat: 'Esecuzione di codice PowerShell via variabile offuscata', severity: 'high' },
{ pattern: /chmod\s+\+x/, threat: 'Rendere file eseguibile', severity: 'medium' },
{ pattern: /sudo\s+/, threat: 'Elevazione privilegi richiesta', severity: 'medium' },
{ pattern: /python\s+-c\s+["'].*["']/, threat: 'Esecuzione codice Python inline', severity: 'medium' },
{ pattern: /(curl|wget|iwr)\s+.*https?:\/\//, threat: 'Download da URL remoto', severity: 'low' },
];
private readonly packageManagers: PackageManager[] = [
{ pattern: /pip\s+install/, name: 'pip (Python)' },
{ pattern: /npm\s+install/, name: 'npm (Node.js)' },
{ pattern: /yarn\s+add/, name: 'yarn (Node.js)' },
{ pattern: /choco\s+install/, name: 'Chocolatey (Windows)' },
{ pattern: /winget\s+install/, name: 'winget (Windows)' },
{ pattern: /scoop\s+install/, name: 'Scoop (Windows)' },
{ pattern: /conda\s+install/, name: 'Conda (Python)' },
{ pattern: /mamba\s+install/, name: 'Mamba (Python)' },
{ pattern: /cargo\s+install/, name: 'Cargo (Rust)' },
{ pattern: /gem\s+install/, name: 'RubyGems' },
{ pattern: /Install-Package\s+/, name: 'Install-Package (PowerShell)' },
{ pattern: /Add-AppxPackage\s+/, name: 'Add-AppxPackage (Windows Apps)' },
{ pattern: /Start-BitsTransfer\s+/, name: 'Start-BitsTransfer (Windows BITS)' },
{ pattern: /msiexec\s+/, name: 'msiexec (Windows Installer)' },
];
// CORS proxy chain
private readonly corsProxies: string[] = [
'https://corsproxy.io/?',
'https://api.allorigins.win/get?url=',
'https://cors-anywhere.herokuapp.com/',
];
constructor() {
this.initializeApp();
}
private initializeApp(): void {
document.addEventListener('DOMContentLoaded', () => {
this.createHTML();
this.attachEventListeners();
});
if (document.readyState === 'loading') {
// DOMContentLoaded has not fired yet
return;
} else {
// DOM is already loaded
this.createHTML();
this.attachEventListeners();
}
}
private createHTML(): void {
document.body.innerHTML = `
<div class="header">
<div class="container">
<div class="header-content">
<div class="header-icon">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 002 2z"></path>
</svg>
</div>
<div>
<h1 class="header-title">Command Analyzer</h1>
<p class="header-subtitle">Analisi di sicurezza per comandi da terminale</p>
</div>
</div>
</div>
</div>
<div class="container">
<div class="main-grid">
<!-- Input Section -->
<div>
<div class="card">
<h2 class="card-title">
<svg width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 002 2z"></path>
</svg>
Inserisci Comando
</h2>
<textarea id="commandInput" class="textarea-compact"></textarea>
<button id="resetBtn" class="button" style="background-color: #6b7280; margin-top: 0.5rem;">
<svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
</svg>
Reset
</button>
<button id="analyzeBtn" class="button">
<svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
</svg>
Analizza Comando
</button>
<div id="slowMessage" class="alert hidden">
<svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
L'analisi sta richiedendo più tempo del solito. Stiamo scaricando e analizzando i contenuti...
</div>
</div>
<!-- Cronologia -->
<div class="card">
<h3 class="card-title">
<svg width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
Cronologia
</h3>
<div id="historyContainer"></div>
</div>
</div>
<!-- Results Section -->
<div>
<div id="results" class="hidden"></div>
<div id="emptyState">
<div class="card">
<div class="empty-state">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
</svg>
<h3>Nessuna Analisi Disponibile</h3>
<p>Inserisci un comando nel campo di input per iniziare l'analisi di sicurezza.</p>
</div>
</div>
</div>
</div>
</div>
</div>
`;
}
private attachEventListeners(): void {
const analyzeBtn = document.getElementById('analyzeBtn') as HTMLButtonElement;
const resetBtn = document.getElementById('resetBtn') as HTMLButtonElement;
const commandInput = document.getElementById('commandInput') as HTMLTextAreaElement;
analyzeBtn?.addEventListener('click', () => this.handleAnalyze());
resetBtn?.addEventListener('click', () => this.handleReset());
commandInput?.addEventListener('keydown', (e: KeyboardEvent) => {
if (e.key === 'Enter') {
e.preventDefault();
this.handleAnalyze();
}
});
commandInput?.addEventListener('input', this.autoResizeTextarea.bind(this));
this.loadHistory();
this.renderHistory();
}
private autoResizeTextarea(): void {
const textarea = document.getElementById('commandInput') as HTMLTextAreaElement;
if (textarea) {
// Reset to minimum height first
textarea.style.height = '36px';
// Only expand if there's content and it needs more space
if (textarea.value.trim() && textarea.scrollHeight > 36) {
textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';
}
}
}
private loadHistory(): void {
const saved = localStorage.getItem('commandHistory');
if (saved) {
this.commandHistory = JSON.parse(saved);
}
}
private saveHistory(): void {
localStorage.setItem('commandHistory', JSON.stringify(this.commandHistory));
}
private addToHistory(command: string): void {
const index = this.commandHistory.indexOf(command);
if (index > -1) {
this.commandHistory.splice(index, 1);
}
this.commandHistory.unshift(command);
if (this.commandHistory.length > 50) {
this.commandHistory = this.commandHistory.slice(0, 50);
}
this.saveHistory();
this.renderHistory();
}
private removeFromHistory(command: string): void {
// Find the specific command that needs to be removed
this.commandHistory = this.commandHistory.filter(cmd => cmd !== command);
this.saveHistory();
this.renderHistory();
}
private copyToClipboard(text: string): void {
navigator.clipboard.writeText(text).then(() => {
console.log('Comando copiato negli appunti');
}).catch(err => {
console.error('Errore nella copia:', err);
});
}
private selectHistoryCommand(command: string): void {
const textarea = document.getElementById('commandInput') as HTMLTextAreaElement;
if (textarea) {
textarea.value = command;
this.autoResizeTextarea();
this.handleAnalyze();
}
}
private renderHistory(): void {
const container = document.getElementById('historyContainer') as HTMLDivElement;
if (!container) return;
if (this.commandHistory.length === 0) {
container.innerHTML = '<p style="color: #6b7280; font-size: 0.875rem; text-align: center; padding: 1rem;">Nessun comando nella cronologia</p>';
return;
}
const truncateCommand = (cmd: string, maxLength: number = 50): string => {
return cmd.length > maxLength ? cmd.substring(0, maxLength) + '...' : cmd;
};
const displayHistory = this.showAllHistory ? this.commandHistory : this.commandHistory.slice(0, 3);
let html = '';
for (let i = 0; i < displayHistory.length; i++) {
const cmd = displayHistory[i];
const displayCmd = truncateCommand(cmd);
const itemId = `history-item-${i}`;
html += `
<div class="history-item" data-command-index="${i}" id="${itemId}">
<button class="delete-btn" data-action="delete" data-index="${i}" title="Elimina dalla cronologia">
<svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
</svg>
</button>
<div class="command-text" data-action="select" data-index="${i}" title="Clicca per riutilizzare questo comando: ${cmd.replace(/"/g, '"')}">${displayCmd}</div>
<button class="copy-btn" data-action="copy" data-index="${i}" title="Copia comando">
<svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path>
</svg>
</button>
</div>
`;
}
if (this.commandHistory.length > 3) {
html += `
<div style="text-align: center; margin-top: 1rem;">
<button class="expand-btn" data-action="toggle-expand">
${this.showAllHistory ? 'Mostra meno' : '⋯'}
</button>
</div>
`;
}
container.innerHTML = html;
this.attachHistoryEventListeners();
}
private attachHistoryEventListeners(): void {
const container = document.getElementById('historyContainer') as HTMLDivElement;
if (!container) return;
container.addEventListener('click', (e: Event) => {
const target = e.target as HTMLElement;
const button = target.closest('[data-action]') as HTMLElement;
if (!button) return;
e.preventDefault();
e.stopPropagation();
const action = button.getAttribute('data-action');
const index = parseInt(button.getAttribute('data-index') || '0');
const displayHistory = this.showAllHistory ? this.commandHistory : this.commandHistory.slice(0, 3);
switch (action) {
case 'delete':
if (displayHistory[index]) {
this.removeFromHistory(displayHistory[index]);
}
break;
case 'copy':
if (displayHistory[index]) {
this.copyToClipboard(displayHistory[index]);
}
break;
case 'select':
if (displayHistory[index]) {
this.selectHistoryCommand(displayHistory[index]);
}
break;
case 'toggle-expand':
this.toggleHistoryExpansion();
break;
}
});
}
private toggleHistoryExpansion(): void {
this.showAllHistory = !this.showAllHistory;
this.renderHistory();
}
// Extract URLs from command
private extractUrls(text: string): string[] {
const urlRegex = /https?:\/\/[^\s<>"{}|\\^`[\]]+/g;
return text.match(urlRegex) || [];
}
// Detect binary content - improved to avoid false positives
private detectBinary(content: string): BinaryResult | null {
if (content.startsWith('MZ')) return { type: 'EXE', mime: 'application/vnd.microsoft.portable-executable' };
if (content.startsWith('PK')) return { type: 'ZIP', mime: 'application/zip' };
if (content.startsWith('%PDF')) return { type: 'PDF', mime: 'application/pdf' };
if (content.startsWith('\x7fELF')) return { type: 'ELF', mime: 'application/x-executable' };
if (content.startsWith('\x89PNG')) return { type: 'PNG', mime: 'image/png' };
if (content.startsWith('\xff\xd8\xff')) return { type: 'JPEG', mime: 'image/jpeg' };
// Check if it's actually a text file (like PowerShell scripts, batch files, etc.)
const textIndicators = [
/^#!\/bin\//, // Shebang
/^@echo\s+off/i, // Batch file
/^param\s*\(/i, // PowerShell param
/^function\s+/i, // Function definition
/^if\s*\(/i, // Conditional statements
/^for\s*\(/i, // Loop statements
/^\s*<\?xml/i, // XML
/^\s*<!DOCTYPE/i, // HTML/XML
/^\s*{/i, // JSON
];
const isLikelyText = textIndicators.some(regex => regex.test(content.substring(0, 200)));
if (isLikelyText) return null;
// Heuristic: check for non-printable characters - more restrictive
const nonPrintable = content.split('').filter(char => {
const code = char.charCodeAt(0);
return code < 32 && code !== 9 && code !== 10 && code !== 13;
}).length;
const ratio = nonPrintable / content.length;
// Increased threshold to reduce false positives and require more content
if (ratio > 0.5 && content.length > 500) {
return { type: 'BINARY', mime: 'application/octet-stream' };
}
return null;
}
// Follow redirects and download content
private async downloadContent(url: string): Promise<any> {
let finalUrl = url;
let content = '';
// Try to follow redirects (simplified)
for (const proxy of this.corsProxies) {
try {
const proxyUrl = proxy + encodeURIComponent(finalUrl);
const response = await fetch(proxyUrl);
if (proxy.includes('allorigins')) {
const data = await response.json();
content = data.contents;
} else {
content = await response.text();
}
break;
} catch (error) {
console.log(`Failed with proxy ${proxy}:`, error);
continue;
}
}
if (!content) {
throw new Error('Impossibile scaricare il contenuto dopo tutti i proxy');
}
const binaryResult = this.detectBinary(content);
return {
url: finalUrl,
content: content.substring(0, 10000), // Limit content size
isBinary: !!binaryResult,
mimeType: binaryResult?.mime,
size: content.length,
};
}
// Syntax highlighting
private highlightSyntax(code: string): string {
let highlighted = code;
// Escape HTML first
highlighted = highlighted.replace(/[&<>"']/g, (char) => {
const entities: Record<string, string> = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return entities[char];
});
// Highlight dangerous commands
highlighted = highlighted.replace(/(rm\s+-rf|sudo|curl|wget|chmod\s+\+x)/g, '<span class="highlight-danger">$1</span>');
// Highlight URLs
highlighted = highlighted.replace(/(https?:\/\/[^\s<>"{}|\\^`[\]]+)/g, '<span class="highlight-url">$1</span>');
// Highlight pipe operations
highlighted = highlighted.replace(/(\|\s*(bash|sh|zsh|iex))/g, '<span class="highlight-pipe">$1</span>');
// Highlight package managers
highlighted = highlighted.replace(/(pip|npm|yarn|choco|winget|scoop|conda|mamba|cargo|gem)\s+(install|add)/g, '<span class="highlight-package">$1 $2</span>');
highlighted = highlighted.replace(/(Install-Package|Add-AppxPackage|Start-BitsTransfer)/g, '<span class="highlight-package">$1</span>');
// Highlight obfuscated code patterns
highlighted = highlighted.replace(/(\[System\.Text\.Encoding\]::\w+\.GetString\(\[Convert\]::FromBase64String)/g, '<span class="highlight-danger">$1</span>');
highlighted = highlighted.replace(/(\[ScriptBlock\]::Create)/g, '<span class="highlight-danger">$1</span>');
return highlighted;
}
// Get documentation URL for command type
private getDocumentationUrl(type: string): string {
const docUrls: Record<string, string> = {
'iwr': 'https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest',
'iex': 'https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-expression',
'irm': 'https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod',
'install-package': 'https://docs.microsoft.com/en-us/powershell/module/packagemanagement/install-package',
'add-appxpackage': 'https://docs.microsoft.com/en-us/powershell/module/appx/add-appxpackage',
'start-bitstransfer': 'https://docs.microsoft.com/en-us/powershell/module/bitstransfer/start-bitstransfer',
'msiexec': 'https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/msiexec',
'base64 decode (offuscato)': 'https://attack.mitre.org/techniques/T1027/010/',
'remote execution (offuscato)': 'https://attack.mitre.org/techniques/T1059/001/',
'chocolatey': 'https://chocolatey.org/docs',
'Install-Package': 'https://docs.microsoft.com/en-us/powershell/module/packagemanagement/install-package',
'Add-AppxPackage': 'https://docs.microsoft.com/en-us/powershell/module/appx/add-appxpackage',
'Start-BitsTransfer': 'https://docs.microsoft.com/en-us/powershell/module/bitstransfer/start-bitstransfer',
'curl': 'https://curl.se/docs/manpage.html',
'wget': 'https://www.gnu.org/software/wget/manual/wget.html',
'pip': 'https://pip.pypa.io/en/stable/',
'npm': 'https://docs.npmjs.com/',
'choco': 'https://chocolatey.org/docs',
'winget': 'https://docs.microsoft.com/en-us/windows/package-manager/winget/',
'powershell': 'https://docs.microsoft.com/en-us/powershell/',
'bash': 'https://www.gnu.org/software/bash/manual/bash.html'
};
return docUrls[type.toLowerCase()] || 'https://google.com/search?q=' + encodeURIComponent(type + ' command documentation');
}
// Extract package names from install commands and get documentation URLs
private extractPackagesWithDocs(command: string): { name: string; url: string | null }[] {
const packages: { name: string; url: string | null }[] = [];
// NPM packages
const npmMatch = command.match(/npm\s+install\s+([^&\s;|]+)/i);
if (npmMatch) {
const packageName = npmMatch[1].replace(/^[@-]/, '').split('@')[0];
packages.push({
name: packageName,
url: `https://www.npmjs.com/package/${packageName}`
});
}
// Yarn packages
const yarnMatch = command.match(/yarn\s+add\s+([^&\s;|]+)/i);
if (yarnMatch) {
const packageName = yarnMatch[1].replace(/^[@-]/, '').split('@')[0];
packages.push({
name: packageName,
url: `https://www.npmjs.com/package/${packageName}`
});
}
// Pip packages
const pipMatch = command.match(/pip\s+install\s+([^&\s;|]+)/i);
if (pipMatch) {
const packageName = pipMatch[1].split('==')[0].split('>=')[0].split('<=')[0];
packages.push({
name: packageName,
url: `https://pypi.org/project/${packageName}/`
});
}
// Chocolatey packages
const chocoMatch = command.match(/choco\s+install\s+([^&\s;|]+)/i);
if (chocoMatch) {
const packageName = chocoMatch[1];
packages.push({
name: packageName,
url: `https://chocolatey.org/packages/${packageName}`
});
}
// Install-Package (PowerShell PackageManagement)
const installPkgMatch = command.match(/Install-Package\s+.*-Name\s+([^&\s;|-]+)/i);
if (installPkgMatch) {
const packageName = installPkgMatch[1];
const providerMatch = command.match(/-ProviderName\s+([^&\s;|-]+)/i);
const provider = providerMatch ? providerMatch[1].toLowerCase() : 'unknown';
let baseUrl = '';
switch (provider) {
case 'chocolatey':
baseUrl = `https://chocolatey.org/packages/${packageName}`;
break;
case 'powershellgallery':
baseUrl = `https://www.powershellgallery.com/packages/${packageName}`;
break;
default:
baseUrl = `https://google.com/search?q=${encodeURIComponent(packageName + ' ' + provider)}`;
}
packages.push({
name: packageName,
url: baseUrl
});
}
// Add-AppxPackage
const appxMatch = command.match(/Add-AppxPackage\s+.*-Path\s+"?([^"&\s;|]+)"?/i);
if (appxMatch) {
const packagePath = appxMatch[1];
packages.push({
name: packagePath,
url: null
});
}
// Start-BitsTransfer - extract the source URL but don't link to direct download
const bitsMatch = command.match(/Start-BitsTransfer\s+.*-Source\s+"?([^"&\s;|]+)"?/i);
if (bitsMatch) {
const sourceUrl = bitsMatch[1];
const fileName = sourceUrl.split('/').pop() || 'downloaded file';
const domain = new URL(sourceUrl).hostname;
packages.push({
name: `${fileName} (da ${domain})`,
url: `https://google.com/search?q=${encodeURIComponent(fileName + ' ' + domain)}`
});
}
// msiexec - extract installer path (local installation, potentially dangerous)
const msiMatch = command.match(/msiexec\s+.*\/i\s+"?([^"&\s;|]+)"?/i);
if (msiMatch) {
const installerPath = msiMatch[1];
packages.push({
name: `Installazione locale: ${installerPath}`,
url: null // No docs for local files
});
}
// Winget packages
const wingetMatch = command.match(/winget\s+install\s+([^&\s;|]+)/i);
if (wingetMatch) {
// Remove --id= prefix if present
let packageName = wingetMatch[1].replace(/^--id=/, '');
packages.push({
name: packageName,
url: `https://winget.run/pkg/${packageName}`
});
}
// Cargo packages
const cargoMatch = command.match(/cargo\s+install\s+([^&\s;|]+)/i);
if (cargoMatch) {
const packageName = cargoMatch[1];
packages.push({
name: packageName,
url: `https://crates.io/crates/${packageName}`
});
}
// RubyGems
const gemMatch = command.match(/gem\s+install\s+([^&\s;|]+)/i);
if (gemMatch) {
const packageName = gemMatch[1];
packages.push({
name: packageName,
url: `https://rubygems.org/gems/${packageName}`
});
}
return packages;
}
// Detect and decode obfuscated PowerShell code
private async deobfuscateCode(command: string): Promise<string> {
let deobfuscatedCode = '';
// Base64 decoding pattern - improved detection
const base64Patterns = [
/\[System\.Text\.Encoding\]::\w+\.GetString\(\[Convert\]::FromBase64String\("([^"]+)"\)\)/gi,
/\$\w+\s*=\s*'([A-Za-z0-9+/=]+)'\s*;\s*\$\w+\s*=\s*\[System\.Text\.Encoding\]::UTF8\.GetString\(\[Convert\]::FromBase64String\(\$\w+\)\)/gi
];
for (const pattern of base64Patterns) {
const matches = [...command.matchAll(pattern)];
for (const match of matches) {
try {
const decoded = atob(match[1]);
deobfuscatedCode += `\n--- Codice Base64 decodificato ---\n${decoded}\n`;
} catch (error) {
deobfuscatedCode += `\n--- Errore decodifica Base64 ---\n${match[1]}\n`;
}
}
}
// ScriptBlock with DownloadString pattern - improved detection
const downloadPatterns = [
/\[ScriptBlock\]::Create\(\(.*\.DownloadString\("([^"]+)"\)\)\)/gi,
/\&\(\[ScriptBlock\]::Create\(\(New-Object Net\.WebClient\)\.DownloadString\("([^"]+)"\)\)\)/gi,
/\&\(\[ScriptBlock\]::Create\(\(.*\.DownloadString\(\$\w+\)\)\)\)/gi
];
for (const pattern of downloadPatterns) {
const matches = [...command.matchAll(pattern)];
for (const match of matches) {
try {
let url = match[1];
// Handle variable URL references
if (url.startsWith('$')) {
const varPattern = new RegExp(`\\${url}\\s*=\\s*"([^"]+)"`, 'i');
const varMatch = command.match(varPattern);
if (varMatch) url = varMatch[1];
}
const content = await this.downloadContent(url);
if (!content.isBinary) {
deobfuscatedCode += `\n--- Codice scaricato da ${url} ---\n${content.content}\n`;
}
} catch (error) {
deobfuscatedCode += `\n--- Errore download da ${match[1]} ---\nURL non raggiungibile\n`;
}
}
}
// URL concatenation pattern - improved detection
const concatPatterns = [
/\$\w+\s*=\s*"([^"]*https?:\/\/[^"]*)"[^;]*\+[^;]*"([^"]*)"[^;]*;/gi,
/\$\w+\s*=\s*"(https?:\/\/[^"]*?)"\s*\+\s*"([^"]*?)"/gi
];
for (const pattern of concatPatterns) {
const matches = [...command.matchAll(pattern)];
for (const match of matches) {
const reconstructedUrl = match[1] + match[2];
try {
const content = await this.downloadContent(reconstructedUrl);
if (!content.isBinary) {
deobfuscatedCode += `\n--- Codice da URL concatenato ${reconstructedUrl} ---\n${content.content}\n`;
}
} catch (error) {
deobfuscatedCode += `\n--- Errore download da URL concatenato ${reconstructedUrl} ---\nURL non raggiungibile\n`;
}
}
}
// Complex variable obfuscation pattern
const complexPattern = /\$\w+\s*=\s*'([^']+)'\s*\+\s*'([^']+)'\s*\+\s*'([^']+)'/gi;
const complexMatches = [...command.matchAll(complexPattern)];
for (const match of complexMatches) {
const assembled = match[1] + match[2] + match[3];
if (assembled.includes('New') && assembled.includes('Object') && assembled.includes('WebClient')) {
deobfuscatedCode += `\n--- Comando assemblato rilevato ---\n${assembled}\n`;
}
}
return deobfuscatedCode;
}
private formatFileSize(bytes: number): string {
if (bytes === 0) return '0 bytes';
const k = 1024;
const sizes = ['bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
const size = parseFloat((bytes / Math.pow(k, i)).toFixed(2));
return size + ' ' + sizes[i];
}
private getTypeDescription(type: string): string {
const descriptions: {[key: string]: string} = {
'Install-Package': 'PowerShell PackageManagement per installare software da repository. Supporta provider come Chocolatey, PowerShellGet, etc.',
'chocolatey': 'Chocolatey è un gestore di pacchetti per Windows che installa software da repository di terze parti.',
'Add-AppxPackage': 'PowerShell per installare app da file locali (MSIX/APPX). Installa applicazioni da file già scaricati nel sistema.',
'Start-BitsTransfer': 'PowerShell per trasferimenti file in background tramite BITS. Può scaricare file da server remoti.',
'msiexec': 'Windows Installer per installare pacchetti MSI da file locali. Origine e sicurezza del file sconosciute.',
'iwr': 'PowerShell command per scaricare contenuto web. Può essere usato per scaricare ed eseguire script remoti.',
'iex': 'PowerShell command per eseguire codice come stringhe. Spesso usato per eseguire script scaricati.',
'irm': 'PowerShell command per chiamate REST API. Può scaricare ed eseguire contenuto web.',
'winget': 'Windows Package Manager per installare software. Gestore di pacchetti ufficiale Microsoft per Windows.',
'Base64 Decode (OFFUSCATO)': '⚠️ CODICE OFFUSCATO: Decodifica ed esecuzione di codice PowerShell nascosto tramite Base64. Tecnica comune per nascondere payload malevoli.',
'Remote Execution (OFFUSCATO)': '⚠️ CODICE OFFUSCATO: Esecuzione remota di codice PowerShell. Scarica ed esegue script da URL remoti in modo offuscato.',
'curl': 'Utility per trasferire dati da/verso server. Comunemente usato per scaricare script di installazione.',
'wget': 'Utility per scaricare file dalla rete. Spesso usato per automatizzare download di software.',
'sudo': 'Comando per eseguire operazioni con privilegi amministrativi. Richiede attenzione per rischi di sicurezza.',
'rm/del': 'Comando per eliminare file e directory. Può causare perdita di dati se usato impropriamente.',
'Package Manager': 'Gestore di pacchetti per installare librerie e software. Verifica sempre la fonte dei pacchetti.',
'chmod/chown': 'Comandi per modificare permessi e proprietà dei file. Possono compromettere la sicurezza del sistema.'
};
return descriptions[type] || 'Comando non riconosciuto o comando personalizzato.';
}
private getCommandInfo(command: string): { type: string[]; description: string } {
const commandTypes = [
{ pattern: /^(iwr|Invoke-WebRequest)/i, type: 'iwr', description: 'PowerShell command per scaricare contenuto web. Può essere usato per scaricare ed eseguire script remoti.' },
{ pattern: /^(iex|Invoke-Expression)/i, type: 'iex', description: 'PowerShell command per eseguire codice come stringhe. Spesso usato per eseguire script scaricati.' },
{ pattern: /^(irm|Invoke-RestMethod)/i, type: 'irm', description: 'PowerShell command per chiamate REST API. Può scaricare ed eseguire contenuto web.' },
{ pattern: /^(winget)/i, type: 'winget', description: 'Windows Package Manager per installare software. Gestore di pacchetti ufficiale Microsoft per Windows.' },
{ pattern: /^(msiexec)/i, type: 'msiexec', description: 'Windows Installer per installare pacchetti MSI da file locali. Origine e sicurezza del file sconosciute.' },
{ pattern: /^(Install-Package)/i, type: 'Install-Package', description: 'PowerShell PackageManagement per installare software da repository. Supporta provider come Chocolatey, PowerShellGet, etc.' },
{ pattern: /^(Add-AppxPackage)/i, type: 'Add-AppxPackage', description: 'PowerShell per installare app da file locali (MSIX/APPX). Installa applicazioni da file già scaricati nel sistema.' },
{ pattern: /^(Start-BitsTransfer)/i, type: 'Start-BitsTransfer', description: 'PowerShell per trasferimenti file in background tramite BITS. Può scaricare file da server remoti.' },
{ pattern: /\[System\.Text\.Encoding\].*FromBase64String/i, type: 'Base64 Decode (OFFUSCATO)', description: '⚠️ CODICE OFFUSCATO: Decodifica ed esecuzione di codice PowerShell nascosto tramite Base64. Tecnica comune per nascondere payload malevoli.' },
{ pattern: /\[ScriptBlock\]::Create.*DownloadString/i, type: 'Remote Execution (OFFUSCATO)', description: '⚠️ CODICE OFFUSCATO: Esecuzione remota di codice PowerShell. Scarica ed esegue script da URL remoti in modo offuscato.' },
{ pattern: /^curl/i, type: 'curl', description: 'Utility per trasferire dati da/verso server. Comunemente usato per scaricare script di installazione.' },
{ pattern: /^wget/i, type: 'wget', description: 'Utility per scaricare file dalla rete. Spesso usato per automatizzare download di software.' },
{ pattern: /^sudo/i, type: 'sudo', description: 'Comando per eseguire operazioni con privilegi amministrativi. Richiede attenzione per rischi di sicurezza.' },
{ pattern: /^(rm|del)/i, type: 'rm/del', description: 'Comando per eliminare file e directory. Può causare perdita di dati se usato impropriamente.' },
{ pattern: /^(pip|npm|yarn|gem|cargo)/i, type: 'Package Manager', description: 'Gestore di pacchetti per installare librerie e software. Verifica sempre la fonte dei pacchetti.' },
{ pattern: /^(chmod|chown)/i, type: 'chmod/chown', description: 'Comandi per modificare permessi e proprietà dei file. Possono compromettere la sicurezza del sistema.' }
];
const detectedTypes: string[] = [];
let description = '';
for (const cmd of commandTypes) {
if (cmd.pattern.test(command)) {
detectedTypes.push(cmd.type);
description = cmd.description;
break;
}
}
// Special handling for Install-Package with provider detection
if (detectedTypes.includes('Install-Package')) {
const providerMatch = command.match(/-ProviderName\s+([^&\s;|-]+)/i);
if (providerMatch) {
const provider = providerMatch[1].toLowerCase();
detectedTypes.push(provider);
}
}
if (detectedTypes.length === 0) {
detectedTypes.push('Unknown');
description = 'Comando non riconosciuto o comando personalizzato.';
}
return { type: detectedTypes, description };
}
// Handle reset functionality
private handleReset(): void {
const input = document.getElementById('commandInput') as HTMLTextAreaElement;
const resultsDiv = document.getElementById('results') as HTMLDivElement;
const emptyState = document.getElementById('emptyState') as HTMLDivElement;
// Clear input
input.value = '';
this.autoResizeTextarea();
// Hide results and show empty state
resultsDiv.classList.add('hidden');
emptyState.classList.remove('hidden');
// Clear stored command and result
this.command = '';
this.result = null;
// Focus on input
input.focus();
}
// Extract code content from URLs
private async extractCodeFromUrls(urls: string[]): Promise<string[]> {
const codeContents = [];
for (const url of urls) {
try {
const content = await this.downloadContent(url);
if (!content.isBinary) {
codeContents.push(content.content);
}
} catch (error) {
console.error(`Failed to download ${url}:`, error);
}
}
return codeContents;
}
// Extract all unique URLs from code content
private extractAllUrls(command: string, codeContents: string[]): string[] {
const allUrls = new Set<string>();
// URLs from command
const commandUrls = this.extractUrls(command);
commandUrls.forEach(url => allUrls.add(url));
// URLs from downloaded content
for (const content of codeContents) {
const contentUrls = this.extractUrls(content);
contentUrls.forEach(url => allUrls.add(url));
}
return Array.from(allUrls);
}
// Main analysis function
private async analyzeCommand(inputCommand: string): Promise<AnalysisResult> {
const threats: string[] = [];
const detectedPatterns: string[] = [];
const suggestions: string[] = [];
const codeContents: string[] = [];
let riskLevel: 'low' | 'medium' | 'high' = 'low';
// Check dangerous patterns
for (const { pattern, threat, severity } of this.dangerousPatterns) {
if (pattern.test(inputCommand)) {
threats.push(threat);
detectedPatterns.push(pattern.source);
if (severity === 'high') riskLevel = 'high';
else if (severity === 'medium' && riskLevel !== 'high') riskLevel = 'medium';
}
}
// Check package managers
for (const { pattern, name } of this.packageManagers) {
if (pattern.test(inputCommand)) {
detectedPatterns.push(`Package manager: ${name}`);
suggestions.push(`Verifica la fonte del package prima di installare da ${name}`);
}
}
// Get command info and check if unknown command
const commandInfo = this.getCommandInfo(inputCommand);
// Handle multiple command types
const typeDescriptions = commandInfo.type.map(type => `${type}`).join(', ');
detectedPatterns.push(`Tipo comando: ${typeDescriptions} - ${commandInfo.description}`);
// If command is unknown, set risk to medium
if (commandInfo.type.includes('Unknown') && riskLevel === 'low') {
riskLevel = 'medium';
threats.push('Comando non riconosciuto - richiede attenzione manuale');
}
// Check for obfuscated commands and attempt deobfuscation
const isObfuscated = /(\[System\.Text\.Encoding\].*FromBase64String|\[ScriptBlock\]::Create.*DownloadString)/i.test(inputCommand);
if (isObfuscated) {
try {
const deobfuscatedCode = await this.deobfuscateCode(inputCommand);
if (deobfuscatedCode) {
codeContents.push(deobfuscatedCode);
threats.push('⚠️ CODICE OFFUSCATO RILEVATO - Possibile tentativo di nascondere payload malevolo');
if (riskLevel !== 'high') riskLevel = 'high';
}
} catch (error) {
threats.push('Codice offuscato rilevato ma non decodificabile');
if (riskLevel !== 'high') riskLevel = 'high';
}
}
// Extract and analyze URLs
const urls = this.extractUrls(inputCommand);
const downloadedContent = [];
const codeContents = [];
for (const url of urls) {
try {
const content = await this.downloadContent(url);
downloadedContent.push(content);
if (content.isBinary) {
threats.push(`URL scarica contenuto binario: ${content.mimeType || 'unknown'}`);
riskLevel = 'high';
} else {
codeContents.push(content.content);
}
} catch (error) {
console.error(`Failed to download ${url}:`, error);
threats.push(`Impossibile analizzare URL: ${url}`);
}
}
// Special risk check for msiexec with local files
if (/^msiexec\s+.*\/i\s+/i.test(inputCommand) && riskLevel === 'low') {
riskLevel = 'medium';
threats.push('Installazione di pacchetto MSI locale - origine e sicurezza sconosciute');
}
// Extract all URLs from command and downloaded content
const allUrls = this.extractAllUrls(inputCommand, codeContents);
// Increase risk level based on number of URLs found
if (allUrls.length > 0) {
if (allUrls.length >= 5) {
// Many URLs increase risk significantly
if (riskLevel === 'low') riskLevel = 'medium';
else if (riskLevel === 'medium') riskLevel = 'high';
threats.push(`Numero elevato di URL rilevati: ${allUrls.length} collegamenti`);
} else if (allUrls.length >= 2) {
// Multiple URLs increase risk moderately
if (riskLevel === 'low') riskLevel = 'medium';
threats.push(`Multiple URL rilevate: ${allUrls.length} collegamenti`);
} else {
// Single URL - minimal risk increase
threats.push(`URL rilevato: ${allUrls.length} collegamento`);
}
}
// Add general suggestions
if (threats.length === 0) {
suggestions.push('Il comando sembra sicuro da eseguire');
} else {
suggestions.push('Esamina attentamente i rischi identificati prima di eseguire');
suggestions.push('Considera di eseguire il comando in un ambiente isolato');
if (allUrls.length > 0) {
suggestions.push('Verifica manualmente tutti gli URL prima dell\'esecuzione');
}
}
return {
command: inputCommand,
riskLevel,
threats,
detectedPatterns,
urls: allUrls,
downloadedContent,
highlightedCode: this.highlightSyntax(inputCommand),
suggestions,
};
}