Repository navigation
Expand file tree
/
Copy pathciscoresearchertoolkit.py
More file actions
957 lines (814 loc) · 44.5 KB
/
Copy pathciscoresearchertoolkit.py
File metadata and controls
957 lines (814 loc) · 44.5 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
import requests
import json
import textwrap
import os
import re
import time
import html
from datetime import datetime, timezone
from enum import Enum
from typing import Optional, Dict, Any
def sanitize_html(text):
"""Escape HTML special characters to prevent XSS attacks."""
if not text:
return text
# Use built-in html.escape to convert HTML special characters to safe entities
return html.escape(text, quote=True)
# --- Configuration ---
class AIProvider(Enum):
GEMINI = "gemini"
CLAUDE = "claude"
OPENAI = "openai"
# API Configuration
API_KEYS = {
AIProvider.GEMINI: os.getenv("GEMINI_API_KEY", ""),
AIProvider.CLAUDE: os.getenv("CLAUDE_API_KEY", ""),
AIProvider.OPENAI: os.getenv("OPENAI_API_KEY", "")
}
# Safe default provider setting
try:
DEFAULT_PROVIDER = AIProvider(os.getenv("DEFAULT_AI_PROVIDER", "gemini"))
except ValueError:
DEFAULT_PROVIDER = AIProvider.GEMINI
# API URLs and configurations
API_CONFIGS = {
AIProvider.GEMINI: {
"url": "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent",
"headers": {"Content-Type": "application/json"}
},
AIProvider.CLAUDE: {
"url": "https://api.anthropic.com/v1/messages",
"headers": {
"Content-Type": "application/json",
"anthropic-version": "2023-06-01"
}
},
AIProvider.OPENAI: {
"url": "https://api.openai.com/v1/chat/completions",
"headers": {"Content-Type": "application/json"}
}
}
# Cisco Release Monitoring Resources
CISCO_RELEASE_RESOURCES = {
"Cisco Networking Blog": "https://blogs.cisco.com/networking",
"Meraki Feature Announcements": "https://community.meraki.com/t5/Feature-Announcements/bg-p/new-features",
"Meraki Firmware Upgrades Feed": "https://community.meraki.com/t5/Firmware-Upgrades-Feed/bg-p/firmwareupgrades",
"Meraki Blog": "https://meraki.cisco.com/blog/",
"DevNet Meraki What's New": "https://developer.cisco.com/meraki/whats-new/"
}
# Recent High-Value Releases (Date-Prioritized)
RECENT_HIGH_VALUE_RELEASES = [
{"date": "2024-12", "title": "Cisco AI Assistant", "description": "Conversational AI for network management and troubleshooting", "category": "AI/ML", "type": "Feature", "source_url": "https://blogs.cisco.com/networking"},
{"date": "2024-11", "title": "Meraki MV Smart Camera Analytics", "description": "AI-powered video insights and behavior detection", "category": "AI/IoT", "type": "Feature", "source_url": "https://community.meraki.com/t5/Feature-Announcements/bg-p/new-features"},
{"date": "2024-10", "title": "SD-WAN Cloud OnRamp for SaaS", "description": "Direct cloud connectivity optimization features", "category": "Cloud", "type": "Feature", "source_url": "https://blogs.cisco.com/networking"},
{"date": "2024-09", "title": "Catalyst Center AI Network Analytics", "description": "ML-driven network optimization and predictive insights", "category": "AI/ML", "type": "Feature", "source_url": "https://blogs.cisco.com/networking"},
{"date": "2024-08", "title": "Meraki Systems Manager Zero-Touch", "description": "Automated device deployment and configuration", "category": "Authentication", "type": "Feature", "source_url": "https://community.meraki.com/t5/Feature-Announcements/bg-p/new-features"}
]
# Cache for recent releases (simple timestamp-based caching)
_releases_cache = {"data": None, "timestamp": 0, "ttl": 1800} # 30 minutes TTL
def fetch_recent_releases():
"""Fetch recent releases from Cisco/Meraki Community feeds with caching."""
current_time = time.time()
# Check cache first
if (_releases_cache["data"] is not None and
current_time - _releases_cache["timestamp"] < _releases_cache["ttl"]):
# print("Debug: Using cached data") # Uncomment for debugging
return _releases_cache["data"]
try:
recent_releases = []
# Fetch feature announcements
try:
feature_url = CISCO_RELEASE_RESOURCES["Meraki Feature Announcements"]
response = requests.get(feature_url, timeout=10, headers={
'User-Agent': 'Mozilla/5.0 (compatible; CiscoResearcherToolkit/1.0)'
})
response.raise_for_status()
# Basic HTML parsing to extract post titles and dates
content = response.text
# Look for post patterns in the HTML - Updated patterns based on actual site structure
# Try multiple patterns to catch different layouts
post_patterns = [
r'data-lia-message-uid[^>]*>.*?<a[^>]*>([^<]+)</a>', # Pattern that worked
r'<h[1-6][^>]*>.*?<a[^>]*>([^<]+)</a>.*?</h[1-6]>', # Header with link
r'<a[^>]*href="[^"]*Feature-Announcements[^"]*"[^>]*>([^<]+)</a>' # Direct feature links
]
posts = []
for pattern in post_patterns:
found_posts = re.findall(pattern, content, re.DOTALL | re.IGNORECASE)
for post in found_posts:
clean_post = re.sub(r'\s+', ' ', post.strip()) # Clean whitespace
clean_post = sanitize_html(clean_post) # Sanitize HTML to prevent XSS
if len(clean_post) > 15 and clean_post not in posts: # Filter short/duplicate titles
posts.append(clean_post)
if len(posts) >= 5: # Stop when we have enough
break
# Try to find dates with multiple patterns
date_patterns = [
r'<span[^>]*class="[^"]*DateTime[^"]*"[^>]*title="([^"]+)"',
r'<time[^>]*datetime="([^"]+)"',
r'<span[^>]*class="[^"]*date[^"]*"[^>]*>([^<]+)</span>'
]
dates = []
for pattern in date_patterns:
found_dates = re.findall(pattern, content, re.IGNORECASE)
dates.extend(found_dates)
if len(dates) >= len(posts): # Stop when we have enough dates
break
# Process feature announcements
# print(f"Debug: Found {len(posts)} posts, {len(dates)} dates") # Uncomment for debugging
# if posts:
# print(f"Debug: Sample posts: {posts[:2]}") # Uncomment for debugging
# Process posts (use current date if no dates found)
for i, title in enumerate(posts[:3]): # Top 3 features
if title and len(title) > 15: # Filter out short titles
# Use date if available, otherwise current month
date_str = dates[i] if i < len(dates) else None
date_formatted = parse_date(date_str) if date_str else datetime.now().strftime("%Y-%m")
# Parse date and categorize
category = categorize_release(title)
recent_releases.append({
"date": date_formatted,
"title": title,
"description": generate_description(title),
"category": category,
"type": "Feature",
"source_url": "https://community.meraki.com/t5/Feature-Announcements/bg-p/new-features"
})
# print(f"Debug: Added feature: {title} ({category})") # Uncomment for debugging
except Exception as e:
print(f"Warning: Failed to fetch feature announcements: {e}")
# Fetch firmware updates
try:
firmware_url = CISCO_RELEASE_RESOURCES["Meraki Firmware Upgrades Feed"]
response = requests.get(firmware_url, timeout=10, headers={
'User-Agent': 'Mozilla/5.0 (compatible; CiscoResearcherToolkit/1.0)'
})
response.raise_for_status()
content = response.text
# Look for firmware update patterns using the same approach as features
firmware_patterns = [
r'data-lia-message-uid[^>]*>.*?<a[^>]*>([^<]+)</a>',
r'<h[1-6][^>]*>.*?<a[^>]*>([^<]+)</a>.*?</h[1-6]>'
]
firmware_posts = []
for pattern in firmware_patterns:
found_posts = re.findall(pattern, content, re.DOTALL | re.IGNORECASE)
for post in found_posts:
clean_post = re.sub(r'\s+', ' ', post.strip())
clean_post = sanitize_html(clean_post) # Sanitize HTML to prevent XSS
if (len(clean_post) > 10 and
('firmware' in clean_post.lower() or any(x in clean_post.upper() for x in ['MR', 'MX', 'MS', 'CS'])) and
clean_post not in firmware_posts):
firmware_posts.append(clean_post)
if len(firmware_posts) >= 2:
break
# Use the same date patterns as features
firmware_dates = []
for pattern in date_patterns:
found_dates = re.findall(pattern, content, re.IGNORECASE)
firmware_dates.extend(found_dates)
if len(firmware_dates) >= len(firmware_posts):
break
# Process firmware updates
# print(f"Debug: Found {len(firmware_posts)} firmware posts") # Uncomment for debugging
for i, title in enumerate(firmware_posts[:2]): # Top 2 firmware
if title:
# Use date if available, otherwise current month
date_str = firmware_dates[i] if i < len(firmware_dates) else None
date_formatted = parse_date(date_str) if date_str else datetime.now().strftime("%Y-%m")
recent_releases.append({
"date": date_formatted,
"title": title,
"description": "Security and feature updates for network devices",
"category": "Firmware",
"type": "Firmware",
"source_url": "https://community.meraki.com/t5/Firmware-Upgrades-Feed/bg-p/firmwareupgrades"
})
# print(f"Debug: Added firmware: {title}") # Uncomment for debugging
except Exception as e:
print(f"Warning: Failed to fetch firmware updates: {e}")
# If we got some data, sort by date and cache it
if recent_releases:
# Sort by date (newest first)
recent_releases.sort(key=lambda x: x["date"], reverse=True)
recent_releases = recent_releases[:5] # Top 5
# Cache the results
_releases_cache["data"] = recent_releases
_releases_cache["timestamp"] = current_time
# Write to releases.json for web interface synchronization
try:
with open("releases.json", "w") as f:
json.dump(recent_releases, f, indent=4)
except Exception as e:
print(f"Warning: Failed to write releases.json: {e}")
return recent_releases
except Exception as e:
print(f"Warning: Failed to fetch live releases: {e}")
# Fallback to static data
return RECENT_HIGH_VALUE_RELEASES
def categorize_release(title):
"""Categorize a release based on its title."""
title_lower = title.lower()
if any(word in title_lower for word in ['ai', 'ml', 'assistant', 'analytics', 'intelligence']):
return "AI/ML"
elif any(word in title_lower for word in ['auth', 'oauth', 'sso', 'entra', 'security']):
return "Authentication"
elif any(word in title_lower for word in ['cloud', 'saas', 'api']):
return "Cloud"
elif any(word in title_lower for word in ['firmware', 'mr', 'mx', 'ms', 'cs']):
return "Firmware"
elif any(word in title_lower for word in ['iot', 'camera', 'sensor']):
return "AI/IoT"
else:
return "Feature"
def generate_description(title):
"""Generate a brief description based on the title."""
title_lower = title.lower()
if 'oauth' in title_lower:
return "Enhanced API security and authentication"
elif 'ai' in title_lower or 'assistant' in title_lower:
return "AI-powered network management capabilities"
elif 'entra' in title_lower or 'microsoft' in title_lower:
return "Microsoft identity integration features"
elif 'analytics' in title_lower:
return "Advanced network analytics and insights"
elif 'configuration' in title_lower:
return "Network configuration management tools"
else:
return "New network management features"
def parse_date(date_str):
"""Parse date string and return formatted date."""
try:
# Try different date formats
for fmt in ['%Y-%m-%d', '%m/%d/%Y', '%B %d, %Y', '%b %d, %Y']:
try:
dt = datetime.strptime(date_str.split('T')[0], fmt)
return dt.strftime("%Y-%m")
except:
continue
# If parsing fails, return current month
return datetime.now().strftime("%Y-%m")
except:
return datetime.now().strftime("%Y-%m")
# --- Helper Functions for Styling ---
def print_header(text):
"""Prints a styled header."""
print("\n" + "=" * 60)
print(f" {text.upper()} ".center(60, "="))
print("=" * 60)
def print_subheader(text):
"""Prints a styled subheader."""
print("\n" + "-" * 50)
print(f" {text} ")
print("-" * 50)
def print_wrapped(text, indent=0):
"""Prints text with wrapping and optional indentation."""
prefix = ' ' * indent
wrapper = textwrap.TextWrapper(initial_indent=prefix, subsequent_indent=prefix, width=80)
print(wrapper.fill(text))
def get_choice(prompt, options):
"""Gets a valid choice from a list of options."""
print(prompt)
for i, option in enumerate(options, 1):
print(f" [{i}] {option}")
while True:
try:
choice = int(input("> "))
if 1 <= choice <= len(options):
return options[choice - 1]
else:
print("Invalid choice. Please try again.")
except ValueError:
print("Invalid input. Please enter a number.")
def is_meraki_or_catalyst_product(product_line):
"""Detects if the product line is Meraki, Catalyst, or IOS-XE."""
if not product_line:
return False
product_lower = product_line.lower()
# Check for Meraki products
meraki_keywords = ['meraki', 'dashboard']
if any(keyword in product_lower for keyword in meraki_keywords):
return True
# Check for specific Meraki device model prefixes (more precise matching)
import re
meraki_models = ['mx', 'mr', 'mv', 'mt', 'ms']
for model in meraki_models:
# Match model prefix followed by digits (e.g., MX84, ms220)
if re.search(rf'\b{model}\d', product_lower):
return True
# Check for Catalyst products (more specific matching)
if 'catalyst' in product_lower or 'catalyst center' in product_lower:
return True
# Check for IOS-XE products
ios_xe_keywords = ['ios-xe', 'ios', 'xe']
if any(keyword in product_lower for keyword in ios_xe_keywords):
return True
return False
# --- AI Provider Management ---
class AIManager:
"""Manages multiple AI providers with fallback capabilities."""
def __init__(self):
self.available_providers = self._get_available_providers()
self.current_provider = self._get_default_provider()
def _get_available_providers(self) -> list[AIProvider]:
"""Returns list of providers with valid API keys."""
return [provider for provider, key in API_KEYS.items() if key.strip()]
def _get_default_provider(self) -> Optional[AIProvider]:
"""Returns the default provider if available, otherwise the first available one."""
if DEFAULT_PROVIDER in self.available_providers:
return DEFAULT_PROVIDER
return self.available_providers[0] if self.available_providers else None
def _create_payload(self, prompt: str, provider: AIProvider) -> Dict[str, Any]:
"""Creates the appropriate payload for each provider."""
if provider == AIProvider.GEMINI:
return {"contents": [{"role": "user", "parts": [{"text": prompt}]}]}
elif provider == AIProvider.CLAUDE:
return {
"model": "claude-3-7-sonnet-20250219",
"max_tokens": 4000,
"messages": [{"role": "user", "content": prompt}]
}
elif provider == AIProvider.OPENAI:
return {
"model": "gpt-4o",
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 4000
}
def _extract_response(self, result: Dict[str, Any], provider: AIProvider) -> str:
"""Extracts the text response from the API result."""
try:
if provider == AIProvider.GEMINI:
if "candidates" in result and result["candidates"]:
part = result["candidates"][0].get("content", {}).get("parts", [{}])[0]
if "text" in part:
return part["text"]
elif provider == AIProvider.CLAUDE:
if "content" in result and result["content"]:
return result["content"][0].get("text", "")
elif provider == AIProvider.OPENAI:
if "choices" in result and result["choices"]:
return result["choices"][0]["message"]["content"]
except (KeyError, IndexError, TypeError):
pass
return ""
def _call_provider(self, prompt: str, provider: AIProvider) -> str:
"""Makes an API call to a specific provider."""
if provider not in self.available_providers:
return f"Error: {provider.value} API key not configured."
config = API_CONFIGS[provider]
api_key = API_KEYS[provider]
# Prepare headers with authentication
headers = config["headers"].copy()
if provider == AIProvider.GEMINI:
url = f"{config['url']}?key={api_key}"
elif provider == AIProvider.CLAUDE:
headers["x-api-key"] = api_key
url = config["url"]
elif provider == AIProvider.OPENAI:
headers["Authorization"] = f"Bearer {api_key}"
url = config["url"]
payload = self._create_payload(prompt, provider)
try:
response = requests.post(url, headers=headers, json=payload, timeout=60)
response.raise_for_status()
result = response.json()
extracted_text = self._extract_response(result, provider)
if extracted_text:
return extracted_text
else:
return "Sorry, the AI could not generate a response. The response format was unexpected."
except requests.exceptions.RequestException as e:
return f"Error: API request to {provider.value} failed: {e}"
except Exception as e:
return f"An unexpected error occurred with {provider.value}: {e}"
def call_ai(self, prompt: str, preferred_provider: Optional[AIProvider] = None) -> str:
"""Calls AI with fallback support across providers."""
if not self.available_providers:
return "Error: No AI providers are configured. Please set API keys for at least one provider."
# Determine provider order
providers_to_try = []
if preferred_provider and preferred_provider in self.available_providers:
providers_to_try.append(preferred_provider)
if self.current_provider and self.current_provider not in providers_to_try:
providers_to_try.append(self.current_provider)
# Add remaining providers as fallbacks
for provider in self.available_providers:
if provider not in providers_to_try:
providers_to_try.append(provider)
# Try each provider
for i, provider in enumerate(providers_to_try):
provider_name = provider.value.title()
if i == 0:
print(f"\n✨ Calling {provider_name} AI... Please wait.")
else:
print(f"⚠️ Trying fallback provider {provider_name}...")
result = self._call_provider(prompt, provider)
# If successful, update current provider and return
if not result.startswith("Error:") and not result.startswith("Sorry,"):
self.current_provider = provider
return result
# If this was the last provider, return the error
if i == len(providers_to_try) - 1:
return result
return "Error: All AI providers failed."
def list_available_providers(self) -> list[str]:
"""Returns list of available provider names."""
return [provider.value.title() for provider in self.available_providers]
def set_provider(self, provider_name: str) -> bool:
"""Sets the current provider by name."""
try:
provider = AIProvider(provider_name.lower())
if provider in self.available_providers:
self.current_provider = provider
return True
except ValueError:
pass
return False
# Global AI manager instance
ai_manager = AIManager()
def call_ai(prompt: str, preferred_provider: Optional[str] = None) -> str:
"""Convenience function for calling AI with optional provider preference."""
provider = None
if preferred_provider:
try:
provider = AIProvider(preferred_provider.lower())
except ValueError:
pass
return ai_manager.call_ai(prompt, provider)
# --- Tool Functions ---
def vulnerability_triage():
"""Guides the user through vulnerability triage."""
print_header("Vulnerability Triage Tool")
print_wrapped("This tool will guide you through classifying your finding and identifying the correct Cisco program for your submission.")
# Step 1
finding_type_options = [
"Hardcoded credentials in a public GitHub repo",
"Exposed customer or employee PII",
"Vulnerability in a live, production Cisco/Meraki system",
"Vulnerability in a demo, test, or non-production environment",
"Operational infrastructure finding (e.g., dangling DNS, subdomain takeover)",
"A bug that seems out-of-scope but is high-impact",
"A security issue in a third-party library used by Cisco"
]
finding_type = get_choice("\nStep 1: What type of issue did you find?", finding_type_options)
# Step 2
print_subheader("Step 2: Assess the Impact (PIRR Framework)")
product_line = input("Which Cisco product line is affected? (e.g., Meraki, Catalyst) > ")
impact_options = ["Low", "Medium", "High", "Critical (e.g., RCE)"]
impact = get_choice("\nWhat is the potential impact?", impact_options)
infra_options = ["Cisco-owned cloud service/infrastructure", "Customer-deployed device/software"]
infrastructure = get_choice("\nWhere was the vulnerability found?", infra_options)
# Additional infrastructure context for Cisco-owned infrastructure
is_product_infra = None
if infrastructure == "Cisco-owned cloud service/infrastructure":
infra_type_options = ["Part of the product offering (e.g., Meraki Dashboard features)", "Operational infrastructure not part of the product (e.g., internal systems, support portals)"]
infra_type = get_choice("\nIs this infrastructure part of the product offering?", infra_type_options)
is_product_infra = "product" in infra_type.lower()
risk_options = ["No", "Yes"]
risk = get_choice("\nDoes it pose a direct risk to a business-critical function?", risk_options)
# Recommendation Logic
print_subheader("Step 3: Recommendation")
if impact == "Critical (e.g., RCE)" or risk == "Yes" or "credentials" in finding_type or "PII" in finding_type:
# Check if this is a Meraki/Catalyst/IOS-XE product for bug bounty eligibility
if is_meraki_or_catalyst_product(product_line):
program_name = "Cisco Meraki Bug Bounty Program"
program_url = "https://bugcrowd.com/ciscomeraki"
title = "High Impact Finding: Report to Bug Bounty"
text = "This appears to be a high-impact finding on a Meraki, Catalyst, or IOS-XE product. It is likely eligible for a monetary reward."
else:
program_name = "Cisco PSIRT"
program_url = "https://sec.cloudapps.cisco.com/security/center/resources/security_vulnerability_policy.html#Contact"
title = "High Impact Finding: Report to Cisco PSIRT"
text = "This appears to be a high-impact finding on a Cisco product. For ASA, FTD, ISE, Nexus, and other Cisco devices, report to Cisco PSIRT (psirt@cisco.com) for coordinated disclosure and security advisory process."
elif "Operational infrastructure finding" in finding_type or (impact in ["Low", "Medium"] and infrastructure == "Cisco-owned cloud service/infrastructure" and is_product_infra == False):
# Check if this is Meraki or Catalyst operational infrastructure
if is_meraki_or_catalyst_product(product_line):
program_name = "Cisco Meraki VDP Pro"
program_url = "https://bugcrowd.com/engagements/cisco-meraki-vdp-pro"
title = "VDP Submission: Meraki/Catalyst Operational Infrastructure"
text = "Operational infrastructure findings for Meraki and Catalyst products (including Dashboard and Center) should be reported to the Cisco Meraki VDP Pro program for coordinated disclosure."
else:
program_name = "Cisco Security VDP"
program_url = "https://bugcrowd.com/engagements/ciscosecurity"
title = "VDP Submission: Operational Infrastructure"
text = "Low-medium impact findings on operational infrastructure that is not part of the product should be reported to VDP programs for coordinated disclosure. For findings like dangling DNS without demonstrated linkage to products, VDP is the appropriate channel."
elif "demo" in finding_type or impact == "Low":
# Product-aware routing for demo environments and low impact findings
if "demo" in finding_type:
# Demo environments always go to Meraki VDP Pro regardless of product
program_name = "Cisco Meraki VDP Pro"
program_url = "https://bugcrowd.com/engagements/cisco-meraki-vdp-pro"
title = "VDP Submission Recommended"
text = "Vulnerabilities in non-production environments are perfect for our VDP."
elif is_meraki_or_catalyst_product(product_line):
# Low impact on Meraki/Catalyst/IOS-XE products go to Meraki VDP Pro
program_name = "Cisco Meraki VDP Pro"
program_url = "https://bugcrowd.com/engagements/cisco-meraki-vdp-pro"
title = "VDP Submission Recommended"
text = "Low impact findings on Meraki, Catalyst, or IOS-XE products should be reported to the Cisco Meraki VDP Pro program."
else:
# Low impact on other Cisco products go to general Cisco Security VDP
program_name = "Cisco Security VDP"
program_url = "https://bugcrowd.com/engagements/ciscosecurity"
title = "VDP Submission Recommended"
text = "Low impact findings on Cisco products should be reported to the general Cisco Security VDP program."
elif "out-of-scope" in finding_type:
program_name = "Relevant Program (Researcher's Discretion)"
program_url = "https://sec.cloudapps.cisco.com/security/center/resources/cisco_bug_bounty_faq.html"
title = "Discretionary Submission"
text = "For high-impact but out-of-scope findings, focus on the business risk in your report."
else:
program_name = "Cisco Security VDP"
program_url = "https://bugcrowd.com/engagements/ciscosecurity"
title = "General Submission: Report to VDP"
text = "For most other findings, the general Cisco Security VDP is the best place to start."
print(f"\nTitle: {title}")
print_wrapped(text)
print(f"\nRecommendation: Submit to the {program_name}")
print(f"URL: {program_url}")
def submission_quality():
"""Analyzes submission quality and uses AI to enhance reports."""
print_header("Submission Quality Analyzer")
# Checklist
checklist_items = [
"Clear and concise title",
"Affected product and version",
"Step-by-step, reproducible PoC",
"Business impact is clearly explained",
"Includes logs, screenshots, or a video"
]
print_subheader("Submission Checklist")
score = 0
for item in checklist_items:
response = input(f"- Have you included a {item}? (y/n) > ").lower()
if response == 'y':
score += 1
print(f"\nChecklist Score: {score}/{len(checklist_items)}")
if score == len(checklist_items):
print("Excellent! This looks like a solid report.")
else:
print("Consider adding the missing items to improve your report's quality.")
# AI Report Enhancer
print_subheader("AI Report Enhancer")
# Show available providers
available_providers = ai_manager.list_available_providers()
if available_providers:
print(f"Available AI providers: {', '.join(available_providers)}")
if len(available_providers) > 1:
provider_choice = get_choice("Choose AI provider:", available_providers + ["Auto (use default)"])
if provider_choice != "Auto (use default)":
ai_manager.set_provider(provider_choice.lower())
print_wrapped("Enter your brief technical notes or PoC, and AI will help you draft a professional report.")
tech_notes = input("Enter your technical notes:\n> ")
if tech_notes.strip():
prompt = f"As a security researcher, write a professional vulnerability report based on the following notes. The report should be well-structured with clear sections for Title, Executive Summary, Technical Description, Proof of Concept (PoC), and Business Impact. \n\nTechnical Notes:\n{tech_notes}"
report_draft = call_ai(prompt)
print_subheader("Generated Report Draft")
print(report_draft)
else:
print("No notes entered. Skipping report enhancement.")
def determine_testing_methodologies(topic):
"""Determines appropriate testing methodologies based on topic keywords."""
topic_lower = topic.lower()
methodologies = []
# IoT/Hardware keywords
if any(keyword in topic_lower for keyword in ['iot', 'device', 'hardware', 'sensor', 'embedded', 'uart', 'jtag', 'gpio', 'meraki']):
methodologies.append({
'name': 'OWASP IoT Security Testing Guide (ISTG)',
'url': 'https://owasp.org/owasp-istg/',
'key': 'istg',
'description': 'For IoT devices, hardware security, and embedded systems',
'areas': ['Hardware Security', 'Firmware Analysis', 'Data Protection', 'Communication Security']
})
# Firmware keywords
if any(keyword in topic_lower for keyword in ['firmware', 'bootloader', 'bios', 'embedded', 'flash', 'rom']):
methodologies.append({
'name': 'OWASP Firmware Security Testing Methodology (FSTM)',
'url': 'https://github.com/scriptingxss/owasp-fstm',
'key': 'fstm',
'description': 'For firmware analysis, reverse engineering, and binary security',
'areas': ['Static Analysis', 'Dynamic Analysis', 'Reverse Engineering', 'Binary Exploitation']
})
# AI/ML keywords
if any(keyword in topic_lower for keyword in ['ai', 'artificial intelligence', 'ml', 'machine learning', 'assistant', 'canvas', 'chatbot', 'llm', 'genai', 'generative', 'model', 'neural']):
methodologies.append({
'name': 'OWASP AI Testing Guide',
'url': 'https://github.com/OWASP/www-project-ai-testing-guide',
'key': 'aitg',
'description': 'For AI/ML systems, LLMs, and intelligent assistants',
'areas': ['Model Security', 'Prompt Injection', 'Privacy & Ethics', 'Runtime Behavior']
})
# Web/API keywords
if any(keyword in topic_lower for keyword in ['api', 'web', 'dashboard', 'portal', 'interface', 'service', 'cloud', 'authentication', 'session']):
methodologies.append({
'name': 'OWASP Web Security Testing Guide (WSTG)',
'url': 'https://owasp.org/www-project-web-security-testing-guide',
'key': 'wstg',
'description': 'For web applications, APIs, and cloud services',
'areas': ['Authentication Testing', 'Session Management', 'Input Validation', 'Business Logic']
})
# Default to WSTG if no specific match
if not methodologies:
methodologies.append({
'name': 'OWASP Web Security Testing Guide (WSTG)',
'url': 'https://owasp.org/www-project-web-security-testing-guide',
'key': 'wstg',
'description': 'General security testing approach',
'areas': ['Authentication Testing', 'Session Management', 'Input Validation', 'Business Logic']
})
return methodologies
def create_methodology_prompt(topic, methodologies):
"""Creates an AI prompt enhanced with methodology-specific context."""
methodology_context = ''
for method in methodologies:
if method['key'] == 'istg':
methodology_context += ' Consider IoT-specific attack vectors including: hardware interface exploitation (UART, JTAG), firmware extraction and analysis, wireless communication interception, device authentication bypass, and cloud-to-device communication vulnerabilities.'
elif method['key'] == 'fstm':
methodology_context += ' Focus on firmware-specific techniques including: static binary analysis, dynamic firmware emulation, bootloader security, cryptographic implementation flaws, and reverse engineering for hidden functionality.'
elif method['key'] == 'aitg':
methodology_context += ' Include AI/ML security attack vectors such as: prompt injection attacks on AI assistants, model extraction and poisoning, adversarial input crafting, training data leakage, bias exploitation, jailbreaking conversational AI, hallucination exploitation, and AI Canvas model manipulation.'
elif method['key'] == 'wstg':
methodology_context += ' Include web application attack vectors such as: authentication and session management flaws, input validation bypasses, business logic vulnerabilities, API security issues, and cloud configuration weaknesses.'
return f"I am a security researcher looking for vulnerabilities in Cisco products. Brainstorm a list of 5-7 creative and specific attack vectors or security research ideas for the following topic: \"{topic}\".{methodology_context} Focus on potential weaknesses that a real researcher would investigate using appropriate testing methodologies. Format the output as a numbered list with brief descriptions."
def research_areas():
"""Suggests research areas using static lists and AI."""
print_header("Suggested Research Areas")
# Static list
print_subheader("High-Value Targets")
high_value_targets = [
"API Security (AuthN/AuthZ, Rate Limiting)",
"Cross-Tenant Data Access Vulnerabilities",
"Hardware-Specific Attacks (JTAG, UART)",
"Supply Chain Security (Third-party libraries)",
"Cloud Infrastructure Misconfigurations"
]
for target in high_value_targets:
print(f"- {target}")
# Recent High-Value Releases (Date-Prioritized)
print_subheader("Recent High-Value Releases")
print("🔥 Latest releases prioritized by date (newest attack surfaces first):")
# Fetch live data with fallback to static
recent_releases = fetch_recent_releases()
# Check if we got live data or fallback
is_live_data = any(release.get("type") == "Feature" and "Debug:" not in release.get("title", "")
for release in recent_releases
if release.get("title") not in [r["title"] for r in RECENT_HIGH_VALUE_RELEASES])
if is_live_data:
print("📡 Showing live data from Meraki Community")
else:
print("⚠️ Using cached/fallback data - live fetch may have failed")
for release in recent_releases:
# Format date for display
date_str = release.get("date", "2024-12")
if "-" in date_str:
year, month = date_str.split("-")
month_names = {"01": "Jan", "02": "Feb", "03": "Mar", "04": "Apr", "05": "May",
"06": "Jun", "07": "Jul", "08": "Aug", "09": "Sep", "10": "Oct",
"11": "Nov", "12": "Dec"}
date_formatted = f"{month_names.get(month, month)} {year}"
else:
date_formatted = date_str
# Display with appropriate emoji based on type
emoji = "🔥" if "type" not in release or release["type"] == "Feature" else "⚙️"
print(f"{emoji} [{date_formatted}] {release['title']} - {release.get('description', 'New release')} ({release.get('category', 'Feature')})")
print_wrapped("\nMonitor these channels for the latest updates:")
for name, url in CISCO_RELEASE_RESOURCES.items():
print(f"- {name}: {url}")
# AI Suggester
print_subheader("AI Research Suggester")
# Show available providers
available_providers = ai_manager.list_available_providers()
if available_providers:
print(f"Available AI providers: {', '.join(available_providers)}")
if len(available_providers) > 1:
provider_choice = get_choice("Choose AI provider:", available_providers + ["Auto (use default)"])
if provider_choice != "Auto (use default)":
ai_manager.set_provider(provider_choice.lower())
print_wrapped("Enter a product or technology (e.g., 'Meraki SD-WAN', 'API Security') to get AI-powered research ideas.")
topic = input("> ")
if topic.strip():
# Determine relevant testing methodologies
methodologies = determine_testing_methodologies(topic)
# Display recommended methodologies
print_subheader("Recommended Testing Methodologies")
for method in methodologies:
print(f"\n📋 {method['name']}")
print(f" {method['description']}")
print(f" Key areas: {', '.join(method['areas'])}")
print(f" URL: {method['url']}")
# Create enhanced prompt with methodology context
prompt = create_methodology_prompt(topic, methodologies)
suggestions = call_ai(prompt)
print_subheader(f"AI-Generated Attack Vectors for '{topic}'")
print(suggestions)
# Add methodology reference footer
print_subheader("Learn More")
print("Explore these OWASP testing guides for detailed methodologies:")
for method in methodologies:
if method['key'] == 'istg':
print("• OWASP ISTG - Hardware testing, firmware analysis, communication security")
elif method['key'] == 'fstm':
print("• OWASP FSTM - Firmware extraction, binary analysis, reverse engineering")
elif method['key'] == 'aitg':
print("• OWASP AI Testing Guide - AI security, prompt injection, model vulnerabilities")
elif method['key'] == 'wstg':
print("• OWASP WSTG - Web security, API testing, authentication flaws")
print(f" {method['url']}")
else:
print("No topic entered. Skipping AI suggestions.")
def testing_guides():
"""Displays links to testing guides."""
print_header("Industry-Standard Testing Guides")
guides = {
"OWASP IoT Security Testing Guide (ISTG)": "https://owasp.org/owasp-istg/",
"OWASP Firmware Security Testing Methodology (FSTM)": "https://github.com/scriptingxss/owasp-fstm",
"OWASP AI Testing Guide": "https://github.com/OWASP/www-project-ai-testing-guide",
"OWASP Web Security Testing Guide (WSTG)": "https://owasp.org/www-project-web-security-testing-guide"
}
for name, url in guides.items():
print(f"\n- {name}")
print(f" {url}")
print_subheader("Guide Descriptions")
print("• ISTG: Essential guide for testing Internet of Things devices, from hardware to cloud")
print("• FSTM: Deep dive into analyzing and finding vulnerabilities in device firmware")
print("• AI Testing Guide: Comprehensive methodologies for testing AI/ML systems, LLMs, and intelligent assistants")
print("• WSTG: Premier guide for testing the security of web applications and services")
def configure_ai():
"""Configure AI provider settings."""
print_header("AI Provider Configuration")
print_subheader("Available Providers")
all_providers = list(AIProvider)
for provider in all_providers:
key = API_KEYS[provider]
status = "✅ Configured" if key.strip() else "❌ Not configured"
print(f"- {provider.value.title()}: {status}")
available_providers = ai_manager.list_available_providers()
if available_providers:
print(f"\nCurrently using: {ai_manager.current_provider.value.title() if ai_manager.current_provider else 'None'}")
choice = get_choice("\nWhat would you like to do?", [
"Switch default provider",
"View configuration instructions",
"Return to main menu"
])
if choice == "Switch default provider":
if len(available_providers) > 1:
new_provider = get_choice("Choose new default provider:", available_providers)
if ai_manager.set_provider(new_provider.lower()):
print(f"✅ Default provider switched to {new_provider}")
else:
print("❌ Failed to switch provider")
else:
print("Only one provider is configured.")
elif choice == "View configuration instructions":
print_subheader("Configuration Instructions")
print("Set environment variables for the AI providers you want to use:")
print("- GEMINI_API_KEY=your_gemini_key")
print("- CLAUDE_API_KEY=your_claude_key")
print("- OPENAI_API_KEY=your_openai_key")
print("- DEFAULT_AI_PROVIDER=gemini|claude|openai (optional)")
else:
print_subheader("No AI Providers Configured")
print("Please set at least one API key as an environment variable:")
print("- GEMINI_API_KEY=your_gemini_key")
print("- CLAUDE_API_KEY=your_claude_key")
print("- OPENAI_API_KEY=your_openai_key")
def main():
"""Main function to run the CLI application."""
while True:
print_header("Cisco Researcher Toolkit - CLI")
# Show disclaimer
print("⚠️ IMPORTANT: By participating in Cisco's security research programs, you acknowledge")
print(" and agree you are registered with Bugcrowd and bound by their Code of Conduct")
print(" and Standard Disclosure Terms.")
# Show AI status
available_providers = ai_manager.list_available_providers()
if available_providers:
current = ai_manager.current_provider.value.title() if ai_manager.current_provider else "None"
print(f"AI Status: {len(available_providers)} provider(s) available | Using: {current}")
else:
print("⚠️ AI Status: No providers configured")
menu_options = [
"Vulnerability Triage Tool",
"Submission Quality Analyzer",
"Suggested Research Areas",
"Testing Guides",
"Configure AI Providers",
"Exit"
]
choice = get_choice("Select a tool:", menu_options)
if choice == "Vulnerability Triage Tool":
vulnerability_triage()
elif choice == "Submission Quality Analyzer":
submission_quality()
elif choice == "Suggested Research Areas":
research_areas()
elif choice == "Testing Guides":
testing_guides()
elif choice == "Configure AI Providers":
configure_ai()
elif choice == "Exit":
print("\nHappy hunting!")
break
input("\nPress Enter to return to the main menu...")
if __name__ == "__main__":
main()