Debian Codegraph @

tests/sqlite/rustsec.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use sqlx::{Connection, Error, SqliteConnection};
2
3 // https://rustsec.org/advisories/RUSTSEC-2024-0363.html
4 //
5 // Similar theory to the Postgres exploit in `tests/postgres/rustsec.rs` but much simpler
6 // since we just want to overflow the query length itself.
7 #[sqlx::test]
•8 #[cfg(not(target_pointer_width = "32"))]
9 async fn rustsec_2024_0363() -> anyhow::Result<()> {
10 let overflow_len = 4 * 1024 * 1024 * 1024; // 4 GiB
11
12 // `real_query_prefix` plus `fake_message` will be the first query that SQLite "sees"
13 //
14 // Rather contrived because this already represents a regular SQL injection,
15 // but this is the easiest way to demonstrate the exploit for SQLite.
16 let real_query_prefix = "INSERT INTO injection_target(message) VALUES ('";
17 let fake_message = "fake_msg') RETURNING id;";
18 let real_query_suffix = "') RETURNING id";
19
20 // Our actual payload is another query
21 let real_payload =
22 "\nUPDATE injection_target SET message = 'you''ve been pwned!' WHERE id = 1;\n--";
23
24 // This will parse the query up to `real_payload`.
25 let fake_payload_len = real_query_prefix.len() + fake_message.len();
26
27 // Pretty easy to see that this will overflow to `fake_payload_len`
28 let target_len = overflow_len + fake_payload_len;
29
30 let inject_len = target_len - real_query_prefix.len() - real_query_suffix.len();
31
32 let pad_len = inject_len - fake_message.len() - real_payload.len();
33
34 let mut injected_value = String::with_capacity(inject_len);
35 injected_value.push_str(fake_message);
36 injected_value.push_str(real_payload);
37
38 let padding = " ".repeat(pad_len);
39 injected_value.push_str(&padding);
40
41 let query = format!("{real_query_prefix}{injected_value}{real_query_suffix}");
42
43 assert_eq!(query.len(), target_len);
44
45 let mut conn = SqliteConnection::connect("sqlite://:memory:").await?;
46
47 sqlx::raw_sql(
48 "CREATE TABLE injection_target(id INTEGER PRIMARY KEY, message TEXT);\n\
49 INSERT INTO injection_target(message) VALUES ('existing message');",
50 )
51 .execute(&mut conn)
52 .await?;
53
54 let res = sqlx::raw_sql(&query).execute(&mut conn).await;
55
56 if let Err(e) = res {
57 // Connection rejected the query; we're happy.
58 if matches!(e, Error::Protocol(_)) {
59 return Ok(());
60 }
61
62 panic!("unexpected error: {e:?}");
63 }
64
65 let messages: Vec<String> =
66 sqlx::query_scalar("SELECT message FROM injection_target ORDER BY id")
67 .fetch_all(&mut conn)
68 .await?;
69
70 // If the injection succeeds, `messages` will look like:
71 // ["you've been pwned!'.to_string(), "fake_msg".to_string()]
72 assert_eq!(
73 messages,
74 ["existing message".to_string(), "fake_msg".to_string()]
75 );
76
77 // Injection didn't affect our database; we're happy.
78 Ok(())
79 }