{{ message }}
Repository navigation
Expand file tree
/
Copy pathai_service.py
More file actions
executable file
·1145 lines (944 loc) · 49.3 KB
/
Copy pathai_service.py
File metadata and controls
executable file
·1145 lines (944 loc) · 49.3 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
#!/usr/bin/env python3
"""
AI Service for Ragnar
GPT-5 version using OpenAI SDK 2.x
Provides intelligent network analysis, summaries, and insights.
"""
import os
import json
import time
import logging
from datetime import datetime
from typing import Dict, List, Optional, Any
try:
from openai import OpenAI
except Exception: # noqa: BLE001 — SDK optional
# The openai SDK may be absent on a lean/airgapped image. Importing this
# module must still succeed so the non-LLM helpers (normalize_base_url, the
# endpoint discovery/listing routes) keep working; real AI calls raise a
# clear, actionable error instead of a 500. Heal with the Ragnar updater or
# `pip install "openai>=2.0.0"`.
OpenAI = None
_OPENAI_MISSING_MSG = ("The 'openai' package is not installed — run the Ragnar "
"updater, or: pip install 'openai>=2.0.0'.")
from logger import Logger
from env_manager import EnvManager, load_env
def normalize_base_url(url: str) -> str:
"""Tidy an OpenAI-compatible base URL so common shorthands just work.
Adds a missing http:// scheme, strips trailing slashes, and appends the
conventional ``/v1`` path when the operator gave only a host[:port] (every
supported server — Ollama, LocalAI, vLLM, LM Studio — serves the OpenAI API
under /v1). The port is never guessed. Empty input stays empty.
"""
import re
from urllib.parse import urlparse
url = (url or "").strip()
if not url:
return ""
if not re.match(r"^https?://", url, re.IGNORECASE):
url = "http://" + url
url = url.rstrip("/")
if urlparse(url).path in ("", "/"):
url = url + "/v1"
return url
# Load environment variables immediately
load_env()
# ===================================================================
# AI SERVICE
# ===================================================================
class AIService:
"""AI-powered network analysis, vulnerability interpretation, and insights."""
def __init__(self, shared_data):
self.shared_data = shared_data
self.logger = Logger(name="AIService", level=logging.INFO)
self.env_manager = EnvManager()
cfg = shared_data.config
# Configuration
self.enabled = cfg.get("ai_enabled", False)
self.model = cfg.get("ai_model", "gpt-5.4-nano")
# Self-hosted / OpenAI-compatible endpoint support (issue #462).
# When ai_base_url is set (e.g. an Ollama/LocalAI/vLLM/LM Studio server
# on the LAN or mesh), Ragnar talks to it as a thin HTTP client and
# uses the Chat Completions API — local servers implement /v1/chat/
# completions, not OpenAI's proprietary Responses API. Empty base URL
# keeps the default OpenAI Responses behavior unchanged.
self.base_url = normalize_base_url(cfg.get("ai_base_url", ""))
self.use_chat_api = self._resolve_use_chat_api()
# OpenAI-cloud fallback for when a self-hosted endpoint goes away
# (issue #462). Built lazily the first time it's needed.
self._fallback_client = None
self._fallback_model = None
self.fallback_active = False # True while running on the cloud fallback
# These must remain for backward compatibility (but not used)
self.max_tokens = cfg.get("ai_max_tokens")
self.temperature = cfg.get("ai_temperature")
self.temperature_supported = True # will disable on first failure
self.vulnerability_summaries = cfg.get("ai_vulnerability_summaries", True)
self.network_insights = cfg.get("ai_network_insights", True)
self.api_token = self.env_manager.get_token()
# Cache
self.cache = {}
self.cache_ttl = 3600 # 1 hour (3600 seconds) - reduce token consumption
# Client initialization
self.client = None
self.initialization_error = None
self._initialize_client()
# ===================================================================
# INITIALIZATION
# ===================================================================
def _resolve_use_chat_api(self):
"""Decide which API dialect to speak.
``ai_api_style`` ('auto'|'responses'|'chat') overrides when set;
otherwise a configured base URL implies a self-hosted, Chat-Completions
server and the default OpenAI cloud uses the Responses API.
"""
style = str(self.shared_data.config.get("ai_api_style", "auto") or "auto").strip().lower()
if style == "chat":
return True
if style == "responses":
return False
return bool(self.base_url)
def _initialize_client(self):
if not self.enabled:
return
# A real key is mandatory for OpenAI's cloud, but self-hosted endpoints
# usually accept any non-empty string — the SDK still requires one, so
# fall back to a harmless placeholder when the operator left it blank.
if not self.api_token and not self.base_url:
self.initialization_error = "No OpenAI API key found."
self.logger.warning(self.initialization_error)
return
if OpenAI is None:
self.client = None
self.initialization_error = _OPENAI_MISSING_MSG
self.logger.warning(self.initialization_error)
return
try:
# Bound every request: the SDK default is 600s, so a single stuck or
# rate-limited call (common when several field units share one API
# key and each fans out concurrent dashboard calls) would otherwise
# hang for minutes — well past any client timeout — instead of
# failing fast and letting the rest of the insights render. One retry
# keeps the worst-case bounded (~40s/call) so the background insights
# run resolves quickly even on a slow board.
client_kwargs = {
"api_key": self.api_token or "ragnar-local",
"timeout": 20.0,
"max_retries": 1,
}
if self.base_url:
client_kwargs["base_url"] = self.base_url
self.client = OpenAI(**client_kwargs)
self.initialization_error = None
endpoint = self.base_url or "OpenAI"
api_dialect = "chat.completions" if self.use_chat_api else "responses"
self.logger.info(
f"AI Service initialized (model: {self.model}, endpoint: {endpoint}, api: {api_dialect})"
)
except Exception as exc:
self.client = None
self.initialization_error = f"OpenAI client initialization failed: {exc}"
self.logger.error(self.initialization_error)
def reload_token(self) -> bool:
"""Refresh the API token from disk and reinitialize the OpenAI client."""
# Keep enabled flag + endpoint config synced with latest config intent
if hasattr(self.shared_data, "config"):
cfg = self.shared_data.config
self.enabled = cfg.get("ai_enabled", self.enabled)
self.model = cfg.get("ai_model", self.model)
self.base_url = normalize_base_url(cfg.get("ai_base_url", ""))
self.use_chat_api = self._resolve_use_chat_api()
# Force the cloud fallback to rebuild with the latest token/model.
self._fallback_client = None
self.fallback_active = False
self.api_token = self.env_manager.get_token()
self.client = None
self.initialization_error = None
if not self.enabled:
self.logger.info("AI service disabled in config; skipping token reload.")
return False
if not self.api_token and not self.base_url:
self.logger.warning("AI token reload requested but no token present in environment.")
self.initialization_error = "No OpenAI API key found."
return False
self._initialize_client()
success = self.client is not None and self.initialization_error is None
if success:
self.logger.info("AI service reloaded with updated token.")
else:
if self.initialization_error:
self.logger.error(
f"AI service failed to reinitialize after token reload: {self.initialization_error}"
)
else:
self.logger.error("AI service failed to reinitialize after token reload.")
return success
def complete(self, user_msg: str, system_msg: Optional[str] = None) -> Optional[str]:
"""One-shot completion returning the model's raw text (or None).
Public entry over the unified `_ask` call, used by callers that need the
AI to emit a structured artifact rather than a cached 'analysis' — e.g.
the Ulfberht playbook generator. Routes OpenAI vs self-hosted the same
way every other call does. Returns None when AI is disabled/unavailable.
"""
if system_msg is None:
system_msg = ("You are a security automation assistant. Output exactly one "
"JSON object and nothing else — no prose, no markdown fences.")
return self._ask(system_msg, user_msg)
# ===================================================================
# UTILITY HELPERS
# ===================================================================
def is_enabled(self):
"""Return True when the service is enabled and the client is ready."""
return self.ensure_ready()
def ensure_ready(self):
"""Lazily initialize the OpenAI client if configuration says AI is enabled."""
# Sync enabled state with config in case it changed
if hasattr(self.shared_data, "config"):
self.enabled = self.shared_data.config.get("ai_enabled", self.enabled)
if not self.enabled:
return False
# Already initialized and healthy
if self.client is not None and self.initialization_error is None:
return True
# Don't keep retrying when we've already recorded a permanent failure
# But allow retry if token was added after initial failure
if self.initialization_error and self.api_token:
# Clear error and retry if we have a token now
self.initialization_error = None
# Refresh token from disk if we don't have one yet
if not self.api_token:
self.api_token = self.env_manager.get_token()
# A token is only mandatory for the OpenAI cloud; a self-hosted base URL
# can run keyless.
if not self.api_token and not self.base_url:
self.initialization_error = "No OpenAI API key found."
self.logger.warning(self.initialization_error)
return False
self._initialize_client()
return self.client is not None and self.initialization_error is None
def _cache_key(self, name: str, content: Any):
import hashlib
raw = f"{name}:{json.dumps(content, sort_keys=True)}"
return hashlib.md5(raw.encode()).hexdigest()
def _cache_get(self, key: str):
item = self.cache.get(key)
if not item:
return None
if time.time() - item["timestamp"] > self.cache_ttl:
del self.cache[key]
return None
return item["value"]
def _cache_set(self, key: str, value: Any):
self.cache[key] = {"timestamp": time.time(), "value": value}
# ===================================================================
# CORE GPT-5 CALL — NEW RESPONSES API
# ===================================================================
def _ask(self, system_msg: str, user_msg: str) -> Optional[str]:
"""
Unified GPT-5 call with temperature fallback (required for tests).
"""
if not self.is_enabled():
return None
if self.client is None:
self.logger.error("AI client unavailable despite service being enabled.")
return None
# Self-hosted / OpenAI-compatible servers speak Chat Completions, not
# the proprietary Responses API — route them separately.
if self.use_chat_api:
return self._ask_chat(system_msg, user_msg)
return self._ask_responses(system_msg, user_msg)
def _ask_responses(self, system_msg, user_msg, client=None, model=None):
"""OpenAI Responses-API call (GPT-5 family). Reused for both the primary
cloud path and the self-hosted fallback (with a cloud client + model)."""
client = client or self.client
model = model or self.model
payload = {
"model": model,
"input": [
{"role": "system", "content": system_msg},
{"role": "user", "content": user_msg},
],
"reasoning": {"effort": "low"},
"text": {"verbosity": "low"},
}
# Include temperature ONLY if still marked supported
if self.temperature_supported and self.temperature is not None:
payload["temperature"] = self.temperature
# FIRST ATTEMPT
try:
result = client.responses.create(**payload)
return self._extract_output(result)
except Exception as e:
error_text = str(e).lower()
# Handle GPT-5 "temperature unsupported" case
if "temperature" in error_text and "unsupported" in error_text:
self.temperature_supported = False
self.logger.warning(
"Model reported temperature as unsupported — retrying without it."
)
payload.pop("temperature", None)
# SECOND ATTEMPT WITHOUT TEMPERATURE
try:
result = client.responses.create(**payload)
return self._extract_output(result)
except Exception as e2:
self.logger.error(f"Retry after removing temperature failed: {e2}")
return None
self.logger.error(f"OpenAI call failed: {e}")
return None
def _ask_chat(self, system_msg: str, user_msg: str) -> Optional[str]:
"""Chat Completions call for self-hosted OpenAI-compatible endpoints.
No reasoning/verbosity params (unsupported by local servers); reads the
classic ``choices[0].message.content`` response shape.
"""
payload = {
"model": self.model,
"messages": [
{"role": "system", "content": system_msg},
{"role": "user", "content": user_msg},
],
}
if self.temperature_supported and self.temperature is not None:
payload["temperature"] = self.temperature
try:
result = self.client.chat.completions.create(**payload)
except Exception as e:
error_text = str(e).lower()
if "temperature" in error_text and payload.pop("temperature", None) is not None:
self.temperature_supported = False
self.logger.warning("Endpoint rejected temperature — retrying without it.")
try:
result = self.client.chat.completions.create(**payload)
except Exception as e2:
return self._maybe_fallback(system_msg, user_msg, e2)
else:
return self._maybe_fallback(system_msg, user_msg, e)
# A successful self-hosted call clears any prior fallback state.
self.fallback_active = False
# Usage fields on OpenAI-compatible servers use prompt/completion naming.
usage = getattr(result, "usage", None)
if usage is not None:
self.logger.info(
"AI Tokens → input:{} output:{} total:{}".format(
getattr(usage, "prompt_tokens", "?"),
getattr(usage, "completion_tokens", "?"),
getattr(usage, "total_tokens", "?"),
)
)
try:
content = result.choices[0].message.content
return content.strip() if content else None
except (AttributeError, IndexError, TypeError):
self.logger.error("Self-hosted AI response had no message content.")
return None
def _maybe_fallback(self, system_msg, user_msg, error):
"""Retry a failed self-hosted call on OpenAI's cloud when the endpoint
looks unreachable and a token is configured (issue #462)."""
if self._should_fallback(error):
fb = self._ensure_fallback_client()
if fb is not None:
self.logger.warning(
f"Self-hosted endpoint unavailable ({error}); falling back to "
f"OpenAI cloud (model: {self._fallback_model})."
)
self.fallback_active = True
return self._ask_responses(
system_msg, user_msg, client=fb, model=self._fallback_model
)
self.logger.error(f"Self-hosted AI call failed: {error}")
return None
def _should_fallback(self, error):
"""True when the error looks like the endpoint is unreachable / timed
out, rather than a bad request the cloud would also reject."""
if type(error).__name__ in (
"APIConnectionError", "APITimeoutError", "InternalServerError",
"ConnectionError", "Timeout", "ConnectTimeout", "ReadTimeout",
):
return True
msg = str(error).lower()
return any(s in msg for s in (
"connection", "timed out", "timeout", "refused", "unreachable",
"failed to establish", "max retries", "connect", "temporarily unavailable",
))
def _ensure_fallback_client(self):
"""Lazily build an OpenAI-cloud client used only for fallback. Requires a
real token; returns None when none is configured (so no fallback)."""
if not self.base_url:
return None # already on the cloud — no separate fallback needed
if self._fallback_client is not None:
return self._fallback_client
if OpenAI is None:
return None # SDK absent — no cloud fallback possible
token = self.api_token or self.env_manager.get_token()
if not token:
return None
try:
self._fallback_client = OpenAI(api_key=token, timeout=20.0, max_retries=1)
self._fallback_model = (
str(self.shared_data.config.get("ai_fallback_model", "") or "").strip()
or "gpt-5.4-nano"
)
self.logger.info(f"AI cloud fallback ready (model: {self._fallback_model}).")
return self._fallback_client
except Exception as e:
self.logger.warning(f"Could not initialize AI fallback client: {e}")
return None
def _extract_output(self, result):
"""Extract output text and log token usage."""
if hasattr(result, "usage"):
u = result.usage
self.logger.info(
f"AI Tokens → input:{u.input_tokens} output:{u.output_tokens} total:{u.total_tokens}"
)
try:
return result.output_text.strip()
except:
return None
# ===================================================================
# NETWORK SUMMARY
# ===================================================================
def analyze_network_summary(self, network_data):
if not self.is_enabled() or not self.network_insights:
return None
key = self._cache_key("summary", network_data)
cached = self._cache_get(key)
if cached:
return cached
system = (
"You are Ragnar, a witty cybersecurity Viking AI. "
"Provide concise, aggressive but clear summaries."
)
user = f"""
Analyze this network scan:
Targets: {network_data.get('target_count')}
Open Ports: {network_data.get('port_count')}
Vulnerabilities Found: {network_data.get('vulnerability_count')}
Credentials Found: {network_data.get('credential_count')}
Give a 2–3 sentence Viking-style summary.
"""
resp = self._ask(system, user)
if resp:
self._cache_set(key, resp)
return resp
# ===================================================================
# VULNERABILITY ANALYSIS
# ===================================================================
def analyze_vulnerabilities(self, vulnerabilities: List[Dict]):
if not self.is_enabled() or not self.vulnerability_summaries:
return None
key = self._cache_key("vuln_analysis", {"count": len(vulnerabilities)})
cached = self._cache_get(key)
if cached:
return cached
limited = vulnerabilities[:10]
data_json = json.dumps(limited, indent=2)
system = (
"You are Ragnar, an elite vulnerability hunter. "
"Structure your analysis clearly with sections and bullet points. "
"Use markdown-style formatting for readability."
)
user = f"""
Vulnerabilities Detected: {len(vulnerabilities)}
Top Findings:
{data_json}
Provide a structured analysis:
First, give a brief Viking-style tactical summary (max 50 words) of the overall vulnerability situation.
Then provide detailed analysis:
**Critical Weaknesses:**
- List the most severe vulnerabilities (CVE numbers if available)
- Include affected hosts/ports
- Note severity ratings
**Immediate Actions Required:**
- Prioritized remediation steps
- What to patch/fix first
- Quick wins for risk reduction
**Overall Risk Assessment:**
- Current attack surface severity (Critical/High/Medium)
- Potential impact if exploited
- Recommended timeline for fixes
Tone: Direct, tactical Viking strategist. Use bullet points and clear sections.
"""
resp = self._ask(system, user)
if resp:
self._cache_set(key, resp)
return resp
# ===================================================================
# PCAP ANALYSIS (general network fault diagnosis)
# ===================================================================
def analyze_pcap(self, data: Dict):
"""Interpret a PCAP-analysis summary (from network_diagnostics) and tell
the user what is WRONG with the network. Covers the whole stack — L2
(ARP/broadcast storms, duplicate IPs), TCP health (retransmits, resets,
zero-windows, dup-ACKs), DNS/DHCP, TLS handshakes — and treats Wi-Fi/AP
client-drops as a special case when it's an 802.11 capture. `data` is the
dict returned by do_pcap_analyze (summary/protocols/talkers/expert/wifi).
Returns a plain-language root-cause read, or None if AI is unavailable."""
if not self.is_enabled():
return None
wifi = (data or {}).get('wifi') or {}
summary = (data or {}).get('summary') or {}
expert = (data or {}).get('expert') or {}
protos = (data or {}).get('protocols') or []
# Key the cache on what actually drives the verdict, not just packet count
# + Wi-Fi fields — otherwise two unrelated non-Wi-Fi captures with the same
# packet count collide and get served each other's analysis. The expert
# findings + protocol mix uniquely fingerprint what the AI will say.
key = self._cache_key("pcap_analysis", {
"pkts": summary.get('packets'),
"bytes": summary.get('data_size'),
"dur": summary.get('duration_s'),
"exp": (expert.get('errors'), expert.get('warnings'), expert.get('notes')),
"items": [(i.get('protocol'), i.get('summary'), i.get('count'))
for i in (expert.get('items') or [])[:10]],
"protos": [(p.get('proto'), p.get('bytes')) for p in protos[:10]],
"wifi": {
"deauth": (wifi.get('deauth') or {}).get('total'),
"disassoc": (wifi.get('disassoc') or {}).get('total'),
"retry": wifi.get('retry_pct'),
} if wifi else None,
})
cached = self._cache_get(key)
if cached:
return cached
# Keep the prompt compact: send the summary, expert findings, and (if
# present) the Wi-Fi event breakdown that actually explains drops.
payload = {
'summary': summary,
'expert': (data or {}).get('expert'),
'top_protocols': ((data or {}).get('protocols') or [])[:15],
'top_talkers': ((data or {}).get('talkers') or [])[:8],
'wifi': wifi or None,
}
data_json = json.dumps(payload, indent=2, default=str)[:6000]
is_wifi = bool(wifi.get('is_wifi'))
system = (
"You are a senior network engineer triaging a packet capture. Decide whether the "
"network is HEALTHY or has a real problem, and if so diagnose the ROOT CAUSE from "
"the evidence in plain language a field tech can act on. Reason across the whole "
"stack: L2 (ARP/broadcast/multicast storms, duplicate IPs, spanning-tree churn), "
"TCP health (retransmissions, resets, zero-windows, dup-ACKs, out-of-order, "
"high RTT), DNS and DHCP failures/latency, TLS/handshake errors, and — for "
"802.11 captures — deauth/disassoc reason codes and retry rates that drive "
"client drops. "
"CALIBRATE SEVERITY AGAINST VOLUME: a small number of RSTs, duplicate ACKs, "
"retransmissions, and normal FIN-based connection closes is EXPECTED, especially "
"for ordinary web/TLS browsing — judge by RATES relative to total packets/bytes "
"and to the number of conversations, not by raw counts. Normal connection teardown "
"(FIN / 'connection closing') is NOT a fault, and a few RSTs are how clients "
"routinely close sessions. Do not describe the network as 'unstable' or 'degraded' "
"unless the error rate is clearly disproportionate to the traffic. If the capture "
"looks healthy, SAY SO plainly (make that the Verdict) rather than manufacturing a "
"problem. "
"Be specific and quote the counts/codes. Do not invent data not present in the "
"summary. When you cite a Wireshark/tshark display filter or CLI command, use only "
"valid, real syntax (e.g. tcp.analysis.retransmission, tcp.flags.reset==1, "
"tcp.analysis.duplicate_ack) and parenthesize mixed AND/OR filters correctly; if "
"unsure of the exact filter, describe what to match in words rather than inventing "
"a field name. Use short markdown sections and bullet points."
)
focus = (
"This is a Wi-Fi / access-point capture: pay special attention to WHY CLIENTS "
"ARE DROPPING / DISCONNECTING (deauth/disassoc reason codes, retry %, AP "
"behavior), but still flag any other network problems you see." if is_wifi else
"Diagnose the most impactful problems in this capture across every layer — "
"not just one — and rank them by how much they hurt the network. If nothing "
"rises above normal background noise, say the capture looks healthy."
)
user = f"""{focus}
Packet-capture summary (JSON):
{data_json}
Provide:
**Verdict** - is the network healthy, or the single most likely root cause if not (1-2 sentences).
**Evidence** - the specific counts / reason codes / status codes / expert
findings that point to it, quoted from the summary.
**Other factors** - secondary issues worth noting (only if supported by the data).
**Fix it** - concrete, prioritized remediation steps a technician can take.
Keep it tight and practical. If the data is inconclusive, say so and name the
one capture/filter that would confirm it."""
resp = self._ask(system, user)
if resp:
self._cache_set(key, resp)
return resp
def analyze_signal(self, question: str, context: Dict, facts: Dict = None):
"""RF-analyst assistant for the Signal Analyzer (SigMF IQ captures).
Acts as an expert RF / SIGINT / signal-reverse-engineering analyst: helps
the user interpret the analyzer's measurements, choose demod parameters,
read a recovered bitstream / frame structure / CRC, guess the likely
device or protocol, and decide the next step. ``context`` is what the page
currently shows (summary, classification, bursts, demod bits, frame
analysis, decoded devices, marker); ``facts`` are freshly-measured values
the server re-derived from the capture so the AI is grounded in real
numbers. Chat-style, so this is NOT cached. Returns text, or None."""
if not self.is_enabled():
return None
merged = dict(context or {})
if facts:
merged["measured"] = facts
ctx_json = json.dumps(merged, indent=2, default=str)[:7000]
q = (question or "").strip() or "What is this signal, and how would I decode it?"
system = (
"You are a senior RF / SIGINT and signal-reverse-engineering analyst helping a user "
"at a software-defined-radio workbench. They have captured raw IQ (a SigMF recording "
"from an RTL-SDR, ~24 MHz-1.7 GHz, receive-only) and are looking at an on-device "
"analyzer: spectrogram, PSD, envelope, automatic burst detection, an OOK/AM & FSK/FM "
"demodulator that recovers a bitstream, a modulation classifier, and a protocol tool "
"(preamble / repeated-frame alignment / CRC scan). "
"Your job: interpret the measurements and TEACH the user how a professional would "
"proceed - what the signal likely is, which band/service it belongs to, what "
"modulation and symbol rate the numbers imply, how to set the demod (centre offset, "
"bandwidth, OOK vs FSK), how to read the recovered bits / frame structure / CRC, and "
"the single best NEXT step. "
"IMPORTANT HONESTY RULES: the analyzer's dB values are RELATIVE (uncalibrated), not "
"absolute dBm - never present them as calibrated power. LoRa / chirp-spread and most "
"digital mesh (Meshtastic) CANNOT be demodulated here - it is energy/occupancy only; "
"say so. Rolling-code remotes and unlisted protocols won't be 'named' by rtl_433 - "
"explain what the bits still tell you (fixed vs rolling fields). Do NOT invent values "
"that aren't in the provided context; if something needed isn't there, tell the user "
"which analyzer control to use to get it. Reference the analyzer's own controls by "
"name (Zoom/Measure, Demodulate, BW, Frames, Decode, Bin/Hex/Manchester). Be concise "
"and practical; use short markdown sections/bullets. This is receive-only analysis.\n\n"
"TAKING ACTIONS: you can DRIVE the analyzer. When a concrete next step would help, END "
"your reply with a fenced ```json block: {\"actions\":[ ... ]} — the user gets one-click "
"buttons to run them (nothing runs without their click). Use ONLY these actions and only "
"with values grounded in the data shown:\n"
" {\"action\":\"tune\",\"f_mhz\":<centre>,\"bw_khz\":<width>,\"mode\":\"ook|fsk\"} — mark + zoom a signal and set demod BW\n"
" {\"action\":\"demod\",\"mode\":\"ook|fsk\",\"bw_khz\":<width>} — demodulate to bits\n"
" {\"action\":\"classify\"} — auto modulation classification\n"
" {\"action\":\"frames\",\"line\":\"raw|manchester|nrzi\"} — preamble/frame/CRC analysis\n"
" {\"action\":\"decode433\"} — run rtl_433 to name known ISM devices\n"
" {\"action\":\"zoom\",\"t0\":<s>,\"t1\":<s>,\"f0_mhz\":<lo>,\"f1_mhz\":<hi>}\n"
" {\"action\":\"reset\"} — reset zoom\n"
"Propose at most 4 actions, in the order to try them. Omit the block entirely if there's "
"nothing concrete to do. Keep the readable answer ABOVE the block; put no prose after it."
)
user = (
"Here is the current analyzer state for the selected capture (JSON):\n\n"
+ ctx_json
+ "\n\nUser question:\n" + q[:2000]
+ "\n\nAnswer as their RF analyst: interpret what's measured, be specific about the "
"numbers present, and end with a concrete next step using the analyzer's controls."
)
return self._ask(system, user)
# ===================================================================
# ATTACK VECTOR IDENTIFICATION
# ===================================================================
def identify_network_weaknesses(self, network_data: Dict, findings: List[Dict]):
if not self.is_enabled():
return None
key = self._cache_key("weakness", {
"targets": network_data.get("target_count"),
"findings": len(findings),
})
cached = self._cache_get(key)
if cached:
return cached
sample = json.dumps(findings[:5], indent=2)
system = (
"You are Ragnar, a penetration strategist. "
"Structure attack vector analysis clearly with numbered attack paths. "
"Use markdown formatting for readability."
)
user = f"""
Network Profile:
- Devices: {network_data.get('target_count')}
- Open Ports: {network_data.get('port_count')}
Key Findings:
{sample}
Provide structured attack vector analysis:
First, give a brief, witty Viking-style summary (max 50 words) describing the network's exploitability and main attack surface.
Then provide detailed attack paths:
**Primary Attack Paths:**
1. **[Attack Name]**
- Target: [specific host/service]
- Method: [exploitation technique]
- Risk Level: [Critical/High/Medium]
- Ease of Exploitation: [Easy/Moderate/Difficult]
2. **[Attack Name]**
- Target: [specific host/service]
- Method: [exploitation technique]
- Risk Level: [Critical/High/Medium]
- Ease of Exploitation: [Easy/Moderate/Difficult]
3. **[Attack Name]** (if applicable)
- Target: [specific host/service]
- Method: [exploitation technique]
- Risk Level: [Critical/High/Medium]
- Ease of Exploitation: [Easy/Moderate/Difficult]
**Defense Recommendations:**
- Immediate hardening steps
- Network segmentation suggestions
Limit to 2-3 most viable attack paths. Be specific and tactical.
"""
resp = self._ask(system, user)
if resp:
self._cache_set(key, resp)
return resp
# ===================================================================
# WI-FI CONNECTION ANALYSIS (professional tone, no persona)
# ===================================================================
def analyze_wifi_connection(self, context: Dict):
"""Assess the user's current Wi-Fi connection and RF environment from a
spectrum scan + association info, and return prioritized, professional
recommendations. `context` is built by the /api/ai/wifi-analyze route."""
if not self.is_enabled():
return None
connected = (context or {}).get("connected")
bt = (context or {}).get("bt")
zb = (context or {}).get("zigbee")
key = self._cache_key("wifi_conn", {
"bssid": (connected or {}).get("bssid"),
"signal": (connected or {}).get("signal_dbm"),
"cochannel": (context or {}).get("co_channel_count"),
"aps": (context or {}).get("ap_total"),
# Include the non-Wi-Fi 2.4 GHz overlays so enabling/refreshing them
# busts the cache instead of serving a Wi-Fi-only verdict.
"bt": (bt or {}).get("device_count") if bt else None,
"zb": (zb or {}).get("device_count") if zb else None,
})
cached = self._cache_get(key)
if cached:
return cached
# Which non-Wi-Fi 2.4 GHz sources are present shapes what we ask for.
overlays = []
if bt:
overlays.append("Bluetooth/BLE")
if zb:
overlays.append("Zigbee / 802.15.4")
overlay_line = (
(" The data also includes non-Wi-Fi 2.4 GHz emitters discovered "
"alongside the Wi-Fi scan (" + " and ".join(overlays) + "), under "
"the 'bt' and/or 'zigbee' keys, with an estimated per-Wi-Fi-channel "
"pressure for channels 1/6/11/13. Treat these as coexistence load on "
"the 2.4 GHz band: factor them into 2.4 GHz channel advice and, when "
"they are significant, recommend moving affected clients to 5/6 GHz. "
"The pressure figures are heuristic activity estimates, not measured "
"energy — say so and do not overstate them.") if overlays else ""
)
data_json = json.dumps(context, indent=2, default=str)[:6000]
system = (
"You are a professional wireless network engineer. Analyze the user's "
"current Wi-Fi connection and the surrounding RF environment from the "
"scan data provided, and give clear, actionable recommendations to fix "
"or improve it. Use a neutral, professional tone — no personas, no "
"slang, no jokes. Base every statement strictly on the data provided; "
"do not invent SSIDs, channels or values that are not present. If the "
"user is not associated to a network, say so and analyze the "
"environment instead. Use short markdown sections and bullet points."
+ overlay_line
)
user = f"""Analyze this Wi-Fi connection and RF environment.
Data (JSON):
{data_json}
Provide:
**Connection summary** — the network the user is on: band, channel, channel
width, security, Wi-Fi generation, signal strength and negotiated rate, in one
short paragraph.
**Issues found** — concrete problems supported by the data, e.g. co-channel or
adjacent-channel congestion, 2.4 GHz use where 5 GHz is available, weak signal,
legacy/weak security (Open/WEP/WPA/TKIP), a narrow channel width, a crowded
channel, or — when the bt/zigbee overlays are present — non-Wi-Fi 2.4 GHz
coexistence pressure from Bluetooth/BLE or Zigbee on channels 1/6/11. Only list
issues the data supports.
**Recommendations** — prioritized, specific actions (e.g. "move to 5 GHz",
"change to channel 44", "widen to 80 MHz", "upgrade to WPA2/WPA3-CCMP",
"relocate the AP / add an AP"). Say why each helps.
If the environment is healthy, say so plainly. Keep it tight and practical."""
resp = self._ask(system, user)
if resp:
self._cache_set(key, resp)
return resp
# ===================================================================
# SECURITY POSTURE (Watchtower + Wi-Fi Defense passive monitoring)
# ===================================================================
def analyze_security_posture(self, posture: Dict):
"""Summarize the passive-monitoring posture from Watchtower's aggregated
alert feed (which includes the Wi-Fi Defense family: wifiwatch,
legacywatch, wpswatch, ndpwatch, …). Professional tone."""
if not self.is_enabled():
return None
key = self._cache_key("posture", {
"total": (posture or {}).get("total_alerts"),
"worst": (posture or {}).get("worst"),
"by_sev": (posture or {}).get("by_severity"),
})
cached = self._cache_get(key)
if cached:
return cached
data_json = json.dumps(posture, indent=2, default=str)[:5000]
system = (
"You are a professional security operations analyst. Summarize the "
"current passive-monitoring posture from the alert data. Watchtower "
"aggregates Ragnar's passive watchers, including the Wi-Fi Defense "
"family (wifiwatch, legacywatch, wpswatch) and wired monitors "
"(ndpwatch, arp_guard, …). Use a neutral, professional tone. Base "
"every statement on the data; do not invent alerts. Be concise."
)
user = f"""Summarize this passive security-monitoring posture.
Data (JSON):
{data_json}
Provide:
**Posture** — one or two sentences on the overall state (quiet, elevated, or
active incidents), grounded in the alert counts.
**Top concerns** — the most important active findings (by severity and source),
naming the finding codes/summaries present.
**Recommended actions** — concrete next steps for the highest-severity items.
If there are no alerts, state that the monitored surface is currently clean and
note which watchers are reporting. Keep it short."""
resp = self._ask(system, user)
if resp:
self._cache_set(key, resp)
return resp
# ===================================================================
# WI-FI DEFENSE (WIDS + airtime + client-isolation, one read)
# ===================================================================
def analyze_wifi_defense(self, context: Dict):
"""One professional read across the three WiFi Defense modules for a
single capture window: the 802.11 WIDS scan (deauth/beacon floods,
rogue/evil-twin APs, KARMA, airspace posture), the airtime / link-quality
analysis (retry rates, airtime hogs, slow/legacy clients, weak security),
and the client-isolation observer (whether stations can reach each other
on the same BSS/mesh). `context` is assembled by /api/ai/wifidef-analyze
from whatever the panel currently holds. Neutral SOC-analyst tone."""
if not self.is_enabled():
return None
wids = (context or {}).get('wids') or {}
airtime = (context or {}).get('airtime') or {}
isolation = (context or {}).get('isolation') or {}
key = self._cache_key("wifidef", {
"threat": wids.get('threat'),
"dets": len(wids.get('detections') or []),
"at": len(airtime.get('findings') or []),
"iso": [(b.get('bssid'), b.get('verdict')) for b in (isolation.get('bss') or [])[:12]],
"frames": wids.get('frames'),
})
cached = self._cache_get(key)
if cached:
return cached
present = []
if wids:
present.append("WIDS")
if airtime:
present.append("airtime/link-quality")
if isolation:
present.append("client-isolation")
data_json = json.dumps(context, indent=2, default=str)[:6500]
system = (
"You are a professional wireless security operations analyst reviewing "
"a single passive 802.11 monitor-mode capture through three lenses: an "
You can’t perform that action at this time.
