ruso_script/script/ast.rs
1//! The abstract syntax tree the parser produces and the compiler consumes.
2//!
3//! An RSL script is a flat list of [`Stmt`]s executed top to bottom; the only
4//! nesting comes from `if` and `for`, which carry their own bodies. Everything
5//! that also has to survive into bytecode — matchers, bodies, severities — is
6//! re-exported from [`ruso_runtime::contract`] rather than redefined here, so
7//! the parser and the VM cannot drift apart.
8
9pub use ruso_runtime::contract::{
10 BodyValue, CmpOp, CmpValue, EvidenceKind, ExtractSource, FieldKind, HttpMethod, InlinePart,
11 InlinePartBody, MatchPredicate, ObjectBody, QualifiedField, QualifiedMatch, Severity,
12};
13
14/// A parsed script: every statement in source order.
15#[derive(Debug, Clone, PartialEq)]
16pub struct Program {
17 /// Top-level statements, including metadata and probe definitions.
18 pub statements: Vec<Stmt>,
19}
20
21/// Generic socket probe fields shared by `dns`, `tcp`, and `udp`.
22#[derive(Debug, Clone, PartialEq)]
23pub struct SocketProbe {
24 /// The probe's name, used to reference its response (`p.response`).
25 pub name: String,
26 /// Target host. May be a `{{ var }}` placeholder such as `{{scan_host}}`,
27 /// resolved from the scan target at send time.
28 pub host: String,
29 /// Target port. `None` on a `dns` probe means resolver mode (ask the system
30 /// resolver) rather than a wire-protocol query to a specific port.
31 pub port: Option<u16>,
32 /// UTF-8 text or raw bytes (from `payload "..."` or `payload "aabbcc"` hex).
33 pub payload: Option<Vec<u8>>,
34 /// Wrap the connection in TLS.
35 pub tls: bool,
36 /// Keep the connection open after this probe so later sends to the same
37 /// probe reuse it, instead of reconnecting.
38 pub session: bool,
39 /// Maximum number of response bytes to read.
40 pub read_max: u32,
41 /// How long to wait for more data, in milliseconds, before treating the
42 /// response as complete.
43 pub read_idle_ms: u32,
44}
45
46/// The right-hand side of a `set`.
47#[derive(Debug, Clone, PartialEq)]
48pub enum Value {
49 /// A single string, possibly containing `{{ var }}` placeholders.
50 String(String),
51 /// A list literal.
52 List(Vec<String>),
53}
54
55/// What a `for … in …` loop iterates over.
56#[derive(Debug, Clone, PartialEq)]
57pub enum ListSource {
58 /// An inline list literal: `for p in ["/a", "/b"]`.
59 Literal(Vec<String>),
60 /// A previously `set` list variable: `for p in paths`.
61 Variable(String),
62}
63
64/// One statement of a script.
65///
66/// The first group of variants is metadata — declarations that describe the
67/// check rather than doing anything — and is recognized by
68/// [`Stmt::is_metadata`]. The rest define probes, control flow, matching, and
69/// the finding the check emits.
70#[derive(Debug, Clone, PartialEq)]
71pub enum Stmt {
72 /// `name "…"` — the finding's title.
73 Name(String),
74 /// `description "…"` — what the check looks for.
75 Description(String),
76 /// `impact "…"` — what an affected target is exposed to.
77 Impact(String),
78 /// `severity …` — the finding's severity; defaults to `info` when absent.
79 Severity(Severity),
80 /// `author "…"` — who wrote the check.
81 Author(String),
82 /// `cve "…"` — a CVE id the check detects. May be repeated.
83 Cve(String),
84 /// `cwe "…"` — a CWE id for the weakness class. May be repeated.
85 Cwe(String),
86 /// `reference "…"` — a supporting URL. May be repeated.
87 Reference(String),
88 /// `cvss "…"` — a CVSS vector string. May be repeated.
89 Cvss(String),
90 /// `cvss_score "…"` — a numeric CVSS score. May be repeated.
91 CvssScore(String),
92 /// `mitigation "…"` — how to fix the issue.
93 Mitigation(String),
94 /// `tag "…"` — a search tag in the registry. May be repeated.
95 Tag(String),
96 /// `version "…"` — the check's own version.
97 Version(String),
98 /// `family "…"` — the family the check belongs to, as used by
99 /// `ruso scan --family`.
100 Family(String),
101
102 /// `set <name> = <value>` — bind a variable.
103 Set {
104 /// Variable name.
105 name: String,
106 /// The value bound to it.
107 value: Value,
108 },
109
110 /// `for <item> in <list> { … }` — iterate, rebinding `item` each pass.
111 ForIn {
112 /// The loop variable.
113 item: String,
114 /// What is iterated.
115 list: ListSource,
116 /// Statements run per iteration.
117 body: Vec<Stmt>,
118 },
119
120 /// `http <name> { … }` — define an HTTP probe.
121 Http {
122 /// The probe's name, used to reference its response (`p.status`).
123 name: String,
124 /// The probe's settings, in source order.
125 items: Vec<HttpItem>,
126 },
127 /// `dns <name> { … }` — define a DNS probe.
128 Dns(SocketProbe),
129 /// `tcp <name> { … }` — define a TCP probe.
130 Tcp(SocketProbe),
131 /// `udp <name> { … }` — define a UDP probe.
132 Udp(SocketProbe),
133 /// `send <probe>` — fire a defined probe, optionally overriding its body.
134 Send {
135 /// Name of the probe to send.
136 probe: String,
137 /// Payload that replaces the probe's own body for this send.
138 payload: Option<Vec<u8>>,
139 },
140 /// `break` — leave the enclosing `for`.
141 Break,
142
143 /// `match …` — evaluate one condition; a false result clears the run's
144 /// match state so no finding is emitted, but execution continues.
145 Match(QualifiedMatch),
146 /// `match_all [ … ]` — true only if every condition holds.
147 MatchAll(Vec<QualifiedMatch>),
148 /// `match_any [ … ]` — true if any condition holds.
149 MatchAny(Vec<QualifiedMatch>),
150 /// `assert …` — like `match`, but a false result aborts the script.
151 Assert(QualifiedMatch),
152
153 /// `extract <name> from …` — bind part of a response to a variable.
154 Extract {
155 /// Variable to bind.
156 name: String,
157 /// Where the value comes from: a body regex or a named header.
158 source: ExtractSource,
159 },
160
161 /// `if <condition> { … }` — run the body only when the condition holds.
162 If {
163 /// The condition tested.
164 condition: QualifiedMatch,
165 /// Statements run when it holds.
166 body: Vec<Stmt>,
167 },
168
169 /// `save <request> as <alias>` — make a response reachable under a second
170 /// name, so a later matcher can refer to an earlier probe's result.
171 Save {
172 /// The probe whose response is saved.
173 request: String,
174 /// The additional name it becomes reachable under.
175 alias: String,
176 },
177
178 /// `evidence <probe>.body | .response | .header "…"` — attach proof to the
179 /// finding, optionally narrowed by a regex.
180 Evidence(EvidenceKind),
181
182 /// `stop` — end the run without emitting a finding.
183 Stop,
184 /// `fail` — end the run and mark it failed.
185 Fail,
186 /// `continue` — skip to the next iteration of the enclosing `for`.
187 Continue,
188 /// `exit` — end the run immediately.
189 Exit,
190
191 /// `retry <request> <count>` — re-send a probe while it keeps failing.
192 Retry {
193 /// The probe to re-send.
194 request: String,
195 /// Maximum number of attempts.
196 count: u32,
197 },
198 /// `retry_delay "<duration>"` — wait between retry attempts.
199 RetryDelay(String),
200 /// `sleep "<duration>"` — pause the run.
201 Sleep(String),
202}
203
204impl Stmt {
205 /// Whether this statement only describes the check (its name, severity,
206 /// references, …) rather than doing anything at run time.
207 ///
208 /// The compiler collects these into the program's metadata instead of
209 /// emitting instructions for them.
210 pub fn is_metadata(&self) -> bool {
211 matches!(
212 self,
213 Self::Name(_)
214 | Self::Description(_)
215 | Self::Impact(_)
216 | Self::Severity(_)
217 | Self::Author(_)
218 | Self::Cve(_)
219 | Self::Cwe(_)
220 | Self::Reference(_)
221 | Self::Cvss(_)
222 | Self::CvssScore(_)
223 | Self::Mitigation(_)
224 | Self::Tag(_)
225 | Self::Version(_)
226 | Self::Family(_)
227 )
228 }
229
230 /// Whether this statement defines a probe (`http`, `dns`, `tcp`, `udp`).
231 ///
232 /// Probe definitions go into the program's probe table; they do not run
233 /// until a `send` names them.
234 pub fn is_probe_definition(&self) -> bool {
235 matches!(
236 self,
237 Self::Http { .. } | Self::Dns(_) | Self::Tcp(_) | Self::Udp(_)
238 )
239 }
240}
241
242/// One setting inside an `http` block.
243///
244/// Items appear in source order and are folded into the runtime's
245/// `HttpRequestSpec` by the compiler. Anything not stated falls back to the
246/// executor's configuration.
247#[derive(Debug, Clone, PartialEq)]
248pub enum HttpItem {
249 /// `method GET` — the request method. Defaults to `GET`.
250 Method(HttpMethod),
251 /// `path "/…"` — the request path, resolved against the scan target.
252 Path(String),
253 /// `timeout "5s"` — a per-probe timeout.
254 Timeout(String),
255 /// `follow_redirect true|false` — whether to follow redirects.
256 FollowRedirect(bool),
257 /// `verify_ssl true|false` — whether to verify the TLS certificate.
258 VerifySsl(bool),
259 /// `proxy "…"` — route this probe through a proxy.
260 Proxy(String),
261 /// `user_agent "…"` — override the `User-Agent`.
262 UserAgent(String),
263 /// `header "<name>" "<value>"` — add a request header.
264 Header {
265 /// Header name.
266 name: String,
267 /// Header value; may interpolate variables.
268 value: String,
269 },
270 /// `cookie "<name>" "<value>"` — add a request cookie.
271 Cookie {
272 /// Cookie name.
273 name: String,
274 /// Cookie value; may interpolate variables.
275 value: String,
276 },
277 /// `query "<name>" "<value>"` — add a query-string parameter.
278 Query {
279 /// Parameter name.
280 name: String,
281 /// Parameter value; may interpolate variables.
282 value: String,
283 },
284 /// `data { … }` — a form-urlencoded body.
285 Data(ObjectBody),
286 /// `json { … }` — a JSON body.
287 Json(ObjectBody),
288 /// `raw "…"` — a body sent verbatim.
289 Raw(String),
290 /// `body_bytes "aabbcc"` — a hex-encoded binary body.
291 BodyBytes(String),
292 /// `multipart { … }` — a `multipart/form-data` body.
293 Multipart(ObjectBody),
294}