| 1 | #[cfg(unix)] |
| 2 | use super::*; |
| 3 | |
| 4 | #[cfg(unix)] |
| 5 | struct RepoFixture { |
| 6 | _root: tempfile::TempDir, |
| 7 | repo: std::path::PathBuf, |
| 8 | secret_path: std::path::PathBuf, |
| 9 | canary_path: std::path::PathBuf, |
| 10 | secret_value: &'static str, |
| 11 | } |
| 12 | |
| 13 | #[cfg(unix)] |
| 14 | impl RepoFixture { |
| 15 | fn new(config_snippet: &str, attributes: Option<&str>, add_signed_commit: bool) -> Self { |
| 16 | let root = crate::test_support::sandbox_visible_tempdir(); |
| 17 | let repo = root.path().join("repo"); |
| 18 | std::fs::create_dir_all(&repo).unwrap(); |
| 19 | let secret_path = root.path().join("secret.txt"); |
| 20 | let canary_path = root.path().join("ran.canary"); |
| 21 | let secret_value = "GIT-HARDENING-CANARY-9f2a"; |
| 22 | std::fs::write(&secret_path, format!("{secret_value}\n")).unwrap(); |
| 23 | |
| 24 | let git = |args: &[&str]| { |
| 25 | let status = std::process::Command::new("git") |
| 26 | .args(args) |
| 27 | .current_dir(&repo) |
| 28 | .env("GIT_CONFIG_NOSYSTEM", "1") |
| 29 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 30 | .status() |
| 31 | .expect("run git"); |
| 32 | assert!(status.success(), "git {args:?} failed: {status}"); |
| 33 | }; |
| 34 | |
| 35 | git(&["init", "-q"]); |
| 36 | git(&["config", "user.email", "test@example.invalid"]); |
| 37 | git(&["config", "user.name", "Test"]); |
| 38 | std::fs::write(repo.join("a.txt"), "hello\n").unwrap(); |
| 39 | if let Some(attrs) = attributes { |
| 40 | std::fs::write(repo.join(".gitattributes"), attrs).unwrap(); |
| 41 | } |
| 42 | git(&["add", "-A"]); |
| 43 | git(&["commit", "-qm", "init"]); |
| 44 | |
| 45 | if add_signed_commit { |
| 46 | let tree = String::from_utf8( |
| 47 | std::process::Command::new("git") |
| 48 | .args(["rev-parse", "HEAD^{tree}"]) |
| 49 | .current_dir(&repo) |
| 50 | .output() |
| 51 | .expect("rev-parse") |
| 52 | .stdout, |
| 53 | ) |
| 54 | .unwrap(); |
| 55 | let commit_obj = format!( |
| 56 | "tree {}\nauthor Test <test@example.invalid> 1700000000 +0000\ncommitter Test <test@example.invalid> 1700000000 +0000\ngpgsig -----BEGIN PGP SIGNATURE-----\n \n iQEzBAABCAAdFiEE\n -----END PGP SIGNATURE-----\n\nsigned commit\n", |
| 57 | tree.trim() |
| 58 | ); |
| 59 | let mut hash_child = std::process::Command::new("git") |
| 60 | .args(["hash-object", "-t", "commit", "-w", "--stdin"]) |
| 61 | .current_dir(&repo) |
| 62 | .stdin(std::process::Stdio::piped()) |
| 63 | .stdout(std::process::Stdio::piped()) |
| 64 | .spawn() |
| 65 | .expect("hash-object"); |
| 66 | std::io::Write::write_all(hash_child.stdin.as_mut().unwrap(), commit_obj.as_bytes()) |
| 67 | .unwrap(); |
| 68 | let output = hash_child.wait_with_output().unwrap(); |
| 69 | assert!(output.status.success()); |
| 70 | let commit_id = String::from_utf8(output.stdout).unwrap(); |
| 71 | git(&["update-ref", "HEAD", commit_id.trim()]); |
| 72 | } |
| 73 | |
| 74 | std::fs::write(repo.join("a.txt"), "hello\nworld\n").unwrap(); |
| 75 | |
| 76 | let rendered = config_snippet |
| 77 | .replace("{{SECRET}}", &secret_path.display().to_string()) |
| 78 | .replace("{{CANARY}}", &canary_path.display().to_string()); |
| 79 | let mut config = std::fs::read_to_string(repo.join(".git/config")).unwrap(); |
| 80 | config.push('\n'); |
| 81 | config.push_str(&rendered); |
| 82 | config.push('\n'); |
| 83 | std::fs::write(repo.join(".git/config"), config).unwrap(); |
| 84 | |
| 85 | Self { |
| 86 | _root: root, |
| 87 | repo, |
| 88 | secret_path, |
| 89 | canary_path, |
| 90 | secret_value, |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | fn write_helper_script(&self) -> std::path::PathBuf { |
| 95 | use std::os::unix::fs::PermissionsExt as _; |
| 96 | let script = self._root.path().join("helper.sh"); |
| 97 | std::fs::write( |
| 98 | &script, |
| 99 | format!( |
| 100 | "#!/bin/sh\necho RAN > {}\ncat {}\nexit 0\n", |
| 101 | shell_words::quote(&self.canary_path.display().to_string()), |
| 102 | shell_words::quote(&self.secret_path.display().to_string()), |
| 103 | ), |
| 104 | ) |
| 105 | .unwrap(); |
| 106 | let mut perms = std::fs::metadata(&script).unwrap().permissions(); |
| 107 | perms.set_mode(0o755); |
| 108 | std::fs::set_permissions(&script, perms).unwrap(); |
| 109 | script |
| 110 | } |
| 111 | |
| 112 | fn assert_inert(&self, output: &str, label: &str) { |
| 113 | assert!( |
| 114 | !output.contains(self.secret_value), |
| 115 | "{label}: repository helper leaked secret into output: {output}" |
| 116 | ); |
| 117 | assert!( |
| 118 | !self.canary_path.exists(), |
| 119 | "{label}: repository helper executed and created canary file" |
| 120 | ); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | #[cfg(unix)] |
| 125 | fn full_interactive_context(repo: &std::path::Path) -> ToolContext { |
| 126 | let mut context = ToolContext::new(repo); |
| 127 | context.auto_approve = false; |
| 128 | context.shell_policy = ShellPolicy::Full; |
| 129 | context |
| 130 | } |
| 131 | |
| 132 | #[cfg(unix)] |
| 133 | fn native_readonly_context(repo: &std::path::Path) -> Option<ToolContext> { |
| 134 | let mut context = ToolContext::new(repo); |
| 135 | context.auto_approve = false; |
| 136 | context.shell_policy = ShellPolicy::Full; |
| 137 | #[cfg(target_os = "linux")] |
| 138 | context.shell_manager.lock().unwrap().set_prefer_bwrap(true); |
| 139 | if !context |
| 140 | .shell_manager |
| 141 | .lock() |
| 142 | .unwrap() |
| 143 | .configured_sandbox_type() |
| 144 | .is_some_and(is_native_readonly_sandbox) |
| 145 | { |
| 146 | return None; |
| 147 | } |
| 148 | Some(context) |
| 149 | } |
| 150 | |
| 151 | #[cfg(unix)] |
| 152 | #[tokio::test] |
| 153 | async fn auto_approved_readonly_git_commands_block_all_repo_config_exec_vectors() { |
| 154 | let diff_driver = RepoFixture::new( |
| 155 | "[diff \"x\"]\n\tcommand = sh -c 'echo RAN > {{CANARY}}; cat {{SECRET}}'", |
| 156 | Some("* diff=x\n"), |
| 157 | false, |
| 158 | ); |
| 159 | let ctx = full_interactive_context(&diff_driver.repo); |
| 160 | for cmd in ["git diff", "git log -n 1", "git show HEAD"] { |
| 161 | let input = json!({"command": cmd}); |
| 162 | assert_eq!( |
| 163 | LowercaseBashTool.approval_requirement_for(&input), |
| 164 | ApprovalRequirement::Auto, |
| 165 | "{cmd}" |
| 166 | ); |
| 167 | let result = LowercaseBashTool |
| 168 | .execute(input, &ctx) |
| 169 | .await |
| 170 | .expect("auto-approved git read succeeds"); |
| 171 | diff_driver.assert_inert(&result.content, cmd); |
| 172 | if cmd == "git diff" { |
| 173 | assert!(result.content.contains("+world"), "{}", result.content); |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | let textconv = RepoFixture::new( |
| 178 | "[diff \"x\"]\n\ttextconv = sh -c 'echo RAN > {{CANARY}}; cat {{SECRET}}'", |
| 179 | Some("* diff=x\n"), |
| 180 | false, |
| 181 | ); |
| 182 | let ctx = full_interactive_context(&textconv.repo); |
| 183 | for cmd in ["git diff", "git blame a.txt"] { |
| 184 | let input = json!({"command": cmd}); |
| 185 | assert_eq!( |
| 186 | LowercaseBashTool.approval_requirement_for(&input), |
| 187 | ApprovalRequirement::Auto, |
| 188 | "{cmd}" |
| 189 | ); |
| 190 | let result = LowercaseBashTool |
| 191 | .execute(input, &ctx) |
| 192 | .await |
| 193 | .expect("textconv-hardened git read succeeds"); |
| 194 | textconv.assert_inert(&result.content, cmd); |
| 195 | } |
| 196 | |
| 197 | let ext_diff = RepoFixture::new( |
| 198 | "[diff]\n\texternal = sh -c 'echo RAN > {{CANARY}}; cat {{SECRET}}'", |
| 199 | None, |
| 200 | false, |
| 201 | ); |
| 202 | let ctx = full_interactive_context(&ext_diff.repo); |
| 203 | let result = LowercaseBashTool |
| 204 | .execute(json!({"command": "git diff"}), &ctx) |
| 205 | .await |
| 206 | .expect("diff.external neutralized"); |
| 207 | ext_diff.assert_inert(&result.content, "diff.external"); |
| 208 | assert!(result.content.contains("+world"), "{}", result.content); |
| 209 | |
| 210 | let fsmonitor = RepoFixture::new( |
| 211 | "[core]\n\tfsmonitor = sh -c 'echo RAN > {{CANARY}}; cat {{SECRET}}'", |
| 212 | None, |
| 213 | false, |
| 214 | ); |
| 215 | let ctx = full_interactive_context(&fsmonitor.repo); |
| 216 | let result = LowercaseBashTool |
| 217 | .execute(json!({"command": "git status"}), &ctx) |
| 218 | .await |
| 219 | .expect("core.fsmonitor neutralized"); |
| 220 | fsmonitor.assert_inert(&result.content, "core.fsmonitor"); |
| 221 | |
| 222 | let filter = RepoFixture::new( |
| 223 | "[filter \"x\"]\n\tprocess = sh -c 'echo RAN > {{CANARY}}; cat {{SECRET}}'\n\tclean = sh -c 'echo RAN > {{CANARY}}; cat {{SECRET}}'", |
| 224 | Some("* filter=x\n"), |
| 225 | false, |
| 226 | ); |
| 227 | let ctx = full_interactive_context(&filter.repo); |
| 228 | for cmd in ["git diff", "git status"] { |
| 229 | let result = LowercaseBashTool |
| 230 | .execute(json!({"command": cmd}), &ctx) |
| 231 | .await |
| 232 | .expect("filter driver neutralized"); |
| 233 | filter.assert_inert(&result.content, cmd); |
| 234 | } |
| 235 | |
| 236 | let gpg = RepoFixture::new("", None, true); |
| 237 | let helper = gpg.write_helper_script(); |
| 238 | let mut cfg = std::fs::read_to_string(gpg.repo.join(".git/config")).unwrap(); |
| 239 | cfg.push_str(&format!( |
| 240 | "\n[gpg]\n\tprogram = {}\n[log]\n\tshowSignature = true\n", |
| 241 | helper.display() |
| 242 | )); |
| 243 | std::fs::write(gpg.repo.join(".git/config"), cfg).unwrap(); |
| 244 | let ctx = full_interactive_context(&gpg.repo); |
| 245 | for cmd in ["git log -n 1", "git show HEAD"] { |
| 246 | let input = json!({"command": cmd}); |
| 247 | assert_eq!( |
| 248 | LowercaseBashTool.approval_requirement_for(&input), |
| 249 | ApprovalRequirement::Auto, |
| 250 | "{cmd}" |
| 251 | ); |
| 252 | let result = LowercaseBashTool |
| 253 | .execute(input, &ctx) |
| 254 | .await |
| 255 | .expect("gpg.program neutralized"); |
| 256 | gpg.assert_inert(&result.content, cmd); |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | #[cfg(unix)] |
| 261 | #[tokio::test] |
| 262 | async fn enforced_readonly_blocks_all_repo_config_exec_vectors() { |
| 263 | let diff_driver = RepoFixture::new( |
| 264 | "[diff \"x\"]\n\tcommand = sh -c 'cat {{SECRET}}'", |
| 265 | Some("* diff=x\n"), |
| 266 | false, |
| 267 | ); |
| 268 | let Some(ctx) = native_readonly_context(&diff_driver.repo) else { |
| 269 | return; |
| 270 | }; |
| 271 | for cmd in [ |
| 272 | "git diff", |
| 273 | "git status && git diff", |
| 274 | "git diff | head -n 20", |
| 275 | "git -C . diff", |
| 276 | ] { |
| 277 | let result = LowercaseBashTool |
| 278 | .execute(json!({"command": cmd, "read_only": true}), &ctx) |
| 279 | .await |
| 280 | .expect("enforced readonly git diff succeeds"); |
| 281 | diff_driver.assert_inert(&result.content, cmd); |
| 282 | assert!( |
| 283 | result.content.contains("+world"), |
| 284 | "{cmd}: {}", |
| 285 | result.content |
| 286 | ); |
| 287 | } |
| 288 | let wrapped = LowercaseBashTool |
| 289 | .execute( |
| 290 | json!({"command": "sh -c 'git diff'", "read_only": true}), |
| 291 | &ctx, |
| 292 | ) |
| 293 | .await; |
| 294 | let wrapped_text = match wrapped { |
| 295 | Ok(res) => res.content, |
| 296 | Err(err) => err.to_string(), |
| 297 | }; |
| 298 | diff_driver.assert_inert(&wrapped_text, "sh -c 'git diff'"); |
| 299 | |
| 300 | let textconv = RepoFixture::new( |
| 301 | "[diff \"x\"]\n\ttextconv = sh -c 'cat {{SECRET}}'", |
| 302 | Some("* diff=x\n"), |
| 303 | false, |
| 304 | ); |
| 305 | let ctx = native_readonly_context(&textconv.repo).unwrap(); |
| 306 | let result = LowercaseBashTool |
| 307 | .execute(json!({"command": "git diff", "read_only": true}), &ctx) |
| 308 | .await |
| 309 | .expect("enforced readonly textconv neutralized"); |
| 310 | textconv.assert_inert(&result.content, "readonly textconv"); |
| 311 | |
| 312 | let ext_diff = RepoFixture::new("[diff]\n\texternal = sh -c 'cat {{SECRET}}'", None, false); |
| 313 | let ctx = native_readonly_context(&ext_diff.repo).unwrap(); |
| 314 | let result = LowercaseBashTool |
| 315 | .execute(json!({"command": "git diff", "read_only": true}), &ctx) |
| 316 | .await |
| 317 | .expect("enforced readonly diff.external neutralized"); |
| 318 | ext_diff.assert_inert(&result.content, "readonly diff.external"); |
| 319 | assert!(result.content.contains("+world"), "{}", result.content); |
| 320 | |
| 321 | let fsmonitor = RepoFixture::new("[core]\n\tfsmonitor = sh -c 'cat {{SECRET}}'", None, false); |
| 322 | let ctx = native_readonly_context(&fsmonitor.repo).unwrap(); |
| 323 | let result = LowercaseBashTool |
| 324 | .execute(json!({"command": "git status", "read_only": true}), &ctx) |
| 325 | .await |
| 326 | .expect("enforced readonly core.fsmonitor neutralized"); |
| 327 | fsmonitor.assert_inert(&result.content, "readonly core.fsmonitor"); |
| 328 | |
| 329 | let filter = RepoFixture::new( |
| 330 | "[filter \"x\"]\n\tprocess = sh -c 'cat {{SECRET}}'", |
| 331 | Some("* filter=x\n"), |
| 332 | false, |
| 333 | ); |
| 334 | let ctx = native_readonly_context(&filter.repo).unwrap(); |
| 335 | let result = LowercaseBashTool |
| 336 | .execute(json!({"command": "git diff", "read_only": true}), &ctx) |
| 337 | .await |
| 338 | .expect("enforced readonly filter.process neutralized"); |
| 339 | filter.assert_inert(&result.content, "readonly filter.process"); |
| 340 | |
| 341 | let gpg = RepoFixture::new("", None, true); |
| 342 | let helper = gpg.write_helper_script(); |
| 343 | let mut cfg = std::fs::read_to_string(gpg.repo.join(".git/config")).unwrap(); |
| 344 | cfg.push_str(&format!( |
| 345 | "\n[gpg]\n\tprogram = {}\n[log]\n\tshowSignature = true\n", |
| 346 | helper.display() |
| 347 | )); |
| 348 | std::fs::write(gpg.repo.join(".git/config"), cfg).unwrap(); |
| 349 | let ctx = native_readonly_context(&gpg.repo).unwrap(); |
| 350 | let result = LowercaseBashTool |
| 351 | .execute(json!({"command": "git log -n 1", "read_only": true}), &ctx) |
| 352 | .await |
| 353 | .expect("enforced readonly gpg.program neutralized"); |
| 354 | gpg.assert_inert(&result.content, "readonly gpg.program"); |
| 355 | } |
| 356 |