mysqladm/server/
input_sanitization.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
use crate::core::{
    common::UnixUser,
    protocol::server_responses::{NameValidationError, OwnerValidationError},
};

const MAX_NAME_LENGTH: usize = 64;

pub fn validate_name(name: &str) -> Result<(), NameValidationError> {
    if name.is_empty() {
        Err(NameValidationError::EmptyString)
    } else if name.len() > MAX_NAME_LENGTH {
        Err(NameValidationError::TooLong)
    } else if !name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
    {
        Err(NameValidationError::InvalidCharacters)
    } else {
        Ok(())
    }
}

pub fn validate_ownership_by_unix_user(
    name: &str,
    user: &UnixUser,
) -> Result<(), OwnerValidationError> {
    let prefixes = std::iter::once(user.username.to_owned())
        .chain(user.groups.iter().cloned())
        .collect::<Vec<String>>();

    validate_ownership_by_prefixes(name, &prefixes)
}

/// Core logic for validating the ownership of a database name.
/// This function checks if the given name matches any of the given prefixes.
/// These prefixes will in most cases be the user's unix username and any
/// unix groups the user is a member of.
pub fn validate_ownership_by_prefixes(
    name: &str,
    prefixes: &[String],
) -> Result<(), OwnerValidationError> {
    if name.is_empty() {
        return Err(OwnerValidationError::StringEmpty);
    }

    if prefixes
        .iter()
        .filter(|p| name.starts_with(&(p.to_string() + "_")))
        .collect::<Vec<_>>()
        .is_empty()
    {
        return Err(OwnerValidationError::NoMatch);
    };

    Ok(())
}

#[inline]
pub fn quote_literal(s: &str) -> String {
    format!("'{}'", s.replace('\'', r"\'"))
}

#[inline]
pub fn quote_identifier(s: &str) -> String {
    format!("`{}`", s.replace('`', r"\`"))
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_quote_literal() {
        let payload = "' OR 1=1 --";
        assert_eq!(quote_literal(payload), r#"'\' OR 1=1 --'"#);
    }

    #[test]
    fn test_quote_identifier() {
        let payload = "` OR 1=1 --";
        assert_eq!(quote_identifier(payload), r#"`\` OR 1=1 --`"#);
    }

    #[test]
    fn test_validate_name() {
        assert_eq!(validate_name(""), Err(NameValidationError::EmptyString));
        assert_eq!(validate_name("abcdefghijklmnopqrstuvwxyz"), Ok(()));
        assert_eq!(validate_name("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), Ok(()));
        assert_eq!(validate_name("0123456789_-"), Ok(()));

        for c in "\n\t\r !@#$%^&*()+=[]{}|;:,.<>?/".chars() {
            assert_eq!(
                validate_name(&c.to_string()),
                Err(NameValidationError::InvalidCharacters)
            );
        }

        assert_eq!(validate_name(&"a".repeat(MAX_NAME_LENGTH)), Ok(()));

        assert_eq!(
            validate_name(&"a".repeat(MAX_NAME_LENGTH + 1)),
            Err(NameValidationError::TooLong)
        );
    }

    #[test]
    fn test_validate_owner_by_prefixes() {
        let prefixes = vec!["user".to_string(), "group".to_string()];

        assert_eq!(
            validate_ownership_by_prefixes("", &prefixes),
            Err(OwnerValidationError::StringEmpty)
        );

        assert_eq!(
            validate_ownership_by_prefixes("user_testdb", &prefixes),
            Ok(())
        );
        assert_eq!(
            validate_ownership_by_prefixes("group_testdb", &prefixes),
            Ok(())
        );
        assert_eq!(
            validate_ownership_by_prefixes("group_test_db", &prefixes),
            Ok(())
        );
        assert_eq!(
            validate_ownership_by_prefixes("group_test-db", &prefixes),
            Ok(())
        );

        assert_eq!(
            validate_ownership_by_prefixes("nonexistent_testdb", &prefixes),
            Err(OwnerValidationError::NoMatch)
        );
    }
}