1use crate::seqstring::global_string;
57use crate::stack::{Stack, pop, push};
58use crate::value::{MapKey, Value};
59
60use std::collections::HashMap;
61use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, ToSocketAddrs};
62use std::sync::LazyLock;
63use std::time::Duration;
64
65const DEFAULT_TIMEOUT_SECS: u64 = 30;
67
68const MAX_BODY_SIZE: usize = 10 * 1024 * 1024;
70
71static HTTP_AGENT: LazyLock<ureq::Agent> = LazyLock::new(|| {
74 ureq::AgentBuilder::new()
75 .timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
76 .build()
77});
78
79fn is_dangerous_ipv4(ip: Ipv4Addr) -> bool {
81 if ip.is_loopback() {
83 return true;
84 }
85 if ip.octets()[0] == 10 {
87 return true;
88 }
89 if ip.octets()[0] == 172 && (ip.octets()[1] >= 16 && ip.octets()[1] <= 31) {
91 return true;
92 }
93 if ip.octets()[0] == 192 && ip.octets()[1] == 168 {
95 return true;
96 }
97 if ip.octets()[0] == 169 && ip.octets()[1] == 254 {
99 return true;
100 }
101 if ip.is_broadcast() {
103 return true;
104 }
105 false
106}
107
108fn is_dangerous_ipv6(ip: Ipv6Addr) -> bool {
110 if ip.is_loopback() {
112 return true;
113 }
114 let segments = ip.segments();
116 if (segments[0] & 0xffc0) == 0xfe80 {
117 return true;
118 }
119 if (segments[0] & 0xfe00) == 0xfc00 {
121 return true;
122 }
123 if let Some(ipv4) = ip.to_ipv4_mapped() {
125 return is_dangerous_ipv4(ipv4);
126 }
127 false
128}
129
130fn is_dangerous_ip(ip: IpAddr) -> bool {
132 match ip {
133 IpAddr::V4(v4) => is_dangerous_ipv4(v4),
134 IpAddr::V6(v6) => is_dangerous_ipv6(v6),
135 }
136}
137
138fn validate_url_for_ssrf(url: &str) -> Result<(), String> {
141 let parsed = match url::Url::parse(url) {
143 Ok(u) => u,
144 Err(e) => return Err(format!("Invalid URL: {}", e)),
145 };
146
147 match parsed.scheme() {
149 "http" | "https" => {}
150 scheme => {
151 return Err(format!(
152 "Blocked scheme '{}': only http/https allowed",
153 scheme
154 ));
155 }
156 }
157
158 let host = match parsed.host_str() {
160 Some(h) => h,
161 None => return Err("URL has no host".to_string()),
162 };
163
164 let host_lower = host.to_lowercase();
166 if host_lower == "localhost"
167 || host_lower == "localhost.localdomain"
168 || host_lower.ends_with(".localhost")
169 {
170 return Err("Blocked: localhost access not allowed".to_string());
171 }
172
173 let port = parsed
175 .port()
176 .unwrap_or(if parsed.scheme() == "https" { 443 } else { 80 });
177
178 let addr_str = format!("{}:{}", host, port);
180 match addr_str.to_socket_addrs() {
181 Ok(addrs) => {
182 for addr in addrs {
183 if is_dangerous_ip(addr.ip()) {
184 return Err(format!(
185 "Blocked: {} resolves to private/internal IP {}",
186 host,
187 addr.ip()
188 ));
189 }
190 }
191 }
192 Err(_) => {
193 }
196 }
197
198 Ok(())
199}
200
201fn build_response_map(status: i64, body: String, ok: bool, error: Option<String>) -> Value {
203 let mut map: HashMap<MapKey, Value> = HashMap::new();
204
205 map.insert(
206 MapKey::String(global_string("status".to_string())),
207 Value::Int(status),
208 );
209 map.insert(
210 MapKey::String(global_string("body".to_string())),
211 Value::String(global_string(body)),
212 );
213 map.insert(
214 MapKey::String(global_string("ok".to_string())),
215 Value::Bool(ok),
216 );
217
218 if let Some(err) = error {
219 map.insert(
220 MapKey::String(global_string("error".to_string())),
221 Value::String(global_string(err)),
222 );
223 }
224
225 Value::Map(Box::new(map))
226}
227
228fn error_response(error: String) -> Value {
230 build_response_map(0, String::new(), false, Some(error))
231}
232
233#[unsafe(no_mangle)]
242pub unsafe extern "C" fn patch_seq_http_get(stack: Stack) -> Stack {
243 assert!(!stack.is_null(), "http.get: stack is empty");
244
245 let (stack, url_value) = unsafe { pop(stack) };
246
247 match url_value {
248 Value::String(url) => {
249 let response = perform_get(url.as_str());
250 unsafe { push(stack, response) }
251 }
252 _ => panic!(
253 "http.get: expected String (URL) on stack, got {:?}",
254 url_value
255 ),
256 }
257}
258
259#[unsafe(no_mangle)]
268pub unsafe extern "C" fn patch_seq_http_post(stack: Stack) -> Stack {
269 assert!(!stack.is_null(), "http.post: stack is empty");
270
271 let (stack, content_type_value) = unsafe { pop(stack) };
272 let (stack, body_value) = unsafe { pop(stack) };
273 let (stack, url_value) = unsafe { pop(stack) };
274
275 match (url_value, body_value, content_type_value) {
276 (Value::String(url), Value::String(body), Value::String(content_type)) => {
277 let response = perform_post(url.as_str(), body.as_str(), content_type.as_str());
278 unsafe { push(stack, response) }
279 }
280 (url, body, ct) => panic!(
281 "http.post: expected (String, String, String) on stack, got ({:?}, {:?}, {:?})",
282 url, body, ct
283 ),
284 }
285}
286
287#[unsafe(no_mangle)]
296pub unsafe extern "C" fn patch_seq_http_put(stack: Stack) -> Stack {
297 assert!(!stack.is_null(), "http.put: stack is empty");
298
299 let (stack, content_type_value) = unsafe { pop(stack) };
300 let (stack, body_value) = unsafe { pop(stack) };
301 let (stack, url_value) = unsafe { pop(stack) };
302
303 match (url_value, body_value, content_type_value) {
304 (Value::String(url), Value::String(body), Value::String(content_type)) => {
305 let response = perform_put(url.as_str(), body.as_str(), content_type.as_str());
306 unsafe { push(stack, response) }
307 }
308 (url, body, ct) => panic!(
309 "http.put: expected (String, String, String) on stack, got ({:?}, {:?}, {:?})",
310 url, body, ct
311 ),
312 }
313}
314
315#[unsafe(no_mangle)]
324pub unsafe extern "C" fn patch_seq_http_delete(stack: Stack) -> Stack {
325 assert!(!stack.is_null(), "http.delete: stack is empty");
326
327 let (stack, url_value) = unsafe { pop(stack) };
328
329 match url_value {
330 Value::String(url) => {
331 let response = perform_delete(url.as_str());
332 unsafe { push(stack, response) }
333 }
334 _ => panic!(
335 "http.delete: expected String (URL) on stack, got {:?}",
336 url_value
337 ),
338 }
339}
340
341fn handle_response(result: Result<ureq::Response, ureq::Error>) -> Value {
343 match result {
344 Ok(response) => {
345 let status = response.status() as i64;
346 let ok = (200..300).contains(&response.status());
347
348 match response.into_string() {
349 Ok(body) => {
350 if body.len() > MAX_BODY_SIZE {
351 error_response(format!(
352 "Response body too large ({} bytes, max {})",
353 body.len(),
354 MAX_BODY_SIZE
355 ))
356 } else {
357 build_response_map(status, body, ok, None)
358 }
359 }
360 Err(e) => error_response(format!("Failed to read response body: {}", e)),
361 }
362 }
363 Err(ureq::Error::Status(code, response)) => {
364 let body = response.into_string().unwrap_or_default();
366 build_response_map(
367 code as i64,
368 body,
369 false,
370 Some(format!("HTTP error: {}", code)),
371 )
372 }
373 Err(ureq::Error::Transport(e)) => {
374 error_response(format!("Connection error: {}", e))
376 }
377 }
378}
379
380fn perform_get(url: &str) -> Value {
382 if let Err(msg) = validate_url_for_ssrf(url) {
384 return error_response(msg);
385 }
386 handle_response(HTTP_AGENT.get(url).call())
387}
388
389fn perform_post(url: &str, body: &str, content_type: &str) -> Value {
391 if let Err(msg) = validate_url_for_ssrf(url) {
393 return error_response(msg);
394 }
395 handle_response(
396 HTTP_AGENT
397 .post(url)
398 .set("Content-Type", content_type)
399 .send_string(body),
400 )
401}
402
403fn perform_put(url: &str, body: &str, content_type: &str) -> Value {
405 if let Err(msg) = validate_url_for_ssrf(url) {
407 return error_response(msg);
408 }
409 handle_response(
410 HTTP_AGENT
411 .put(url)
412 .set("Content-Type", content_type)
413 .send_string(body),
414 )
415}
416
417fn perform_delete(url: &str) -> Value {
419 if let Err(msg) = validate_url_for_ssrf(url) {
421 return error_response(msg);
422 }
423 handle_response(HTTP_AGENT.delete(url).call())
424}
425
426#[cfg(test)]
427mod tests;