1use crate::error::{Failure, Result};
9use crate::sql::classify::{analyze, Analysis, Classification};
10use crate::sql::parse::ParseLimits;
11use crate::sql::strip::{strip, Stripped};
12use core::ops::ControlFlow;
13use sqlparser::ast::{Expr, ObjectName, Select, Statement, Visit, Visitor};
14
15const SERVER_FILE_READERS: &[&str] = &["load_file", "loadfile"];
20
21const SERVER_FILE_WRITERS: &[&str] = &["outfile", "dumpfile"];
23
24const CLIENT_FILE_READER: &str = "infile";
31
32#[derive(Debug, Clone)]
34pub struct Admission {
35 analysis: Analysis,
36 stripped: Stripped,
37}
38
39impl Admission {
40 #[must_use]
42 pub const fn analysis(&self) -> &Analysis {
43 &self.analysis
44 }
45
46 #[must_use]
48 pub const fn classification(&self) -> Classification {
49 self.analysis.classification()
50 }
51
52 #[must_use]
54 pub const fn stripped(&self) -> &Stripped {
55 &self.stripped
56 }
57}
58
59pub fn admit(sql: &str, limits: ParseLimits) -> Result<Admission> {
76 let stripped = strip(sql);
77 stripped.refuse_if_unterminated()?;
78 refuse_file_access_by_text(&stripped)?;
79
80 let analysis = analyze(sql, limits)?;
81 refuse_multiple_statements(&stripped, analysis.statements())?;
82 refuse_server_filesystem_access(&stripped, analysis.statements())?;
83
84 Ok(Admission { analysis, stripped })
85}
86
87pub fn refuse_multiple_statements(stripped: &Stripped, statements: &[Statement]) -> Result<()> {
101 let commands = stripped
102 .text()
103 .split(';')
104 .filter(|segment| !segment.trim().is_empty())
105 .count();
106
107 if statements.len() > 1 || commands > 1 {
108 return Err(Failure::validation(
109 "sql.multiple_statements",
110 "the text carries more than one statement",
111 )
112 .with_hint("send one statement per call"));
113 }
114 Ok(())
115}
116
117pub fn refuse_server_filesystem_access(
137 stripped: &Stripped,
138 statements: &[Statement],
139) -> Result<()> {
140 for statement in statements {
141 let mut finder = FilesystemFinder;
142 if let ControlFlow::Break(finding) = statement.visit(&mut finder) {
143 return Err(finding.into_failure());
144 }
145 }
146 refuse_file_access_by_text(stripped)
147}
148
149fn refuse_file_access_by_text(stripped: &Stripped) -> Result<()> {
154 let words = ascii_words(stripped.text());
155 for pair in words.windows(2) {
156 if pair[0].text == "into" && SERVER_FILE_WRITERS.contains(&pair[1].text.as_str()) {
157 return Err(Finding::FileOutput(pair[1].text.clone()).into_failure());
158 }
159 if pair[0].text == "local" && pair[1].text == CLIENT_FILE_READER {
160 return Err(Finding::ClientFileRead.into_failure());
161 }
162 }
163 for word in &words {
164 if SERVER_FILE_READERS.contains(&word.text.as_str()) && word.opens_a_call(stripped.text()) {
165 return Err(Finding::FileReader(word.text.clone()).into_failure());
166 }
167 }
168 Ok(())
169}
170
171#[derive(Debug, Clone)]
176struct Word {
177 text: String,
178 ends_at: usize,
179}
180
181impl Word {
182 fn opens_a_call(&self, text: &str) -> bool {
189 text[self.ends_at..]
190 .chars()
191 .find(|character| !character.is_whitespace())
192 == Some('(')
193 }
194}
195
196fn ascii_words(text: &str) -> Vec<Word> {
198 let mut words = Vec::new();
199 let mut current = String::new();
200 for (offset, character) in text.char_indices() {
201 if character.is_alphanumeric() || character == '_' {
202 current.extend(character.to_lowercase());
203 } else if !current.is_empty() {
204 words.push(Word {
205 text: std::mem::take(&mut current),
206 ends_at: offset,
207 });
208 }
209 }
210 if !current.is_empty() {
211 words.push(Word {
212 text: current,
213 ends_at: text.len(),
214 });
215 }
216 words
217}
218
219#[derive(Debug, Clone)]
221enum Finding {
222 FileReader(String),
224 FileOutput(String),
226 ClientFileRead,
228}
229
230impl Finding {
231 fn into_failure(self) -> Failure {
232 match self {
233 Self::FileReader(name) => Failure::validation(
234 "sql.server_file_read",
235 format!("the statement calls `{name}`, which reads a file on the server"),
236 )
237 .with_detail("detail", name)
238 .with_hint("read the file where it lives instead of through the server"),
239 Self::FileOutput(clause) => Failure::validation(
240 "sql.server_file_write",
241 format!("the statement uses `into {clause}`, which writes a file on the server"),
242 )
243 .with_detail("detail", format!("into {clause}"))
244 .with_hint("take the result on the primary channel and write it yourself"),
245 Self::ClientFileRead => Failure::validation(
246 "sql.client_file_read",
247 "the statement asks the server to read a file from this machine",
248 )
249 .with_hint("load the file with `data import`, which reads it here and never asks the server to"),
250 }
251 }
252}
253
254#[derive(Debug)]
256struct FilesystemFinder;
257
258impl FilesystemFinder {
259 fn check_call(name: &ObjectName) -> ControlFlow<Finding> {
261 let Some(last) = name
262 .0
263 .last()
264 .and_then(sqlparser::ast::ObjectNamePart::as_ident)
265 else {
266 return ControlFlow::Continue(());
267 };
268 let lowered = last.value.to_lowercase();
269 if SERVER_FILE_READERS.contains(&lowered.as_str()) {
270 return ControlFlow::Break(Finding::FileReader(lowered));
271 }
272 ControlFlow::Continue(())
273 }
274}
275
276impl Visitor for FilesystemFinder {
277 type Break = Finding;
278
279 fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<Self::Break> {
280 match expr {
281 Expr::Function(function) => Self::check_call(&function.name),
282 _ => ControlFlow::Continue(()),
283 }
284 }
285
286 fn pre_visit_statement(&mut self, statement: &Statement) -> ControlFlow<Self::Break> {
287 match statement {
288 Statement::Call(function) => Self::check_call(&function.name),
291 Statement::Directory { .. } | Statement::Unload { .. } => {
292 ControlFlow::Break(Finding::FileOutput("directory".to_owned()))
293 }
294 _ => ControlFlow::Continue(()),
295 }
296 }
297
298 fn pre_visit_select(&mut self, select: &Select) -> ControlFlow<Self::Break> {
299 let Some(into) = select.into.as_ref() else {
300 return ControlFlow::Continue(());
301 };
302 let Some(last) = into
303 .name
304 .0
305 .last()
306 .and_then(sqlparser::ast::ObjectNamePart::as_ident)
307 else {
308 return ControlFlow::Continue(());
309 };
310 let lowered = last.value.to_lowercase();
311 if SERVER_FILE_WRITERS.contains(&lowered.as_str()) {
312 return ControlFlow::Break(Finding::FileOutput(lowered));
313 }
314 ControlFlow::Continue(())
315 }
316}
317
318#[cfg(test)]
319mod tests {
320 use super::*;
321
322 fn refusal(sql: &str) -> Failure {
323 admit(sql, ParseLimits::default()).expect_err("the statement must be refused")
324 }
325
326 fn admitted(sql: &str) -> Admission {
327 admit(sql, ParseLimits::default()).expect("the statement must be admitted")
328 }
329
330 #[test]
331 fn a_single_statement_is_admitted() {
332 assert_eq!(admitted("SELECT 1").classification(), Classification::Read);
333 assert_eq!(
334 admitted("SELECT 1;").classification(),
335 Classification::Read,
336 "a trailing separator is not a second statement"
337 );
338 }
339
340 #[test]
343 fn two_statements_are_refused_even_when_the_text_ends_in_a_separator() {
344 for sql in [
345 "SELECT 1; SELECT 2;",
346 "SELECT 1; DROP TABLE users;",
347 "SELECT 1;DELETE FROM users;",
348 ] {
349 let failure = refusal(sql);
350 assert_eq!(failure.code(), "sql.multiple_statements", "input {sql:?}");
351 }
352 }
353
354 #[test]
355 fn two_statements_without_a_trailing_separator_are_refused_as_well() {
356 assert_eq!(
357 refusal("SELECT 1; SELECT 2").code(),
358 "sql.multiple_statements"
359 );
360 }
361
362 #[test]
363 fn a_separator_inside_a_literal_is_not_a_second_statement() {
364 assert_eq!(
365 admitted("SELECT 'a;b' AS note").classification(),
366 Classification::Read
367 );
368 }
369
370 #[test]
371 fn a_separator_inside_a_quoted_identifier_is_not_a_second_statement() {
372 assert_eq!(
373 admitted("SELECT 1 AS `a;b`").classification(),
374 Classification::Read
375 );
376 }
377
378 #[test]
379 fn a_separator_inside_a_comment_is_not_a_second_statement() {
380 assert_eq!(
381 admitted("SELECT 1 -- ; SELECT 2\n").classification(),
382 Classification::Read
383 );
384 }
385
386 #[test]
387 fn a_call_that_reads_a_server_file_is_refused() {
388 assert_eq!(
389 refusal("SELECT LOAD_FILE('/etc/passwd')").code(),
390 "sql.server_file_read"
391 );
392 }
393
394 #[test]
395 fn a_call_that_reads_a_server_file_is_found_inside_a_sub_query() {
396 for sql in [
397 "SELECT * FROM (SELECT LOAD_FILE('/etc/passwd') AS c) AS s",
398 "SELECT * FROM t WHERE a = (SELECT LOAD_FILE('/etc/passwd'))",
399 "SELECT a FROM t JOIN u ON u.a = LOAD_FILE('/etc/passwd')",
400 "SELECT CONCAT('x', LOAD_FILE('/etc/passwd'))",
401 ] {
402 assert_eq!(refusal(sql).code(), "sql.server_file_read", "input {sql:?}");
403 }
404 }
405
406 #[test]
407 fn a_schema_qualifier_does_not_hide_the_call() {
408 assert_eq!(
409 refusal("SELECT mysql.load_file('/etc/passwd')").code(),
410 "sql.server_file_read"
411 );
412 }
413
414 #[test]
415 fn the_name_of_a_file_reading_call_inside_a_literal_does_not_refuse() {
416 for sql in [
417 "SELECT 'LOAD_FILE(/etc/passwd)' AS note",
418 "SELECT * FROM t WHERE note = 'load_file'",
419 ] {
420 assert_eq!(
421 admitted(sql).classification(),
422 Classification::Read,
423 "input {sql:?}"
424 );
425 }
426 }
427
428 #[test]
429 fn a_column_merely_named_after_the_call_does_not_refuse() {
430 assert_eq!(
431 admitted("SELECT load_file FROM t").classification(),
432 Classification::Read
433 );
434 }
435
436 #[test]
437 fn a_clause_that_writes_a_server_file_is_refused() {
438 for sql in [
439 "SELECT * FROM t INTO OUTFILE '/tmp/x'",
440 "SELECT * FROM t INTO DUMPFILE '/tmp/x'",
441 "select a from t into outfile '/tmp/x'",
442 "SELECT a INTO OUTFILE '/tmp/x' FROM t",
443 "SELECT a /* hide */ INTO OUTFILE '/tmp/x' FROM t",
444 ] {
445 assert_eq!(
446 refusal(sql).code(),
447 "sql.server_file_write",
448 "input {sql:?}"
449 );
450 }
451 }
452
453 #[test]
456 fn the_write_clause_inside_a_literal_does_not_refuse() {
457 for sql in [
458 "SELECT 'INTO OUTFILE' AS note",
459 "SELECT * FROM t WHERE note = 'into dumpfile /tmp/x'",
460 "SELECT 1 -- INTO OUTFILE '/tmp/x'\n",
461 "SELECT 1 /* INTO OUTFILE */",
462 ] {
463 assert_eq!(
464 admitted(sql).classification(),
465 Classification::Read,
466 "input {sql:?}"
467 );
468 }
469 }
470
471 #[test]
472 fn an_unterminated_region_is_refused_before_anything_textual_runs() {
473 assert_eq!(
474 refusal("SELECT 'never closed").code(),
475 "sql.unterminated_region"
476 );
477 }
478
479 #[test]
480 fn a_conditional_comment_reaches_the_caller_as_code() {
481 let admission = admitted("SELECT /*!40001 SQL_NO_CACHE */ 1");
482 assert!(admission.stripped().has_conditional_comment());
483 assert!(admission.stripped().text().contains("SQL_NO_CACHE"));
484 }
485
486 #[test]
487 fn letter_case_does_not_change_a_refusal() {
488 assert_eq!(
489 refusal("select load_file('/etc/passwd')").code(),
490 "sql.server_file_read"
491 );
492 assert_eq!(
493 refusal("SELECT LoAd_FiLe('/etc/passwd')").code(),
494 "sql.server_file_read"
495 );
496 }
497
498 #[test]
499 fn a_statement_hidden_behind_a_comment_still_reaches_its_classification() {
500 assert_eq!(
501 admitted("/* SELECT */ DELETE FROM users").classification(),
502 Classification::Change
503 );
504 }
505
506 #[test]
510 fn a_load_that_reads_a_file_from_this_machine_is_refused_by_name() {
511 for statement in [
512 "LOAD DATA LOCAL INFILE '/etc/passwd' INTO TABLE t",
513 "load data local infile '/etc/passwd' into table t",
514 "LOAD DATA /* hide */ LOCAL INFILE '/etc/passwd' INTO TABLE t",
515 ] {
516 let failure = admit(statement, ParseLimits::default()).expect_err("must refuse");
517 assert_eq!(failure.code(), "sql.client_file_read", "for `{statement}`");
518 }
519 }
520
521 #[test]
535 fn a_file_reading_call_hidden_in_a_conditional_comment_is_refused() {
536 for sql in [
537 "SELECT 1 /*M!100000 ,LOAD_FILE('/etc/passwd') */",
538 "SELECT 1 /*!100000 ,LOAD_FILE('/etc/passwd') */",
539 "SELECT 1 /*m!100000 ,LOAD_FILE('/etc/passwd') */",
540 "SELECT 1 /*M! ,LOAD_FILE('/etc/passwd') */",
541 "SELECT 1 /*M!100000 ,mysql.load_file('/etc/passwd') */",
542 ] {
543 assert_eq!(refusal(sql).code(), "sql.server_file_read", "input {sql:?}");
544 }
545 }
546
547 #[test]
554 fn what_a_conditional_comment_adds_reaches_the_classification() {
555 assert_eq!(
556 admitted("SELECT 1 /*M!100000 ,2 */").classification(),
557 Classification::Read
558 );
559 assert_eq!(
560 refusal("SELECT 1 /*M!100000 */; DELETE FROM users").code(),
561 "sql.multiple_statements"
562 );
563 }
564
565 #[test]
573 fn a_conditional_comment_inside_a_plain_comment_carries_nothing_to_the_server() {
574 let failure = refusal("SELECT 1 /* /*M!100000 ,LOAD_FILE('/etc/passwd') */ */");
575 assert_eq!(failure.code(), "sql.unparsable");
576 }
577
578 #[test]
580 fn a_conditional_comment_written_inside_a_literal_refuses_nothing() {
581 assert_eq!(
582 admitted("SELECT '/*M!100000 LOAD_FILE(1) */' AS note").classification(),
583 Classification::Read
584 );
585 }
586
587 #[test]
589 fn the_words_of_a_local_load_inside_a_literal_do_not_refuse() {
590 let admitted = admit("SELECT 'local infile' AS note", ParseLimits::default())
591 .expect("a literal is not a clause");
592 assert!(admitted.analysis().classification().is_read());
593 }
594}