Skip to main content

mariadb_cli/sql/
guard.rs

1//! Structural refusals applied to a statement before it is sent.
2//!
3//! Each refusal here is driven by the syntax tree. Where the tree cannot carry
4//! the answer, the fallback reads the text produced by [`mod@crate::sql::strip`]
5//! and never the raw statement, which is the defect measured in both reference
6//! implementations.
7
8use 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
15/// Server-side functions that read a file from the server's own filesystem.
16///
17/// Names are compared in lower case against the last part of the call, so a
18/// schema qualifier does not hide the call.
19const SERVER_FILE_READERS: &[&str] = &["load_file", "loadfile"];
20
21/// Words that name a file the server would write, when they follow `into`.
22const SERVER_FILE_WRITERS: &[&str] = &["outfile", "dumpfile"];
23
24/// The word that turns a bulk load into a transfer from the caller's own disk,
25/// when it follows `local`.
26///
27/// No handler for that transfer is ever registered, so the driver would refuse
28/// it anyway. Refusing here as well names the real reason instead of leaving
29/// the caller with a generic transport complaint.
30const CLIENT_FILE_READER: &str = "infile";
31
32/// A statement that passed every structural refusal.
33#[derive(Debug, Clone)]
34pub struct Admission {
35    analysis: Analysis,
36    stripped: Stripped,
37}
38
39impl Admission {
40    /// What the statement does and the tree it was read from.
41    #[must_use]
42    pub const fn analysis(&self) -> &Analysis {
43        &self.analysis
44    }
45
46    /// What the statement does.
47    #[must_use]
48    pub const fn classification(&self) -> Classification {
49        self.analysis.classification()
50    }
51
52    /// The text with comments, literals and quoted identifiers blanked.
53    #[must_use]
54    pub const fn stripped(&self) -> &Stripped {
55        &self.stripped
56    }
57}
58
59/// Admits one statement, or says exactly why it is refused.
60///
61/// The order is fixed: blank the text, refuse an unterminated region, run the
62/// text safety net, read the tree, then apply the tree refusals. Nothing
63/// textual runs before the blanking.
64///
65/// The safety net runs before the parse on purpose. This parser does not know
66/// the server's clause for dumping a result into a file, so parsing such a
67/// statement fails and the caller would be told only that the text is
68/// unreadable. Running the net first names the real reason.
69///
70/// # Errors
71///
72/// Returns a validation failure when the statement is unterminated, unreadable,
73/// unrecognised, carries more than one command, or reaches the server's
74/// filesystem.
75pub 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
87/// Refuses a text that carries more than one command.
88///
89/// Two independent checks run, because either alone has a hole. The tree count
90/// is authoritative; the separator count over the blanked text catches a shape
91/// the parser folded into a single statement.
92///
93/// The reference implementation refuses a text that contains a separator and
94/// does not end in one, so `SELECT 1; SELECT 2;` passes it. Ending in a
95/// separator is not what makes a text single, and the tests below say so.
96///
97/// # Errors
98///
99/// Returns a validation failure when more than one command is present.
100pub 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
117/// Refuses a statement that reads or writes a file on the server.
118///
119/// The call is found by walking the tree, so a call nested in a sub-query, a
120/// join or an argument list is found just as the top-level one is, and a name
121/// that only appears inside a text literal is not found at all.
122///
123/// Both sides also have a text net, and for different reasons. The write clause
124/// is not one this parser knows, so a statement using it fails to parse and the
125/// caller would be told only that the text is unreadable. The read call is one
126/// the parser knows perfectly well, and the net exists because the tree was
127/// once measured to be missing it anyway: a call written inside a conditional
128/// comment reached the server and never reached the tree. That is fixed at the
129/// source now, in the preparation the parse runs first, and the net stays
130/// because a refusal that depends on one reading being right is a refusal one
131/// mistake away from silence.
132///
133/// # Errors
134///
135/// Returns a validation failure naming the call or the clause that was found.
136pub 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
149/// The safety net for both sides, run over the blanked text.
150///
151/// Working on the blanked text is what keeps `SELECT 'into outfile'` and
152/// `SELECT 'load_file(1)'` untouched: a literal is data and data never refuses.
153fn 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/// One run of word characters, and where it ended.
172///
173/// The end is carried because the name of a file-reading call is also a legal
174/// column name, and only the parenthesis that follows tells the two apart.
175#[derive(Debug, Clone)]
176struct Word {
177    text: String,
178    ends_at: usize,
179}
180
181impl Word {
182    /// Whether this word is being called rather than merely named.
183    ///
184    /// A call is the name followed by an opening parenthesis, with whitespace
185    /// allowed between the two because this server allows it. A column named
186    /// after the call is followed by anything else, so `SELECT load_file FROM t`
187    /// stays a legitimate query.
188    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
196/// Splits text into lower-case runs of word characters.
197fn 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/// What the tree walk found, if anything.
220#[derive(Debug, Clone)]
221enum Finding {
222    /// A call that reads a file on the server.
223    FileReader(String),
224    /// A clause that writes a file on the server.
225    FileOutput(String),
226    /// A clause that makes the server ask the caller for a local file.
227    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/// Walks a statement looking for anything that touches the server's filesystem.
255#[derive(Debug)]
256struct FilesystemFinder;
257
258impl FilesystemFinder {
259    /// Checks one called name against the file-reading calls.
260    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            // A procedure call carries its name outside any expression, so the
289            // expression hook alone would not see it.
290            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    /// The reference implementation lets this through, because it only refuses
341    /// a text that contains a separator without ending in one.
342    #[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    /// The safety net that catches the write clause must read the blanked text,
454    /// or a legitimate query mentioning the clause is refused.
455    #[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    /// The bulk load that makes the server ask this machine for a file is
507    /// refused by name, so the caller is told the real reason instead of
508    /// meeting a generic transport complaint.
509    #[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    /// A conditional comment carries code, so the tree has to be read from what
522    /// the server will run rather than from what the parser happens to keep.
523    ///
524    /// This is the shape the defect took. The blanking module declares the body
525    /// of `/*M! ... */` executable and keeps it, which is right, because the
526    /// server runs it. The parser crate expands only the introducer that starts
527    /// with an exclamation mark and throws the server-specific one away as
528    /// whitespace. Each side is defensible alone and the pair left a hole: the
529    /// call is caught by walking the tree, and the call was not in the tree.
530    ///
531    /// The trailing text matters. Dropping the comment has to leave a statement
532    /// that still reads, or the parser refuses it for being unreadable and the
533    /// hole never opens.
534    #[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    /// The body of a conditional comment reaches the tree, so what the tree
548    /// says about the statement is what the server will do with it.
549    ///
550    /// Without this the classification is computed over a different statement
551    /// than the one that runs, and every decision downstream inherits the
552    /// error, not just the filesystem refusal above.
553    #[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    /// A conditional comment commented out is not code, and the text that
566    /// wraps it is not a statement anywhere.
567    ///
568    /// This server does not nest block comments: the first closing delimiter
569    /// ends the comment, so what follows is left over and the server refuses
570    /// the text as unreadable. This product reaches the same answer by the same
571    /// route, and the call never leaves this machine either way.
572    #[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    /// The same text inside a literal is data, and data never refuses.
579    #[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    /// The same words inside a literal are data, and data never refuses.
588    #[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}