nullcone 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nullcone/ei_client.py ADDED
@@ -0,0 +1,183 @@
1
+ """
2
+ Entity Identity (EI) client for Nullcone.
3
+
4
+ Thin wrapper around the EI REST API that handles:
5
+ - Proof verification (ZK layer)
6
+ - Nullifier recording (replay prevention)
7
+ - Entity type meta lookup
8
+
9
+ EI API reference: /home/alex/EI/EI/api/API_DESIGN.md
10
+ Live EI server: http://149.28.33.118:3000
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ from dataclasses import dataclass
16
+ from typing import Any, Optional
17
+
18
+ import httpx
19
+
20
+ log = logging.getLogger(__name__)
21
+
22
+ # Entity types that Nullcone accepts. Sensors / autonomous defenders only —
23
+ # no synthetic media generators, drones, etc.
24
+ ALLOWED_ENTITY_TYPES: frozenset[str] = frozenset({
25
+ "AI.CA", # Conversational Agent
26
+ "AI.PO", # Program Orchestrator
27
+ "AI.AA", # Autonomous Agent
28
+ "AI.DB", # Data Broker
29
+ "AI.OS", # Operating System
30
+ "HY.CP", # Copilot (human-in-the-loop)
31
+ "HY.HS", # Hive Swarm
32
+ })
33
+
34
+ # Context ID used for all Nullcone registrations — scopes the nullifier so the
35
+ # same entity can re-prove across sessions, but not within the same context.
36
+ NULLCONE_CONTEXT = "nullcone-registration-v1"
37
+
38
+
39
+ @dataclass
40
+ class EIVerification:
41
+ """Result of a successful EI proof verification."""
42
+ valid: bool
43
+ entity_type: str # e.g. "AI.CA"
44
+ entity_type_name: str # e.g. "Conversational Agent"
45
+ phonetic_name: str # e.g. "Kah"
46
+ entity_commitment: str # 0x-prefixed hex — pseudonymous stable ID
47
+ nullifier: str # 0x-prefixed hex — used to prevent replay
48
+ registry_root_valid: bool
49
+ nullifier_status: str # "new" | "used"
50
+
51
+
52
+ class EIError(Exception):
53
+ """Raised when EI verification fails."""
54
+ pass
55
+
56
+
57
+ class EIClient:
58
+ """
59
+ HTTP client for the Entity Identity API.
60
+
61
+ Usage::
62
+
63
+ client = EIClient()
64
+ # proof + signals come from `npx eid prove -t AI.CA -c nullcone-registration-v1`
65
+ # or from calling EI /api/v1/prove with an attester API key.
66
+ verification = client.verify_and_record(proof, public_signals)
67
+ print(verification.entity_type) # "AI.CA"
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ ei_url: str = "http://149.28.33.118:3000",
73
+ timeout: float = 15.0,
74
+ ) -> None:
75
+ self._base = ei_url.rstrip("/")
76
+ self._http = httpx.Client(timeout=timeout)
77
+
78
+ def close(self) -> None:
79
+ self._http.close()
80
+
81
+ def __enter__(self) -> "EIClient":
82
+ return self
83
+
84
+ def __exit__(self, *_: Any) -> None:
85
+ self.close()
86
+
87
+ # ------------------------------------------------------------------
88
+ # Public API
89
+ # ------------------------------------------------------------------
90
+
91
+ def entity_types(self) -> list[dict]:
92
+ """Return all 16 EI entity types from the registry."""
93
+ r = self._http.get(f"{self._base}/api/v1/types")
94
+ r.raise_for_status()
95
+ return r.json()
96
+
97
+ def verify(
98
+ self,
99
+ proof: dict,
100
+ public_signals: list[str],
101
+ ) -> EIVerification:
102
+ """
103
+ Verify a Groth16 ZK proof against the EI registry.
104
+
105
+ Args:
106
+ proof: dict with keys pi_a, pi_b, pi_c (snarkjs format)
107
+ public_signals: list of 5 hex strings
108
+ [nullifier, commitment, type, root, contextId]
109
+
110
+ Returns:
111
+ EIVerification on success.
112
+
113
+ Raises:
114
+ EIError if the proof is invalid or the EI server is unreachable.
115
+ """
116
+ payload = {"proof": proof, "publicSignals": public_signals}
117
+ try:
118
+ r = self._http.post(f"{self._base}/api/v1/verify", json=payload)
119
+ r.raise_for_status()
120
+ except httpx.HTTPError as exc:
121
+ raise EIError(f"EI server error during verify: {exc}") from exc
122
+
123
+ data = r.json()
124
+ if not data.get("valid"):
125
+ raise EIError(f"EI proof invalid: {data}")
126
+
127
+ return EIVerification(
128
+ valid=True,
129
+ entity_type=data["entityType"],
130
+ entity_type_name=data.get("entityTypeName", ""),
131
+ phonetic_name=data.get("phoneticName", ""),
132
+ entity_commitment=data["entityCommitment"],
133
+ nullifier=data["nullifier"],
134
+ registry_root_valid=data.get("registryRootValid", False),
135
+ nullifier_status=data.get("nullifierStatus", "unknown"),
136
+ )
137
+
138
+ def record_nullifier(self, nullifier: str, context_id: str = NULLCONE_CONTEXT) -> None:
139
+ """
140
+ Record a nullifier as used so it cannot be replayed.
141
+
142
+ This is a best-effort call — if the EI server is temporarily down,
143
+ Nullcone logs a warning but does not block registration. The nullifier
144
+ is already validated as structurally valid by the preceding verify() call.
145
+ """
146
+ payload = {"nullifier": nullifier, "contextId": context_id}
147
+ try:
148
+ r = self._http.post(f"{self._base}/api/v1/verify/record", json=payload)
149
+ r.raise_for_status()
150
+ except httpx.HTTPError as exc:
151
+ log.warning("EI nullifier record failed (non-fatal): %s", exc)
152
+
153
+ def verify_and_record(
154
+ self,
155
+ proof: dict,
156
+ public_signals: list[str],
157
+ allowed_types: Optional[frozenset[str]] = None,
158
+ ) -> EIVerification:
159
+ """
160
+ Verify a proof and immediately record the nullifier to prevent replay.
161
+
162
+ Also enforces that the entity type is in `allowed_types` (defaults to
163
+ ALLOWED_ENTITY_TYPES — the Nullcone-permitted set).
164
+
165
+ Raises:
166
+ EIError if proof is invalid, nullifier already used, or type not allowed.
167
+ """
168
+ v = self.verify(proof, public_signals)
169
+
170
+ allowed = allowed_types if allowed_types is not None else ALLOWED_ENTITY_TYPES
171
+ if v.entity_type not in allowed:
172
+ raise EIError(
173
+ f"Entity type '{v.entity_type}' is not permitted for Nullcone. "
174
+ f"Allowed: {sorted(allowed)}"
175
+ )
176
+
177
+ if v.nullifier_status == "used":
178
+ raise EIError(
179
+ f"EI nullifier already used. Generate a fresh proof with a new context."
180
+ )
181
+
182
+ self.record_nullifier(v.nullifier)
183
+ return v
nullcone/models.py ADDED
@@ -0,0 +1,206 @@
1
+ """
2
+ Malware Intelligence Data Models
3
+
4
+ IOC types, threat signatures, malware families, and agent registration
5
+ records that mirror the SpacetimeDB table schemas.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ from dataclasses import dataclass, field
11
+ from enum import Enum
12
+ from typing import Any, Optional
13
+
14
+
15
+ class IOCType(str, Enum):
16
+ MD5 = "hash_md5"
17
+ SHA1 = "hash_sha1"
18
+ SHA256 = "hash_sha256"
19
+ IP = "ip"
20
+ IP_PORT = "ip_port"
21
+ DOMAIN = "domain"
22
+ URL = "url"
23
+ YARA = "yara"
24
+ EMAIL = "email"
25
+ MUTEX = "mutex"
26
+ REGISTRY = "registry"
27
+ FILEPATH = "filepath"
28
+ ASN = "asn"
29
+ JA3 = "ja3" # TLS fingerprint
30
+ IMPHASH = "imphash" # PE import hash
31
+ CVE = "cve" # Common Vulnerabilities and Exposures identifier
32
+ PROMPT = "prompt" # Prompt injection / malicious LLM instruction pattern
33
+ SKILL = "skill" # Malicious agent skill / plugin identifier
34
+
35
+
36
+ class Severity(int, Enum):
37
+ INFO = 1
38
+ LOW = 3
39
+ MEDIUM = 5
40
+ HIGH = 7
41
+ CRITICAL = 9
42
+
43
+
44
+ class ActionTaken(str, Enum):
45
+ LOGGED = "logged"
46
+ ALERTED = "alerted"
47
+ BLOCKED = "blocked"
48
+ QUARANTINED = "quarantined"
49
+ ERADICATED = "eradicated"
50
+
51
+
52
+ @dataclass
53
+ class IOC:
54
+ """Indicator of Compromise — input to the agent."""
55
+ ioc_type: IOCType
56
+ value: str
57
+ severity: int = 5 # 0-10
58
+ confidence: int = 70 # 0-100
59
+ family_hint: Optional[str] = None
60
+ context: str = ""
61
+ tags: list[str] = field(default_factory=list)
62
+ source: str = "local"
63
+
64
+ def value_hash(self) -> str:
65
+ """Normalized SHA256 of (type, value) for deduplication."""
66
+ normalized = f"{self.ioc_type.value}:{self.value.strip().lower()}"
67
+ return hashlib.sha256(normalized.encode()).hexdigest()
68
+
69
+ def to_dict(self) -> dict[str, Any]:
70
+ return {
71
+ "ioc_type": self.ioc_type.value,
72
+ "value": self.value,
73
+ "severity": self.severity,
74
+ "confidence": self.confidence,
75
+ "family": self.family_hint or "",
76
+ "tags": ",".join(self.tags),
77
+ "context": self.context,
78
+ "source": self.source,
79
+ }
80
+
81
+
82
+ @dataclass
83
+ class ThreatSignature:
84
+ """A confirmed IOC record from SpacetimeDB."""
85
+ id: int
86
+ ioc_type: str
87
+ value: str
88
+ value_hash: str
89
+ meta_compressed: bytes
90
+ threat_symbol: bytes # SecuritySymbol THREAT_IOC (0xF35B) or THREAT_PATTERN (0xF35C)
91
+ family_name: str
92
+ severity: int
93
+ confidence: int
94
+ source_agent_id: str
95
+ first_seen: str # ISO timestamp
96
+ last_seen: str
97
+ detection_count: int
98
+ false_positive_votes: int
99
+ tags: str
100
+
101
+ @property
102
+ def is_likely_fp(self) -> bool:
103
+ """Heuristic: >20% of agents voted false positive."""
104
+ return self.detection_count > 0 and (
105
+ self.false_positive_votes / self.detection_count
106
+ ) > 0.2
107
+
108
+ @property
109
+ def tag_list(self) -> list[str]:
110
+ return [t for t in self.tags.split(",") if t]
111
+
112
+ @classmethod
113
+ def from_dict(cls, d: dict[str, Any]) -> "ThreatSignature":
114
+ def _to_bytes(v: Any) -> bytes:
115
+ if isinstance(v, str):
116
+ return bytes.fromhex(v)
117
+ if isinstance(v, (list, bytes)):
118
+ return bytes(v)
119
+ return b""
120
+
121
+ return cls(
122
+ id=d.get("id", 0),
123
+ ioc_type=d.get("ioc_type", ""),
124
+ value=d.get("value", ""),
125
+ value_hash=d.get("value_hash", ""),
126
+ meta_compressed=_to_bytes(d.get("meta_compressed")),
127
+ threat_symbol=_to_bytes(d.get("threat_symbol")),
128
+ family_name=d.get("family_name", ""),
129
+ severity=d.get("severity", 0),
130
+ confidence=d.get("confidence", 0),
131
+ source_agent_id=d.get("source_agent_id", ""),
132
+ first_seen=d.get("first_seen", ""),
133
+ last_seen=d.get("last_seen", ""),
134
+ detection_count=d.get("detection_count", 0),
135
+ false_positive_votes=d.get("false_positive_votes", 0),
136
+ tags=d.get("tags", ""),
137
+ )
138
+
139
+
140
+ @dataclass
141
+ class MalwareFamily:
142
+ """A known malware family record."""
143
+ id: int
144
+ name: str
145
+ aliases: str
146
+ threat_level: int
147
+ description: str
148
+ first_seen: str
149
+ ioc_count: int
150
+ category: str # ransomware, trojan, worm, rat, stealer, dropper, ...
151
+
152
+ @property
153
+ def alias_list(self) -> list[str]:
154
+ return [a for a in self.aliases.split(",") if a]
155
+
156
+ @classmethod
157
+ def from_dict(cls, d: dict[str, Any]) -> "MalwareFamily":
158
+ return cls(
159
+ id=d.get("id", 0),
160
+ name=d.get("name", ""),
161
+ aliases=d.get("aliases", ""),
162
+ threat_level=d.get("threat_level", 0),
163
+ description=d.get("description", ""),
164
+ first_seen=d.get("first_seen", ""),
165
+ ioc_count=d.get("ioc_count", 0),
166
+ category=d.get("category", ""),
167
+ )
168
+
169
+
170
+ @dataclass
171
+ class AgentInfo:
172
+ """Registered agent record."""
173
+ agent_id: str
174
+ hostname: str
175
+ os_type: str
176
+ capabilities: str # JSON blob
177
+ registered_at: str
178
+ last_seen: str
179
+ ioc_submissions: int
180
+ detections_reported: int
181
+
182
+
183
+ @dataclass
184
+ class SubmitResult:
185
+ """Result returned after submitting an IOC."""
186
+ status: str # "new" | "duplicate" | "updated" | "error"
187
+ signature_id: Optional[int]
188
+ detection_count: int
189
+ message: str = ""
190
+
191
+ @property
192
+ def is_new(self) -> bool:
193
+ return self.status == "new"
194
+
195
+ @property
196
+ def is_known(self) -> bool:
197
+ return self.status in ("duplicate", "updated")
198
+
199
+
200
+ @dataclass
201
+ class DetectionEvent:
202
+ """A detection event to report back to the shared DB."""
203
+ agent_id: str
204
+ signature_id: int
205
+ action: ActionTaken
206
+ context: dict[str, Any] = field(default_factory=dict)
nullcone/py.typed ADDED
File without changes