-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathsilentchain_ai_community.py
More file actions
executable file
·2418 lines (2030 loc) · 101 KB
/
silentchain_ai_community.py
File metadata and controls
executable file
·2418 lines (2030 loc) · 101 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
# -*- coding: utf-8 -*-
# Burp Suite Python Extension: SILENTCHAIN AI - COMMUNITY EDITION
# Version: 1.1.4
# Release Date: 2026-03-17
# License: SILENTCHAIN AI Community Edition License (see LICENSE file)
# Build-ID: bb90850f-1d2e-4d12-852e-842527475b37
#
# COMMUNITY EDITION - AI-Powered Security Scanner
# For active verification and Phase 2 testing, upgrade to Professional Edition
#
# This community edition provides:
# - AI-powered passive security analysis
# - OWASP Top 10 vulnerability detection
# - Real-time threat identification
# - Professional reporting with CWE/OWASP mappings
#
# Professional Edition adds:
# - Phase 2 active verification with exploit payloads
# - WAF detection and evasion
# - Advanced payload libraries
# - Out-of-band (OOB) testing
# - Automated fuzzing with Burp Intruder integration
#
# Changelog:
# v1.1.1 (2025-02-04) - Fix Settings freeze and slow startup: move network calls off EDT to background threads
# v1.1.0 (2025-02-04) - Fix UI hang on Linux: dirty-flag refresh guard, incremental console, remove EDT lock contention
# v1.0.9 (2025-02-02) - Skip static files (js,css,images,fonts), passive scan toggle, taller Settings dialog
# v1.0.8 (2025-01-31) - Minor fixes and improvements
# v1.0.7 (2025-01-31) - Removed Unicode chars, widened Settings dialog
# v1.0.6 (2025-01-31) - Fixed UTF-8 decode errors, timeout max 99999s, moved Debug to Settings
# v1.0.5 (2025-01-31) - Persistent config, equal window sizing, robust JSON parsing
# v1.0.4 (2025-01-31) - Added Cancel/Pause All, Debug Tasks, auto stuck detection
# v1.0.3 (2025-01-31) - Fixed context menu forced re-analysis
# v1.0.2 (2025-01-31) - Fixed unicode format errors, improved error handling
# v1.0.1 (2025-01-31) - Added configurable timeout, retry logic
# v1.0.0 (2025-01-31) - Initial stable release
from burp import IBurpExtender, IHttpListener, IScannerCheck, IScanIssue, ITab, IContextMenuFactory
from java.io import PrintWriter
from java.awt import BorderLayout, GridBagLayout, GridBagConstraints, Insets, Dimension, Font, Color, FlowLayout
from javax.swing import JPanel, JScrollPane, JTextArea, JTable, JLabel, JSplitPane, BorderFactory, SwingUtilities, JButton, BoxLayout, Box, JMenuItem
from javax.swing.table import DefaultTableModel, DefaultTableCellRenderer
from java.lang import Runnable
from java.util import ArrayList
import json
import re
import threading
import urllib2
import time
import hashlib
from datetime import datetime
from collections import defaultdict
# ============================================================================
# Data Sanitizer -- Jython 2.7 compatible (no f-strings)
# Redacts sensitive data before sending to cloud AI APIs.
# ============================================================================
_SANITIZE_ALLOWLIST = set([
"127.0.0.1", "0.0.0.0", "::1", "localhost",
"example.com", "example.org", "example.net", "test.com",
])
_SANITIZE_PATTERNS = [
("KEY", "api_key", re.compile(
r"(?:sk-[A-Za-z0-9_\-]{20,}"
r"|ghp_[A-Za-z0-9]{36,}"
r"|AKIA[A-Z0-9]{16}"
r"|glpat-[A-Za-z0-9_\-]{20,}"
r"|xoxb-[A-Za-z0-9\-]{20,})"
)),
("AUTH", "auth", re.compile(
r"(?:Bearer\s+[A-Za-z0-9_\-\.]{10,}"
r"|Basic\s+[A-Za-z0-9+/=]{8,})"
)),
("CRED", "cred", re.compile(
r"(?:[A-Za-z0-9_.+-]+:[A-Za-z0-9_.+-]+@"
r"|(?:password|passwd|pwd|secret|token)\s*[=:]\s*\S+)",
re.IGNORECASE
)),
("COOKIE", "cookie", re.compile(
r"(?:(?:session|sess|token|csrf|xsrf|jwt|sid|ssid|auth_token|access_token|refresh_token)"
r"=[A-Za-z0-9_\-%.+/=]{4,})",
re.IGNORECASE
)),
("EMAIL", "email", re.compile(
r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"
)),
("IP", "ip", re.compile(
r"\b(?:\d{1,3}\.){3}\d{1,3}\b"
)),
("HOST", "hostname", re.compile(
r"\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}\b"
)),
("PATH", "path", re.compile(
r"(?:/(?:[a-zA-Z0-9._\-]+/){2,}[a-zA-Z0-9._\-]+"
r"|[A-Z]:\\(?:[a-zA-Z0-9._\-]+\\){1,}[a-zA-Z0-9._\-]+)"
)),
]
class DataSanitizer:
"""Bidirectional data sanitizer for cloud AI API requests (Jython 2.7)."""
def __init__(self, enabled=True, target=None):
self.enabled = enabled
self._mapping = {} # placeholder -> original
self._reverse = {} # original -> placeholder
self._counters = defaultdict(int)
if target and enabled:
self._register_target(target)
def _register_target(self, target):
if target in _SANITIZE_ALLOWLIST:
return
if re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", target):
self._add_mapping(target, "IP")
else:
self._add_mapping(target, "HOST")
def _add_mapping(self, value, label):
if value in self._reverse:
return self._reverse[value]
self._counters[label] += 1
placeholder = "[REDACTED_%s_%d]" % (label, self._counters[label])
self._mapping[placeholder] = value
self._reverse[value] = placeholder
return placeholder
def sanitize(self, text):
if not self.enabled or not text:
return text
for label, _cat, pattern in _SANITIZE_PATTERNS:
text = pattern.sub(lambda m, l=label: self._sanitize_match(m, l), text)
return text
def _sanitize_match(self, match, label):
value = match.group(0)
if value in _SANITIZE_ALLOWLIST:
return value
return self._add_mapping(value, label)
def restore(self, text):
if not self.enabled or not text or not self._mapping:
return text
for placeholder in sorted(self._mapping.keys(), key=len, reverse=True):
text = text.replace(placeholder, self._mapping[placeholder])
return text
def reset(self):
self._mapping.clear()
self._reverse.clear()
self._counters.clear()
@property
def redacted_summary(self):
if not self._counters:
return "nothing"
parts = ["%d %s(s)" % (count, label) for label, count in sorted(self._counters.items())]
return ", ".join(parts)
VALID_SEVERITIES = {
"high": "High", "medium": "Medium", "low": "Low",
"information": "Information", "informational": "Information",
"info": "Information", "inform": "Information"
}
def map_confidence(ai_confidence):
if ai_confidence < 50: return None
elif ai_confidence < 75: return "Tentative"
elif ai_confidence < 90: return "Firm"
else: return "Certain"
# Custom PrintWriter wrapper to capture console output
class ConsolePrintWriter:
def __init__(self, original_writer, extender_ref):
self.original = original_writer
self.extender = extender_ref
def println(self, message):
self.original.println(message)
if hasattr(self.extender, 'log_to_console'):
try:
self.extender.log_to_console(str(message))
except:
pass
def print_(self, message):
self.original.print_(message)
def write(self, data):
self.original.write(data)
def flush(self):
self.original.flush()
class BurpExtender(IBurpExtender, IHttpListener, IScannerCheck, ITab, IContextMenuFactory):
def registerExtenderCallbacks(self, callbacks):
self.callbacks = callbacks
self.helpers = callbacks.getHelpers()
# Store original writers
original_stdout = PrintWriter(callbacks.getStdout(), True)
original_stderr = PrintWriter(callbacks.getStderr(), True)
# Wrap to capture console output
self.stdout = ConsolePrintWriter(original_stdout, self)
self.stderr = ConsolePrintWriter(original_stderr, self)
# Version Information
self.VERSION = "1.1.4"
self.EDITION = "Community"
self.RELEASE_DATE = "2026-03-17"
self.BUILD_ID = "bb90850f-1d2e-4d12-852e-842527475b37"
callbacks.setExtensionName("SILENTCHAIN AI - %s Edition v%s" % (self.EDITION, self.VERSION))
callbacks.registerHttpListener(self)
callbacks.registerScannerCheck(self)
callbacks.registerContextMenuFactory(self)
# Configuration file path (in user's home directory)
import os
self.config_file = os.path.join(os.path.expanduser("~"), ".silentchain_config.json")
# AI Provider Settings (defaults - will be overridden by saved config)
self.AI_PROVIDER = "Ollama" # Options: Ollama, OpenAI, Claude, Gemini
self.API_URL = "http://localhost:11434"
self.API_KEY = "" # For OpenAI, Claude, Gemini
self.MODEL = "deepseek-r1:latest"
self.MAX_TOKENS = 2048
self.AI_REQUEST_TIMEOUT = 60 # Timeout for AI requests in seconds (default: 60)
self.available_models = []
self.VERBOSE = True
self.THEME = "Light" # Options: Light, Dark
self.PASSIVE_SCANNING_ENABLED = True # Enable/disable passive scanning (context menu still works)
# Data Sanitization (redact sensitive data for cloud AI APIs)
self.SANITIZE_ENABLED = True
# File extensions to skip during analysis (static/non-security-relevant files)
self.SKIP_EXTENSIONS = ["gif", "jpg", "jpeg", "png", "ico", "css", "woff", "woff2", "ttf", "eot", "otf", "svg", "mp3", "mp4", "avi", "webm", "webp", "avif", "bmp", "map", "br", "gz"]
# Load saved configuration (if exists)
self.load_config()
# UI refresh control
self._ui_dirty = True # Flag: data changed since last refresh
self._refresh_pending = False # Guard: refresh already queued on EDT
self._last_console_len = 0 # Track console length for incremental append
# Console tracking for UI panel
self.console_messages = []
self.console_lock = threading.Lock()
self.max_console_messages = 1000
# Findings tracking for Findings panel
self.findings_list = []
self.findings_lock_ui = threading.Lock()
self.findings_cache = {}
self.findings_lock = threading.Lock()
# Context menu debounce
self.context_menu_last_invoke = {}
self.context_menu_debounce_time = 1.0
self.context_menu_lock = threading.Lock()
self.processed_urls = set()
self.url_lock = threading.Lock()
self.semaphore = threading.Semaphore(1)
self.last_request_time = 0
self.min_delay = 4.0
# Task tracking
self.tasks = []
self.tasks_lock = threading.Lock()
self.stats = {
"total_requests": 0,
"analyzed": 0,
"skipped_duplicate": 0,
"skipped_rate_limit": 0,
"skipped_low_confidence": 0,
"findings_created": 0,
"errors": 0
}
self.stats_lock = threading.Lock()
# Create UI
self.initUI()
self.log_to_console("=== SILENTCHAIN AI - Community Edition Initialized ===")
self.log_to_console("Console panel is active and logging...")
# Force immediate UI refresh
self.refreshUI()
# Display logo
self.print_logo()
self.stdout.println("[+] Version: %s (Released: %s)" % (self.VERSION, self.RELEASE_DATE))
self.stdout.println("[+] Edition: Community (Passive Analysis Only)")
self.stdout.println("[+] AI Provider: %s" % self.AI_PROVIDER)
self.stdout.println("[+] API URL: %s" % self.API_URL)
self.stdout.println("[+] Model: %s" % self.MODEL)
self.stdout.println("[+] Max Tokens: %d" % self.MAX_TOKENS)
self.stdout.println("[+] Request Timeout: %d seconds" % self.AI_REQUEST_TIMEOUT)
self.stdout.println("[+] Deduplication: ENABLED")
self.stdout.println("")
self.stdout.println("[*] COMMUNITY EDITION - Passive scanning only")
self.stdout.println("[*] For active verification, upgrade to Professional Edition")
self.stdout.println("[*] Visit: https://silentchain.ai for more information")
# Test AI connection in background thread (non-blocking startup)
def _startup_connection_test():
connection_ok = self.test_ai_connection()
if not connection_ok:
self.stderr.println("\n[!] WARNING: AI connection test failed!")
self.stderr.println("[!] Extension will not function properly until connection is established.")
self.stderr.println("[!] Please check Settings and verify your AI configuration.")
_conn_thread = threading.Thread(target=_startup_connection_test)
_conn_thread.setDaemon(True)
_conn_thread.start()
# Add UI tab
callbacks.addSuiteTab(self)
# Start auto-refresh timer for Console
self.start_auto_refresh_timer()
def initUI(self):
# Main panel
self.panel = JPanel(BorderLayout())
# Top panel with stats
topPanel = JPanel()
topPanel.setLayout(BoxLayout(topPanel, BoxLayout.Y_AXIS))
topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))
# Title
titleLabel = JLabel("SILENTCHAIN AI - Community Edition v%s" % self.VERSION)
titleLabel.setFont(Font("Monospaced", Font.BOLD, 16))
titlePanel = JPanel()
titlePanel.add(titleLabel)
topPanel.add(titlePanel)
# Edition notice
editionLabel = JLabel("AI-Powered OWASP Top 10 Vulnerability Scanning for Burp Suite")
editionLabel.setFont(Font("Dialog", Font.ITALIC, 12))
editionLabel.setForeground(Color(0xD5, 0x59, 0x35))
editionPanel = JPanel()
editionPanel.add(editionLabel)
topPanel.add(editionPanel)
topPanel.add(Box.createRigidArea(Dimension(0, 10)))
# Stats panel
statsPanel = JPanel(GridBagLayout())
statsPanel.setBorder(BorderFactory.createTitledBorder("Statistics"))
gbc = GridBagConstraints()
gbc.insets = Insets(5, 10, 5, 10)
gbc.anchor = GridBagConstraints.WEST
self.statsLabels = {}
statNames = [
("total_requests", "Total Requests:"),
("analyzed", "Analyzed:"),
("skipped_duplicate", "Skipped (Duplicate):"),
("skipped_rate_limit", "Skipped (Rate Limit):"),
("skipped_low_confidence", "Skipped (Low Confidence):"),
("findings_created", "Findings Created:"),
("errors", "Errors:")
]
row = 0
for key, label in statNames:
gbc.gridx = (row % 4) * 2
gbc.gridy = row / 4
statsPanel.add(JLabel(label), gbc)
gbc.gridx = (row % 4) * 2 + 1
valueLabel = JLabel("0")
valueLabel.setFont(Font("Monospaced", Font.BOLD, 12))
statsPanel.add(valueLabel, gbc)
self.statsLabels[key] = valueLabel
row += 1
topPanel.add(statsPanel)
# Control panel
controlPanel = JPanel()
# Settings button
self.settingsButton = JButton("Settings", actionPerformed=self.openSettings)
self.settingsButton.setBackground(Color(0x4D, 0x47, 0xAC))
self.settingsButton.setForeground(Color.WHITE)
self.settingsButton.setOpaque(True)
self.clearButton = JButton("Clear Completed", actionPerformed=self.clearCompleted)
# Cancel/Pause all buttons (kill switches)
self.cancelAllButton = JButton("Cancel All Tasks", actionPerformed=self.cancelAllTasks)
self.pauseAllButton = JButton("Pause All Tasks", actionPerformed=self.pauseAllTasks)
# Upgrade to Professional button
self.upgradeButton = JButton("Upgrade to Professional", actionPerformed=self.openUpgradePage)
self.upgradeButton.setBackground(Color(0xD5, 0x59, 0x35))
self.upgradeButton.setForeground(Color.WHITE)
self.upgradeButton.setOpaque(True)
controlPanel.add(self.settingsButton)
controlPanel.add(self.clearButton)
controlPanel.add(self.cancelAllButton)
controlPanel.add(self.pauseAllButton)
controlPanel.add(self.upgradeButton)
topPanel.add(controlPanel)
self.panel.add(topPanel, BorderLayout.NORTH)
# Split pane for tasks and findings - equal sizing (33.33% each)
splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
splitPane.setResizeWeight(0.33) # Tasks get 33%
# Task table
taskPanel = JPanel(BorderLayout())
taskPanel.setBorder(BorderFactory.createTitledBorder("Active Tasks"))
self.taskTableModel = DefaultTableModel()
self.taskTableModel.addColumn("Timestamp")
self.taskTableModel.addColumn("Type")
self.taskTableModel.addColumn("URL")
self.taskTableModel.addColumn("Status")
self.taskTableModel.addColumn("Duration")
self.taskTable = JTable(self.taskTableModel)
self.taskTable.setAutoCreateRowSorter(True)
self.taskTable.getColumnModel().getColumn(0).setPreferredWidth(150)
self.taskTable.getColumnModel().getColumn(1).setPreferredWidth(120)
self.taskTable.getColumnModel().getColumn(2).setPreferredWidth(300)
self.taskTable.getColumnModel().getColumn(3).setPreferredWidth(130)
self.taskTable.getColumnModel().getColumn(4).setPreferredWidth(80)
# Color renderer for status
statusRenderer = StatusCellRenderer()
self.taskTable.getColumnModel().getColumn(3).setCellRenderer(statusRenderer)
taskScrollPane = JScrollPane(self.taskTable)
taskPanel.add(taskScrollPane, BorderLayout.CENTER)
splitPane.setTopComponent(taskPanel)
# Findings Panel
findingsPanel = JPanel(BorderLayout())
findingsPanel.setBorder(BorderFactory.createTitledBorder("Findings"))
# Findings stats
findingsStatsPanel = JPanel(FlowLayout(FlowLayout.LEFT))
self.findingsStatsLabel = JLabel("Total: 0 | High: 0 | Medium: 0 | Low: 0 | Info: 0")
self.findingsStatsLabel.setFont(Font("Monospaced", Font.BOLD, 11))
findingsStatsPanel.add(self.findingsStatsLabel)
findingsPanel.add(findingsStatsPanel, BorderLayout.NORTH)
self.findingsTableModel = DefaultTableModel()
self.findingsTableModel.addColumn("Discovered At")
self.findingsTableModel.addColumn("URL")
self.findingsTableModel.addColumn("Finding")
self.findingsTableModel.addColumn("Severity")
self.findingsTableModel.addColumn("Confidence")
self.findingsTable = JTable(self.findingsTableModel)
self.findingsTable.setAutoCreateRowSorter(True)
self.findingsTable.getColumnModel().getColumn(0).setPreferredWidth(150)
self.findingsTable.getColumnModel().getColumn(1).setPreferredWidth(300)
self.findingsTable.getColumnModel().getColumn(2).setPreferredWidth(250)
self.findingsTable.getColumnModel().getColumn(3).setPreferredWidth(80)
self.findingsTable.getColumnModel().getColumn(4).setPreferredWidth(90)
# Color renderers
severityRenderer = SeverityCellRenderer()
confidenceRenderer = ConfidenceCellRenderer()
self.findingsTable.getColumnModel().getColumn(3).setCellRenderer(severityRenderer)
self.findingsTable.getColumnModel().getColumn(4).setCellRenderer(confidenceRenderer)
findingsScrollPane = JScrollPane(self.findingsTable)
findingsPanel.add(findingsScrollPane, BorderLayout.CENTER)
# Create nested split pane for Findings and Console - equal sizing
bottomSplitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
bottomSplitPane.setResizeWeight(0.50) # Findings and Console split 50/50 of bottom 66%
bottomSplitPane.setTopComponent(findingsPanel)
# Console Panel
consolePanel = JPanel(BorderLayout())
consolePanel.setBorder(BorderFactory.createTitledBorder("Console"))
self.consoleTextArea = JTextArea()
self.consoleTextArea.setEditable(False)
self.consoleTextArea.setFont(Font("Monospaced", Font.PLAIN, 13))
self.consoleTextArea.setLineWrap(True)
self.consoleTextArea.setWrapStyleWord(False)
# Apply theme colors
self.applyConsoleTheme()
consoleScrollPane = JScrollPane(self.consoleTextArea)
consoleScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
self.console_user_scrolled = False
from java.awt.event import AdjustmentListener
class ScrollListener(AdjustmentListener):
def __init__(self, extender):
self.extender = extender
self.last_value = 0
def adjustmentValueChanged(self, e):
scrollbar = e.getAdjustable()
current_value = scrollbar.getValue()
max_value = scrollbar.getMaximum() - scrollbar.getVisibleAmount()
if current_value < max_value - 10:
self.extender.console_user_scrolled = True
else:
self.extender.console_user_scrolled = False
consoleScrollPane.getVerticalScrollBar().addAdjustmentListener(ScrollListener(self))
consolePanel.add(consoleScrollPane, BorderLayout.CENTER)
bottomSplitPane.setBottomComponent(consolePanel)
splitPane.setBottomComponent(bottomSplitPane)
self.panel.add(splitPane, BorderLayout.CENTER)
# Store references for divider positioning
self.mainSplitPane = splitPane
self.bottomSplitPane = bottomSplitPane
# Add component listener to set equal 33% splits when panel is shown
from java.awt.event import ComponentAdapter
class SplitPaneInitializer(ComponentAdapter):
def __init__(self, extender):
self.extender = extender
self.initialized = False
def componentResized(self, e):
if not self.initialized and self.extender.panel.getHeight() > 0:
self.initialized = True
# Calculate 33% splits based on actual panel height
total_height = self.extender.panel.getHeight()
third = total_height / 3
# Set main split: Tasks gets top 33%
self.extender.mainSplitPane.setDividerLocation(int(third))
# Set bottom split: Findings and Console each get 50% of remaining 66%
# This means each gets 33% of total
self.extender.bottomSplitPane.setDividerLocation(int(third))
self.panel.addComponentListener(SplitPaneInitializer(self))
def applyConsoleTheme(self):
"""Apply theme colors to console"""
if self.THEME == "Dark":
# Dark theme: Charcoal background with light grey text
self.consoleTextArea.setBackground(Color(0x32, 0x33, 0x34)) # #323334
self.consoleTextArea.setForeground(Color(0x7D, 0xA3, 0x58)) # #7DA358
else:
# Light theme (default): White background with charcoal text
self.consoleTextArea.setBackground(Color.WHITE)
self.consoleTextArea.setForeground(Color(0x36, 0x45, 0x4F)) # Charcoal #36454F
def refreshUI(self, event=None):
# Skip if a refresh is already queued on the EDT
if self._refresh_pending:
return
# Skip if nothing changed since last refresh
if not self._ui_dirty:
return
class RefreshRunnable(Runnable):
def __init__(self, extender):
self.extender = extender
def run(self):
try:
# --- Copy data out of locks (fast) ---
with self.extender.stats_lock:
stats_snapshot = dict(self.extender.stats)
with self.extender.tasks_lock:
tasks_snapshot = []
for task in self.extender.tasks[-100:]:
duration = ""
if task.get("end_time"):
duration = "%.2fs" % (task["end_time"] - task["start_time"])
elif task.get("start_time"):
duration = "%.2fs" % (time.time() - task["start_time"])
tasks_snapshot.append([
task.get("timestamp", ""),
task.get("type", ""),
task.get("url", "")[:100],
task.get("status", ""),
duration
])
with self.extender.findings_lock_ui:
findings_snapshot = []
severity_counts = {"High": 0, "Medium": 0, "Low": 0, "Information": 0}
total_findings = 0
for finding in self.extender.findings_list:
total_findings += 1
severity = finding.get("severity", "Information")
if severity in severity_counts:
severity_counts[severity] += 1
findings_snapshot.append([
finding.get("discovered_at", ""),
finding.get("url", "")[:100],
finding.get("title", "")[:50],
severity,
finding.get("confidence", "")
])
with self.extender.console_lock:
current_len = len(self.extender.console_messages)
prev_len = self.extender._last_console_len
if current_len != prev_len:
new_messages = list(self.extender.console_messages[prev_len:])
console_changed = True
else:
new_messages = []
console_changed = False
# Handle case where messages were trimmed (list shortened)
if current_len < prev_len:
console_changed = True
new_messages = list(self.extender.console_messages)
prev_len = 0
# --- Update Swing components (no locks held) ---
# Stats
for key, label in self.extender.statsLabels.items():
label.setText(str(stats_snapshot.get(key, 0)))
# Task table
self.extender.taskTableModel.setRowCount(0)
for row in tasks_snapshot:
self.extender.taskTableModel.addRow(row)
# Findings table
self.extender.findingsTableModel.setRowCount(0)
for row in findings_snapshot:
self.extender.findingsTableModel.addRow(row)
self.extender.findingsStatsLabel.setText(
"Total: %d | High: %d | Medium: %d | Low: %d | Info: %d" %
(total_findings, severity_counts["High"], severity_counts["Medium"],
severity_counts["Low"], severity_counts["Information"])
)
# Console — incremental append with size cap
if console_changed:
doc = self.extender.consoleTextArea.getDocument()
if prev_len == 0:
# Full rebuild (first load or after trim)
console_text = "\n".join(new_messages)
self.extender.consoleTextArea.setText(console_text)
else:
# Append only new messages
append_text = "\n" + "\n".join(new_messages)
doc.insertString(doc.getLength(), append_text, None)
# Cap document size to prevent UI slowdown (keep last ~200KB)
max_doc_len = 200000
doc_len = doc.getLength()
if doc_len > max_doc_len:
trim_to = doc_len - max_doc_len
# Find next newline after trim point for clean cut
text_start = doc.getText(trim_to, min(200, doc_len - trim_to))
nl_pos = text_start.find("\n")
if nl_pos >= 0:
trim_to += nl_pos + 1
doc.remove(0, trim_to)
self.extender._last_console_len = current_len
was_scrolled = self.extender.console_user_scrolled
if not was_scrolled:
try:
self.extender.consoleTextArea.setCaretPosition(doc.getLength())
except:
pass
finally:
self.extender._refresh_pending = False
# If new data arrived while we were refreshing, flag for another pass
if self.extender._ui_dirty:
SwingUtilities.invokeLater(RefreshRunnable(self.extender))
self.extender._refresh_pending = True
self._ui_dirty = False
self._refresh_pending = True
SwingUtilities.invokeLater(RefreshRunnable(self))
def start_auto_refresh_timer(self):
"""Auto-refresh UI and check for stuck tasks"""
def refresh_timer():
check_interval = 0
while True:
time.sleep(5)
self.refreshUI()
# Check for stuck tasks periodically (every ~30 seconds)
check_interval += 1
if check_interval >= 6:
check_interval = 0
self.check_stuck_tasks()
timer_thread = threading.Thread(target=refresh_timer)
timer_thread.setDaemon(True)
timer_thread.start()
def check_stuck_tasks(self):
"""Automatically check for stuck tasks and log warnings"""
current_time = time.time()
stuck_found = False
with self.tasks_lock:
for idx, task in enumerate(self.tasks):
status = task.get("status", "")
start_time = task.get("start_time", 0)
# Check if task has been analyzing for >5 minutes
if ("Analyzing" in status or "Waiting" in status) and start_time > 0:
duration = current_time - start_time
if duration > 300: # 5 minutes
if not stuck_found:
self.stderr.println("\n[AUTO-CHECK] WARNING: STUCK TASK DETECTED")
stuck_found = True
task_type = task.get("type", "Unknown")
url = task.get("url", "Unknown")[:50]
self.stderr.println("[AUTO-CHECK] Task %d stuck: %s | %.1f min | %s" %
(idx, task_type, duration/60, url))
if stuck_found:
self.stderr.println("[AUTO-CHECK] Run 'Debug Tasks' button for detailed diagnostics")
self.stderr.println("[AUTO-CHECK] Or click 'Cancel All Tasks' to clear stuck tasks")
def clearCompleted(self, event):
with self.tasks_lock:
self.tasks = [t for t in self.tasks if not (
t.get("status") == "Completed" or
"Skipped" in t.get("status", "") or
"Error" in t.get("status", "")
)]
self.refreshUI()
def cancelAllTasks(self, event):
"""Cancel all running/queued tasks (kill switch)"""
self.stdout.println("\n[CANCEL ALL] Cancelling all active tasks...")
cancelled_count = 0
with self.tasks_lock:
for task in self.tasks:
status = task.get("status", "")
# Cancel anything that's not already done
if "Completed" not in status and "Error" not in status and "Cancelled" not in status:
task["status"] = "Cancelled"
task["end_time"] = time.time()
cancelled_count += 1
self.stdout.println("[CANCEL ALL] Cancelled %d tasks" % cancelled_count)
self.refreshUI()
def pauseAllTasks(self, event):
"""Pause/Resume all running tasks"""
# Check if any tasks are currently paused to determine toggle direction
paused_count = 0
active_count = 0
with self.tasks_lock:
for task in self.tasks:
status = task.get("status", "")
if "Paused" in status:
paused_count += 1
elif "Analyzing" in status or "Queued" in status or "Waiting" in status:
active_count += 1
# If more tasks are active than paused, pause all. Otherwise, resume all.
if active_count > paused_count:
# Pause all active tasks
self.stdout.println("\n[PAUSE ALL] Pausing all active tasks...")
with self.tasks_lock:
for task in self.tasks:
status = task.get("status", "")
if "Analyzing" in status or "Queued" in status or "Waiting" in status:
task["status"] = "Paused"
self.stdout.println("[PAUSE ALL] All tasks paused")
else:
# Resume all paused tasks
self.stdout.println("\n[RESUME ALL] Resuming all paused tasks...")
with self.tasks_lock:
for task in self.tasks:
status = task.get("status", "")
if "Paused" in status:
task["status"] = "Analyzing"
self.stdout.println("[RESUME ALL] All tasks resumed")
self.refreshUI()
def debugTasks(self, event):
"""Debug stuck/stalled tasks - provides detailed diagnostic information"""
self.stdout.println("\n" + "="*60)
self.stdout.println("[DEBUG] Task Status Diagnostic Report")
self.stdout.println("="*60)
current_time = time.time()
with self.tasks_lock:
total_tasks = len(self.tasks)
active_tasks = []
queued_tasks = []
stuck_tasks = []
for idx, task in enumerate(self.tasks):
status = task.get("status", "Unknown")
task_type = task.get("type", "Unknown")
url = task.get("url", "Unknown")[:50]
start_time = task.get("start_time", 0)
# Calculate duration
if start_time > 0:
duration = current_time - start_time
else:
duration = 0
# Categorize tasks
if "Analyzing" in status or "Waiting" in status:
active_tasks.append((idx, task_type, status, duration, url))
# Check if stuck (analyzing for >5 minutes)
if duration > 300: # 5 minutes
stuck_tasks.append((idx, task_type, status, duration, url))
elif "Queued" in status:
queued_tasks.append((idx, task_type, status, duration, url))
# Print summary
self.stdout.println("\n[DEBUG] Summary:")
self.stdout.println(" Total Tasks: %d" % total_tasks)
self.stdout.println(" Active (Analyzing/Waiting): %d" % len(active_tasks))
self.stdout.println(" Queued: %d" % len(queued_tasks))
self.stdout.println(" Stuck (>5 min): %d" % len(stuck_tasks))
# Print active tasks
if active_tasks:
self.stdout.println("\n[DEBUG] Active Tasks:")
for idx, task_type, status, duration, url in active_tasks[:10]: # Show first 10
self.stdout.println(" [%d] %s | %s | %.1fs | %s" %
(idx, task_type, status, duration, url))
# Print queued tasks
if queued_tasks:
self.stdout.println("\n[DEBUG] Queued Tasks:")
for idx, task_type, status, duration, url in queued_tasks[:10]:
self.stdout.println(" [%d] %s | %s | %.1fs | %s" %
(idx, task_type, status, duration, url))
# Print stuck tasks with detailed diagnostics
if stuck_tasks:
self.stdout.println("\n[DEBUG] WARNING: STUCK TASKS DETECTED:")
for idx, task_type, status, duration, url in stuck_tasks:
self.stdout.println(" [%d] %s | %s | %.1f minutes | %s" %
(idx, task_type, status, duration/60, url))
self.stdout.println("\n[DEBUG] Possible causes:")
self.stdout.println(" 1. AI request timeout (increase in Settings)")
self.stdout.println(" 2. Network issues (check connectivity)")
self.stdout.println(" 3. AI provider unavailable (test connection)")
self.stdout.println(" 4. Thread deadlock (restart Burp Suite)")
self.stdout.println("\n[DEBUG] Recommended actions:")
self.stdout.println(" - Click 'Cancel All Tasks' to clear stuck tasks")
self.stdout.println(" - Check AI connection: Settings → Test Connection")
self.stdout.println(" - Increase timeout: Settings → Advanced → AI Request Timeout")
self.stdout.println(" - Check Console for error messages")
# Check semaphore status
self.stdout.println("\n[DEBUG] Threading Status:")
self.stdout.println(" Rate Limit Delay: %.1fs" % self.min_delay)
self.stdout.println(" Last Request: %.1fs ago" % (current_time - self.last_request_time))
# Check if semaphore might be blocked
if len(active_tasks) > 0 and len(queued_tasks) > 5:
self.stdout.println("\n[DEBUG] Warning: Many queued tasks with active task")
self.stdout.println(" This is normal - tasks are rate-limited to prevent API overload")
self.stdout.println(" Current rate: 1 task every %.1f seconds" % self.min_delay)
self.stdout.println("\n" + "="*60)
self.stdout.println("[DEBUG] End of diagnostic report")
self.stdout.println("="*60)
self.refreshUI()
def load_config(self):
"""Load configuration from disk"""
try:
import os
if os.path.exists(self.config_file):
with open(self.config_file, 'r') as f:
config = json.load(f)
# Load settings
self.AI_PROVIDER = config.get("ai_provider", self.AI_PROVIDER)
self.API_URL = config.get("api_url", self.API_URL)
self.API_KEY = config.get("api_key", self.API_KEY)
self.MODEL = config.get("model", self.MODEL)
self.MAX_TOKENS = config.get("max_tokens", self.MAX_TOKENS)
self.AI_REQUEST_TIMEOUT = config.get("ai_request_timeout", self.AI_REQUEST_TIMEOUT)
self.VERBOSE = config.get("verbose", self.VERBOSE)
saved_theme = config.get("theme", self.THEME)
self.THEME = saved_theme if saved_theme in ("Light", "Dark") else "Light"
self.PASSIVE_SCANNING_ENABLED = config.get("passive_scanning_enabled", self.PASSIVE_SCANNING_ENABLED)
self.SANITIZE_ENABLED = config.get("sanitize_enabled", self.SANITIZE_ENABLED)
self.stdout.println("\n[CONFIG] Loaded saved configuration from %s" % self.config_file)
self.stdout.println("[CONFIG] Provider: %s | Model: %s" % (self.AI_PROVIDER, self.MODEL))
else:
self.stdout.println("\n[CONFIG] No saved configuration found - using defaults")
self.stdout.println("[CONFIG] Config will be saved to: %s" % self.config_file)
except Exception as e:
self.stderr.println("[!] Failed to load config: %s" % e)
self.stderr.println("[!] Using default settings")
def save_config(self):
"""Save configuration to disk"""
try:
config = {
"ai_provider": self.AI_PROVIDER,
"api_url": self.API_URL,
"api_key": self.API_KEY,
"model": self.MODEL,
"max_tokens": self.MAX_TOKENS,
"ai_request_timeout": self.AI_REQUEST_TIMEOUT,
"verbose": self.VERBOSE,
"theme": self.THEME,
"passive_scanning_enabled": self.PASSIVE_SCANNING_ENABLED,
"sanitize_enabled": self.SANITIZE_ENABLED,
"version": self.VERSION,
"last_saved": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
with open(self.config_file, 'w') as f:
json.dump(config, f, indent=2)
self.stdout.println("[CONFIG] Configuration saved to %s" % self.config_file)
return True
except Exception as e:
self.stderr.println("[!] Failed to save config: %s" % e)
return False
def openUpgradePage(self, event):
"""Open updates page in browser"""
self.stdout.println("\n[UPDATE] Checking for updates...")
self.stdout.println("[UPDATE] Visit https://silentchain.ai/?referral=silentchain_community")
try:
import webbrowser
webbrowser.open("https://silentchain.ai/?referral=silentchain_community")
except:
self.stdout.println("[UPDATE] Please visit: https://silentchain.ai/?referral=silentchain_community")
def openSettings(self, event):
"""Open settings dialog with AI provider and advanced configuration"""
from javax.swing import JDialog, JTabbedPane, JTextField, JComboBox, JPasswordField, JTextArea
from javax.swing import SwingConstants, JCheckBox
from java.awt import GridBagLayout, GridBagConstraints, Insets
# Debug: Log that settings is opening
self.stdout.println("\n[SETTINGS] Opening configuration dialog...")
self.stdout.println("[SETTINGS] Current Provider: %s" % self.AI_PROVIDER)
self.stdout.println("[SETTINGS] Current Model: %s" % self.MODEL)
dialog = JDialog()
dialog.setTitle("SILENTCHAIN Settings - Community Edition")
dialog.setModal(True)
dialog.setSize(750, 650) # Wider to accommodate long model names, taller for Advanced tab
dialog.setLocationRelativeTo(None)
tabbedPane = JTabbedPane()
# AI PROVIDER TAB
aiPanel = JPanel(GridBagLayout())
gbc = GridBagConstraints()
gbc.insets = Insets(5, 5, 5, 5)
gbc.anchor = GridBagConstraints.WEST