forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.2 MiB0a2c24cTahinli1 month ago179 commits

parse.rs367 lines, 12.4 KiBHistoryRawDownload
1//! Strict parsing of the SSH `exec` request: `git-upload-pack '/owner/repo.git'`.
2//!
3//! No shell is ever involved. The accepted grammar is deliberately tiny:
4//! one of four service prefixes, one space, then one argument that is either
5//! single-quoted or a bare token with no whitespace or quoting characters.
6
7use forge_git::GitService;
8
9#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
10pub enum ParseError {
11 #[error("unsupported command")]
12 UnsupportedCommand,
13 #[error("malformed repository path")]
14 MalformedPath,
15}
16
17/// Service prefixes accepted by the server. Both the hyphenated form git uses and
18/// the spaced form `git upload-pack` are allowed. Anything else is rejected.
19const PREFIXES: &[(&str, GitService)] = &[
20 ("git-upload-pack ", GitService::UploadPack),
21 ("git-receive-pack ", GitService::ReceivePack),
22 ("git upload-pack ", GitService::UploadPack),
23 ("git receive-pack ", GitService::ReceivePack),
24];
25
26/// Returns the service and the repository path with `.git` stripped and the
27/// leading `/` or `~/` removed. Anything else is an error.
28pub fn parse_exec(cmd: &str) -> Result<(GitService, String), ParseError> {
29 let (service, rest) = split_service(cmd)?;
30 let raw = unquote_argument(rest)?;
31 let path = normalize_path(raw)?;
32 Ok((service, path))
33}
34
35/// Exec prefix of the Git LFS authenticate request.
36pub(crate) const LFS_AUTHENTICATE_PREFIX: &str = "git-lfs-authenticate ";
37
38/// Direction of a `git-lfs-authenticate` request.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum LfsOperation {
41 Download,
42 Upload,
43}
44
45/// Parses `git-lfs-authenticate '<owner>/<repo>[.git]' download|upload`. The path follows the
46/// same rules as `parse_exec`, and the operation must be exactly `download` or `upload`.
47pub fn parse_lfs_authenticate(cmd: &str) -> Result<(String, LfsOperation), ParseError> {
48 let rest = cmd
49 .strip_prefix(LFS_AUTHENTICATE_PREFIX)
50 .ok_or(ParseError::UnsupportedCommand)?;
51 // The path argument ends at its closing quote, or at the first space when it is bare.
52 let end = if let Some(quoted) = rest.strip_prefix('\'') {
53 quoted.find('\'').ok_or(ParseError::MalformedPath)? + 2
54 } else {
55 rest.find(' ').ok_or(ParseError::MalformedPath)?
56 };
57 let (arg, tail) = rest.split_at(end);
58 let operation = match tail {
59 " download" => LfsOperation::Download,
60 " upload" => LfsOperation::Upload,
61 _ => return Err(ParseError::MalformedPath),
62 };
63 let path = normalize_path(unquote_argument(arg)?)?;
64 Ok((path, operation))
65}
66
67fn split_service(cmd: &str) -> Result<(GitService, &str), ParseError> {
68 PREFIXES
69 .iter()
70 .find_map(|(prefix, service)| cmd.strip_prefix(prefix).map(|rest| (*service, rest)))
71 .ok_or(ParseError::UnsupportedCommand)
72}
73
74/// Extracts the argument. A quoted argument may contain spaces but no quotes,
75/// backslashes or control characters. An unquoted argument must contain none of
76/// whitespace, quotes, backslashes or control characters.
77fn unquote_argument(rest: &str) -> Result<&str, ParseError> {
78 if let Some(quoted) = rest.strip_prefix('\'') {
79 let inner = quoted.strip_suffix('\'').ok_or(ParseError::MalformedPath)?;
80 if inner
81 .chars()
82 .any(|c| matches!(c, '\'' | '\\') || c.is_control())
83 {
84 return Err(ParseError::MalformedPath);
85 }
86 return Ok(inner);
87 }
88 if rest.is_empty()
89 || rest
90 .chars()
91 .any(|c| c.is_whitespace() || matches!(c, '\'' | '"' | '\\') || c.is_control())
92 {
93 return Err(ParseError::MalformedPath);
94 }
95 Ok(rest)
96}
97
98/// Strips one leading `/` or `~/`, then requires exactly `owner/repo` or
99/// `owner/repo.git`, returning `owner/repo`.
100fn normalize_path(raw: &str) -> Result<String, ParseError> {
101 let path = raw.strip_prefix('/').unwrap_or(raw);
102 let path = path.strip_prefix("~/").unwrap_or(path);
103
104 let segments: Vec<&str> = path.split('/').collect();
105 let [owner, repo] = segments.as_slice() else {
106 return Err(ParseError::MalformedPath);
107 };
108 for segment in [owner, repo] {
109 if segment.is_empty()
110 || *segment == ".."
111 || segment.starts_with('-')
112 || segment.starts_with('.')
113 || !segment
114 .bytes()
115 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
116 {
117 return Err(ParseError::MalformedPath);
118 }
119 }
120
121 let repo = repo.strip_suffix(".git").unwrap_or(repo);
122 if repo.is_empty() {
123 return Err(ParseError::MalformedPath);
124 }
125 Ok(format!("{owner}/{repo}"))
126}
127
128#[cfg(test)]
129mod tests {
130 use super::*;
131
132 fn ok(cmd: &str) -> (GitService, String) {
133 match parse_exec(cmd) {
134 Ok(v) => v,
135 Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"),
136 }
137 }
138
139 fn err(cmd: &str) -> ParseError {
140 match parse_exec(cmd) {
141 Ok(v) => panic!("expected {cmd:?} to be rejected, got {v:?}"),
142 Err(e) => e,
143 }
144 }
145
146 #[test]
147 fn accepts_valid_exec_commands() {
148 // Covers both services, wiki suffix, spaced form, leading slash and
149 // tilde stripping, and unquoted paths.
150 let cases: &[(&str, GitService, &str)] = &[
151 (
152 "git-upload-pack '/tahinli/proj.git'",
153 GitService::UploadPack,
154 "tahinli/proj",
155 ),
156 (
157 "git-receive-pack '/tahinli/proj.git'",
158 GitService::ReceivePack,
159 "tahinli/proj",
160 ),
161 (
162 "git-receive-pack '/tahinli/proj.wiki.git'",
163 GitService::ReceivePack,
164 "tahinli/proj.wiki",
165 ),
166 (
167 "git-upload-pack 'tahinli/proj.wiki'",
168 GitService::UploadPack,
169 "tahinli/proj.wiki",
170 ),
171 (
172 "git upload-pack '/tahinli/proj'",
173 GitService::UploadPack,
174 "tahinli/proj",
175 ),
176 (
177 "git receive-pack 'tahinli/proj.git'",
178 GitService::ReceivePack,
179 "tahinli/proj",
180 ),
181 (
182 "git-upload-pack '~/tahinli/proj'",
183 GitService::UploadPack,
184 "tahinli/proj",
185 ),
186 (
187 "git-upload-pack '/~/tahinli/proj'",
188 GitService::UploadPack,
189 "tahinli/proj",
190 ),
191 (
192 "git-upload-pack 'tahinli/proj'",
193 GitService::UploadPack,
194 "tahinli/proj",
195 ),
196 (
197 "git-upload-pack /tahinli/proj.git",
198 GitService::UploadPack,
199 "tahinli/proj",
200 ),
201 (
202 "git-receive-pack tahinli/proj",
203 GitService::ReceivePack,
204 "tahinli/proj",
205 ),
206 ];
207 for (cmd, service, path) in cases {
208 assert_eq!(ok(cmd), (*service, path.to_string()), "case {cmd}");
209 }
210 }
211
212 #[test]
213 fn rejects_malformed_exec_paths() {
214 // Option, shell and traversal injection, bad quoting, control
215 // characters, wrong segment counts, empty values and stray spaces.
216 let cases: &[&str] = &[
217 // Only one leading slash is stripped.
218 "git-upload-pack '//tahinli/proj'",
219 // Unquoted paths with a quote, backslash or space.
220 "git-upload-pack a/b c",
221 "git-upload-pack a/b'",
222 "git-upload-pack a\"b/c",
223 "git-upload-pack a\\b/c",
224 // Option injection.
225 "git-upload-pack '--help'",
226 "git-upload-pack '--upload-pack=touch /x'",
227 "git-upload-pack '-x/y'",
228 "git-upload-pack 'a/-b'",
229 // Shell injection.
230 "git-upload-pack 'a/b'; rm -rf /",
231 "git-upload-pack 'a/b' 'c/d'",
232 "git-upload-pack 'a/b$(id)'",
233 "git-upload-pack 'a/b;c'",
234 "git-upload-pack 'a/b|c'",
235 "git-upload-pack 'a/b&c'",
236 "git-upload-pack 'a/b%20c'",
237 "git-upload-pack 'a/é'",
238 "git-upload-pack 'a/b`id`'",
239 "git-upload-pack 'a/b' && id",
240 // Quote, backslash, newline, NUL and control characters inside quotes.
241 "git-upload-pack 'a/b\\c'",
242 "git-upload-pack 'a/b\nc'",
243 "git-upload-pack 'a/b\rc'",
244 "git-upload-pack 'a/b\0c'",
245 "git-upload-pack 'a/b\x07c'",
246 "git-upload-pack 'a/b\x7fc'",
247 "git-upload-pack 'a/b'c'",
248 // Traversal and hidden segments.
249 "git-upload-pack '../x/y'",
250 "git-upload-pack 'a/..'",
251 "git-upload-pack '/a/../b'",
252 "git-upload-pack '.hidden/repo'",
253 "git-upload-pack 'owner/.git'",
254 // Wrong segment count.
255 "git-upload-pack 'a/b/c'",
256 "git-upload-pack 'a'",
257 "git-upload-pack 'a/'",
258 "git-upload-pack '/a/b/'",
259 "git-upload-pack '//'",
260 // Empty values.
261 "git-upload-pack ''",
262 "git-upload-pack '/'",
263 "git-upload-pack '~/'",
264 "git-upload-pack '.git'",
265 "git-upload-pack ",
266 // Extra spaces and trailing garbage.
267 "git-upload-pack '/a/b'",
268 "git-upload-pack '/a/b' ",
269 "git-upload-pack '/a/b",
270 ];
271 for cmd in cases {
272 assert_eq!(err(cmd), ParseError::MalformedPath, "case {cmd:?}");
273 }
274 }
275
276 #[test]
277 fn rejects_unknown_commands() {
278 let cases: &[&str] = &[
279 "git-upload-archive '/a/b'",
280 "git upload-archive '/a/b'",
281 "ls -la",
282 "",
283 "git-upload-packx '/a/b'",
284 "git-upload-pack'/a/b'",
285 "git-upload-pack",
286 "GIT-UPLOAD-PACK '/a/b'",
287 " git-upload-pack '/a/b'",
288 ];
289 for cmd in cases {
290 assert_eq!(err(cmd), ParseError::UnsupportedCommand, "case {cmd:?}");
291 }
292 }
293
294 fn lfs_ok(cmd: &str) -> (String, LfsOperation) {
295 match parse_lfs_authenticate(cmd) {
296 Ok(v) => v,
297 Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"),
298 }
299 }
300
301 fn lfs_err(cmd: &str) -> ParseError {
302 match parse_lfs_authenticate(cmd) {
303 Ok(v) => panic!("expected {cmd:?} to be rejected, got {v:?}"),
304 Err(e) => e,
305 }
306 }
307
308 #[test]
309 fn lfs_accepts_quoted_and_bare_paths() {
310 let cases: &[(&str, &str, LfsOperation)] = &[
311 (
312 "git-lfs-authenticate '/tahinli/proj.git' download",
313 "tahinli/proj",
314 LfsOperation::Download,
315 ),
316 (
317 "git-lfs-authenticate 'tahinli/proj' upload",
318 "tahinli/proj",
319 LfsOperation::Upload,
320 ),
321 (
322 "git-lfs-authenticate /tahinli/proj.git upload",
323 "tahinli/proj",
324 LfsOperation::Upload,
325 ),
326 ];
327 for (cmd, path, op) in cases {
328 assert_eq!(lfs_ok(cmd), (path.to_string(), *op), "case {cmd}");
329 }
330 }
331
332 #[test]
333 fn lfs_rejects_malformed_commands() {
334 let cases: &[&str] = &[
335 // Bad operation.
336 "git-lfs-authenticate 'a/b' push",
337 "git-lfs-authenticate 'a/b' ",
338 "git-lfs-authenticate 'a/b' download extra",
339 "git-lfs-authenticate 'a/b'download",
340 "git-lfs-authenticate 'a/b' Download",
341 // Bad paths.
342 "git-lfs-authenticate '--help' download",
343 "git-lfs-authenticate '../x/y' upload",
344 "git-lfs-authenticate 'a/b'; id download",
345 "git-lfs-authenticate 'a/b' 'c' download",
346 "git-lfs-authenticate 'a/b download",
347 "git-lfs-authenticate a/b c download",
348 "git-lfs-authenticate 'a/b/c' download",
349 "git-lfs-authenticate ''",
350 ];
351 for cmd in cases {
352 assert_eq!(lfs_err(cmd), ParseError::MalformedPath, "case {cmd:?}");
353 }
354 }
355
356 #[test]
357 fn lfs_rejects_other_commands() {
358 assert_eq!(
359 lfs_err("git-upload-pack 'a/b' download"),
360 ParseError::UnsupportedCommand
361 );
362 assert_eq!(
363 lfs_err("git-lfs-authenticate-x 'a/b' download"),
364 ParseError::UnsupportedCommand
365 );
366 }
367}