forge
Explore
Log in

Don't you dare go Hollow

🛡️ forms drop control characters; registered URIs and public URLs must be ASCII

Browse files at this commit

ec1c66ec7d4e614ce224052e0d73d0e6d4081430Ahmet Kaan GümüşParent: 2920fdc
crates/im-core/src/names.rsmodified+42 -0
@@ -11,6 +11,8 @@
11 //! in mail and in other apps, so control characters and bidirectional overrides are refused: they11 //! in mail and in other apps, so control characters and bidirectional overrides are refused: they
12 //! can make one name read as another.12 //! can make one name read as another.
13 13
14+use serde::Deserialize;
15+
14 use crate::error::{Error, Result};16 use crate::error::{Error, Result};
15 17
16 /// Longest display name, in characters. The schema has the same limit.18 /// Longest display name, in characters. The schema has the same limit.
@@ -63,6 +65,40 @@ pub fn parse_display_name(input: &str) -> Result<String> {
63 Ok(name.to_owned())65 Ok(name.to_owned())
64 }66 }
65 67
68+/// Removes the control characters from a single-line field: every C0 control (U+0000 to U+001F, so NUL,
69+/// tab and line breaks too) and DEL (U+007F). Applied where form values are read, so a typed control
70+/// character is never used or echoed back into a page.
71+pub fn strip_line_controls(input: &str) -> String {
72+ input.chars().filter(|&c| !is_c0_or_del(c)).collect()
73+}
74+
75+/// Removes the control characters from a multi-line field, keeping line feed and tab. A carriage return
76+/// is removed, so a browser's CRLF becomes LF.
77+pub fn strip_text_controls(input: &str) -> String {
78+ input
79+ .chars()
80+ .filter(|&c| c == '\n' || c == '\t' || !is_c0_or_del(c))
81+ .collect()
82+}
83+
84+/// Serde adapter for a single-line form field: see [`strip_line_controls`].
85+pub fn single_line<'de, D: serde::Deserializer<'de>>(
86+ de: D,
87+) -> std::result::Result<String, D::Error> {
88+ String::deserialize(de).map(|text| strip_line_controls(&text))
89+}
90+
91+/// Serde adapter for a multi-line form field: see [`strip_text_controls`].
92+pub fn multi_line<'de, D: serde::Deserializer<'de>>(
93+ de: D,
94+) -> std::result::Result<String, D::Error> {
95+ String::deserialize(de).map(|text| strip_text_controls(&text))
96+}
97+
98+fn is_c0_or_del(c: char) -> bool {
99+ c.is_ascii_control()
100+}
101+
66 /// The bidirectional embedding, override and isolate controls that [`parse_display_name`] refuses.102 /// The bidirectional embedding, override and isolate controls that [`parse_display_name`] refuses.
67 fn is_bidi_control(c: char) -> bool {103 fn is_bidi_control(c: char) -> bool {
68 matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')104 matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
@@ -145,6 +181,12 @@ mod tests {
145 }181 }
146 }182 }
147 183
184+ #[test]
185+ fn form_text_loses_controls_and_multi_line_keeps_line_feed_and_tab() {
186+ assert_eq!(strip_line_controls("a\u{0}b\u{7f}c\td\ne"), "abcde");
187+ assert_eq!(strip_text_controls("a\r\nb\tc\u{0}d"), "a\nb\tcd");
188+ }
189+
148 #[test]190 #[test]
149 fn attack_strings_are_refused() {191 fn attack_strings_are_refused() {
150 let long_local = format!("{}@example.com", "a".repeat(MAX_LOCAL_LEN + 1));192 let long_local = format!("{}@example.com", "a".repeat(MAX_LOCAL_LEN + 1));
crates/im-core/src/oauth.rsmodified+8 -2
@@ -57,10 +57,13 @@ pub fn is_valid_verifier(verifier: &str) -> bool {
57 }57 }
58 58
59 /// True for a registrable URI: `https`, or `http` to a loopback host (for development), absolute, with59 /// True for a registrable URI: `https`, or `http` to a loopback host (for development), absolute, with
60-/// no fragment, no userinfo (`@`), no whitespace or control characters and no backslash. Redirect URIs,60+/// no fragment, no userinfo (`@`), no whitespace or control characters and no backslash. A registered URI
61-/// post-logout URIs and back-channel URIs all use this rule.61+/// is ASCII only: a Unicode character, such as a bidi override, could show the URI differently from how it
62+/// is stored, so other bytes must be percent-encoded. Redirect URIs, post-logout URIs and back-channel URIs
63+/// all use this rule.
62 pub fn is_valid_registered_uri(uri: &str) -> bool {64 pub fn is_valid_registered_uri(uri: &str) -> bool {
63 if uri.len() > MAX_URI_BYTES65 if uri.len() > MAX_URI_BYTES
66+ || !uri.is_ascii()
64 || uri.bytes().any(|b| b <= 0x20 || b == 0x7f || b == b'\\')67 || uri.bytes().any(|b| b <= 0x20 || b == 0x7f || b == b'\\')
65 || uri.contains('#')68 || uri.contains('#')
66 {69 {
@@ -151,6 +154,9 @@ mod tests {
151 "https://in.example.com\\evil",154 "https://in.example.com\\evil",
152 "in.example.com/auth/callback",155 "in.example.com/auth/callback",
153 "javascript://in.example.com/x",156 "javascript://in.example.com/x",
157+ "https://in.example.com/\u{202e}abc",
158+ "https://in.example.com/caf\u{e9}",
159+ "https://in.example.com/\u{0}",
154 ] {160 ] {
155 assert!(!is_valid_registered_uri(bad), "accepted {bad:?}");161 assert!(!is_valid_registered_uri(bad), "accepted {bad:?}");
156 }162 }
crates/im-web/src/pages/admin/clients.rsmodified+11 -9
@@ -12,7 +12,7 @@
12 12
13 use im_core::Error as CoreError;13 use im_core::Error as CoreError;
14 use im_core::model::{AuditAction, Client, Service};14 use im_core::model::{AuditAction, Client, Service};
15-use im_core::names::parse_display_name;15+use im_core::names::{multi_line, parse_display_name, single_line};
16 use im_core::oauth::{is_client_family_key, is_supported_scope, is_valid_registered_uri};16 use im_core::oauth::{is_client_family_key, is_supported_scope, is_valid_registered_uri};
17 use im_core::store::admin::ClientEdit;17 use im_core::store::admin::ClientEdit;
18 use im_core::store::clients::NewClient;18 use im_core::store::clients::NewClient;
@@ -46,23 +46,23 @@ const DEFAULT_SCOPES: &str = "openid profile email";
46 struct ClientForm {46 struct ClientForm {
47 #[serde(default)]47 #[serde(default)]
48 csrf: String,48 csrf: String,
49- #[serde(default)]49+ #[serde(default, deserialize_with = "single_line")]
50 name: String,50 name: String,
51 /// One URI per line.51 /// One URI per line.
52- #[serde(default)]52+ #[serde(default, deserialize_with = "multi_line")]
53 redirect_uris: String,53 redirect_uris: String,
54 /// One URI per line.54 /// One URI per line.
55- #[serde(default)]55+ #[serde(default, deserialize_with = "multi_line")]
56 post_logout_uris: String,56 post_logout_uris: String,
57- #[serde(default)]57+ #[serde(default, deserialize_with = "single_line")]
58 backchannel_uri: String,58 backchannel_uri: String,
59 /// Space-separated scopes.59 /// Space-separated scopes.
60- #[serde(default)]60+ #[serde(default, deserialize_with = "single_line")]
61 scopes: String,61 scopes: String,
62- #[serde(default)]62+ #[serde(default, deserialize_with = "single_line")]
63 family_key: String,63 family_key: String,
64 /// The origin of a family app, such as `https://in.example.com`.64 /// The origin of a family app, such as `https://in.example.com`.
65- #[serde(default)]65+ #[serde(default, deserialize_with = "single_line")]
66 public_url: String,66 public_url: String,
67 }67 }
68 68
@@ -150,13 +150,15 @@ fn uri_lines(text: &str) -> std::result::Result<Vec<String>, &'static str> {
150 Ok(uris)150 Ok(uris)
151 }151 }
152 152
153-/// True for an origin: `http://` or `https://`, a host, and no path, space or query.153+/// True for an origin: `http://` or `https://`, a host, and no path, space or query. ASCII only, like a
154+/// registered URI.
154 pub(crate) fn is_origin(url: &str) -> bool {155 pub(crate) fn is_origin(url: &str) -> bool {
155 let rest = url156 let rest = url
156 .strip_prefix("https://")157 .strip_prefix("https://")
157 .or_else(|| url.strip_prefix("http://"));158 .or_else(|| url.strip_prefix("http://"));
158 rest.is_some_and(|rest| {159 rest.is_some_and(|rest| {
159 !rest.is_empty()160 !rest.is_empty()
161+ && url.is_ascii()
160 && !rest.contains(['/', '?', '#', '@'])162 && !rest.contains(['/', '?', '#', '@'])
161 && !url.chars().any(char::is_whitespace)163 && !url.chars().any(char::is_whitespace)
162 })164 })
crates/im-web/src/pages/admin/message.rsmodified+3 -2
@@ -8,6 +8,7 @@
8 use std::time::Instant;8 use std::time::Instant;
9 9
10 use im_core::model::AuditAction;10 use im_core::model::AuditAction;
11+use im_core::names::{multi_line, single_line};
11 use serde::Deserialize;12 use serde::Deserialize;
12 use serde_json::json;13 use serde_json::json;
13 use topcoat::Result;14 use topcoat::Result;
@@ -54,9 +55,9 @@ const THROTTLE_KEY: &str = "admin-message";
54 struct MessageForm {55 struct MessageForm {
55 #[serde(default)]56 #[serde(default)]
56 csrf: String,57 csrf: String,
57- #[serde(default)]58+ #[serde(default, deserialize_with = "single_line")]
58 subject: String,59 subject: String,
59- #[serde(default)]60+ #[serde(default, deserialize_with = "multi_line")]
60 body: String,61 body: String,
61 }62 }
62 63
crates/im-web/src/pages/admin/users.rsmodified+2 -2
@@ -10,7 +10,7 @@
10 10
11 use im_core::Error as CoreError;11 use im_core::Error as CoreError;
12 use im_core::model::{AuditAction, User};12 use im_core::model::{AuditAction, User};
13-use im_core::names::normalize_email;13+use im_core::names::{normalize_email, single_line};
14 use im_core::store::admin::AdminChange;14 use im_core::store::admin::AdminChange;
15 use im_core::store::backchannel::EndReason;15 use im_core::store::backchannel::EndReason;
16 use serde::Deserialize;16 use serde::Deserialize;
@@ -39,7 +39,7 @@ use crate::views::{ViewerInfo, page_lang, shell};
39 /// The query of the account list: the search, the cursor of the next page, and the flash codes.39 /// The query of the account list: the search, the cursor of the next page, and the flash codes.
40 #[derive(Deserialize, Default)]40 #[derive(Deserialize, Default)]
41 struct UsersQuery {41 struct UsersQuery {
42- #[serde(default)]42+ #[serde(default, deserialize_with = "single_line")]
43 q: String,43 q: String,
44 /// `created_at|id` of the last account of the previous page.44 /// `created_at|id` of the last account of the previous page.
45 #[serde(default)]45 #[serde(default)]
crates/im-web/src/pages/login.rsmodified+2 -2
@@ -9,7 +9,7 @@ use std::sync::OnceLock;
9 use std::time::{Duration, Instant};9 use std::time::{Duration, Instant};
10 10
11 use im_core::model::{AuditAction, User, amr};11 use im_core::model::{AuditAction, User, amr};
12-use im_core::names::normalize_email;12+use im_core::names::{normalize_email, single_line};
13 use im_core::password::{hash_password_async, verify_password_async};13 use im_core::password::{hash_password_async, verify_password_async};
14 use im_core::store::sessions::SignInState;14 use im_core::store::sessions::SignInState;
15 use im_core::time::stamp_after;15 use im_core::time::stamp_after;
@@ -43,7 +43,7 @@ use crate::views::{alert, field, page_lang, shell};
43 struct LoginForm {43 struct LoginForm {
44 #[serde(default)]44 #[serde(default)]
45 precsrf: String,45 precsrf: String,
46- #[serde(default)]46+ #[serde(default, deserialize_with = "single_line")]
47 email: String,47 email: String,
48 #[serde(default)]48 #[serde(default)]
49 password: String,49 password: String,