╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
288 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 289 const allocator = sess.conn.allocator; 290 const io = sess.conn.io; 291 292 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 293 defer parsed.deinit(allocator); 294 295 const create_if_missing = parsed.service == .receive_pack; 296 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 297 298 // authenticate pushes: the authenticated key must be registered to the 299 // repo's owner. 300 if (create_if_missing) { 301 const owner_repo = evt.parseOwnerRepoPath(parsed.dir) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 302 if (!try isKeyAuthorized(io, allocator, handler.admin_repo_path, owner_repo.owner, &sess.fingerprint)) 303 return writeError(sess, "unauthorized: this SSH key is not registered to the repo owner"); 304 } 305 306 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, parsed.dir, create_if_missing)) { 307 .ok => |p| p, 308 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 309 .not_found => return writeError(sess, "repo not found"), 310 }; 311 defer allocator.free(repo_path); 312 313 if (try serveIfExists(repo_path, sess, io, allocator, parsed.service)) { 314 try sess.exit(0); 315 return; 316 } 317 318 if (!create_if_missing) return writeError(sess, "repo not found"); 319 320 // create the on-disk repo for the just-minted event and serve the push 321 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 322 defer repo.deinit(io, allocator); 323 try servePack(repo.self_repo_opts, &repo, sess, io, allocator, parsed.service); 324 try sess.exit(0); 325 } 326 327 // serve an existing repo at `repo_path`, or return false if none is there 328 fn serveIfExists( 329 repo_path: []const u8, 330 sess: *ssh.SessionCtx, 331 io: std.Io, 332 allocator: std.mem.Allocator, 333 service: GitService, 334 ) !bool { 335 // a bare open() creates the directory while probing for the repo, so only 336 // attempt it when the path already exists 337 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 338 339 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 340 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 341 error.RepoNotFound => return false, 342 else => |e| return e, 343 }; 344 defer any_repo.deinit(io, allocator); 345 346 switch (any_repo) { 347 inline else => |*repo| try servePack(repo.self_repo_opts, repo, sess, io, allocator, service), 348 } 349 return true; 350 } 351 352 fn createRepo( 353 comptime repo_opts: rp.RepoOpts(.xit), 354 io: std.Io, 355 allocator: std.mem.Allocator, 356 repo_path: []const u8, 357 ) !rp.Repo(.xit, repo_opts) { 358 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path }); 359 errdefer repo.deinit(io, allocator); 360 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 361 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 362 return repo; 363 } 364 365 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 366 // functions can consume them like any other stream, then run the requested 367 // service 368 fn servePack( 369 comptime repo_opts: rp.RepoOpts(.xit), 370 repo: *rp.Repo(.xit, repo_opts), 371 sess: *ssh.SessionCtx, 372 io: std.Io, 373 allocator: std.mem.Allocator, 374 service: GitService, 375 ) !void { 376 var session_reader_buf: [4096]u8 = undefined; 377 var session_writer_buf: [4096]u8 = undefined; 378 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 379 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 380 381 switch (service) { 382 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 383 .receive_pack => try evt.receivePackAndConsume(repo_opts, io, allocator, repo, &session_reader.interface, &session_writer.interface, .{}), 384 } 385 386 // flush whatever the pack op buffered into our writer adapter 387 session_writer.interface.flush() catch {}; 388 } 389 390 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 391 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 392 defer tokens.deinit(); 393 394 const service_token = tokens.next() orelse return error.InvalidCommand; 395 const dir_token = tokens.next() orelse return error.InvalidCommand; 396 397 const service: GitService = 398 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 399 .upload_pack 400 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 401 .receive_pack 402 else 403 return error.UnsupportedService; 404 405 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 406 } 407 408 // true if `fingerprint` matches one of the named user's registered SSH keys 409 fn isKeyAuthorized( 410 io: std.Io, 411 allocator: std.mem.Allocator, 412 admin_repo_path: []const u8, 413 owner_name: []const u8, 414 fingerprint: *const [ssh.fingerprint_len]u8, 415 ) !bool { 416 var arena = std.heap.ArenaAllocator.init(allocator); 417 defer arena.deinit(); 418 419 const user = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return false; 420 421 var it = std.mem.splitScalar(u8, user.event.ssh_keys, '\n'); 422 while (it.next()) |line| { 423 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 424 if (std.mem.eql(u8, &fp, fingerprint)) return true; 425 } 426 return false; 427 } 428 429 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 430 // blank or not a parseable "<type> <base64> [comment]" entry 431 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 432 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 433 _ = it.next() orelse return null; // key type 434 const blob_b64 = it.next() orelse return null; 435 436 const decoder = std.base64.standard.Decoder; 437 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 438 var blob_buf: [4096]u8 = undefined; 439 if (blob_len > blob_buf.len) return null; 440 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 441 442 return ssh.formatFingerprint(blob_buf[0..blob_len]); 443 } 444 445 // write an error to the client's stderr and exit non-zero. stderr (not stdout) 446 // because the git exec sessions that call this carry the pack protocol on 447 // stdout, where stray text breaks the client's pkt-line parser. 448 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 449 try sess.writeStderr("haxy ssh: " ++ msg ++ "\n"); 450 try sess.exit(1); 451 } 452 453 test "parseGitCommand rejects malformed input" { 454 const allocator = std.testing.allocator; 455 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 456 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 457 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 458 } 459 460 test "parseGitCommand happy paths" { 461 const allocator = std.testing.allocator; 462 463 { 464 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 465 defer parsed.deinit(allocator); 466 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 467 try std.testing.expectEqualStrings("some-repo", parsed.dir); 468 } 469 { 470 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 471 defer parsed.deinit(allocator); 472 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 473 try std.testing.expectEqualStrings("user/proj", parsed.dir); 474 } 475 { 476 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 477 defer parsed.deinit(allocator); 478 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 479 try std.testing.expectEqualStrings("repo", parsed.dir); 480 } 481 } 482