╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
383 writer.interface.flush() catch {}; 384 try sess.exit(0); 385 return; 386 } 387 388 const create_if_missing = parsed.service == .receive_pack; 389 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 390 391 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 392 switch (try authorizeRepoKey(io, allocator, handler.admin_repo_path, owner_repo.owner, owner_repo.name, parsed.service, &sess.fingerprint)) { 393 .allowed => {}, 394 .denied => return switch (parsed.service) { 395 .upload_pack => writeError(sess, "unauthorized: this SSH key cannot read this repo"), 396 .receive_pack => writeError(sess, "unauthorized: this SSH key cannot push to this repo"), 397 }, 398 .not_found => return writeError(sess, "repo not found"), 399 } 400 401 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, repo_identity, create_if_missing)) { 402 .ok => |p| p, 403 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 404 .not_found => return writeError(sess, "repo not found"), 405 }; 406 defer allocator.free(repo_path); 407 408 if (try serveIfExists(repo_path, handler.repo_root_path, sess, io, allocator, parsed.service, handler.err)) { 409 try sess.exit(0); 410 return; 411 } 412 413 if (!create_if_missing) return writeError(sess, "repo not found"); 414 415 // create the on-disk repo for the just-minted event and serve the push 416 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 417 defer repo.deinit(io, allocator); 418 try servePack(repo.self_repo_opts, &repo, handler.repo_root_path, sess, io, allocator, parsed.service, handler.err); 419 try sess.exit(0); 420 } 421 422 // serve an existing repo at `repo_path`, or return false if none is there 423 fn serveIfExists( 424 repo_path: []const u8, 425 repo_root_path: []const u8, 426 sess: *ssh.SessionCtx, 427 io: std.Io, 428 allocator: std.mem.Allocator, 429 service: GitService, 430 error_writer: *std.Io.Writer, 431 ) !bool { 432 // a bare open() creates the directory while probing for the repo, so only 433 // attempt it when the path already exists 434 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 435 436 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 437 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 438 error.RepoNotFound => return false, 439 else => |e| return e, 440 }; 441 defer any_repo.deinit(io, allocator); 442 443 switch (any_repo) { 444 inline else => |*repo| try servePack(repo.self_repo_opts, repo, repo_root_path, sess, io, allocator, service, error_writer), 445 } 446 return true; 447 } 448 449 fn createRepo( 450 comptime repo_opts: rp.RepoOpts(.xit), 451 io: std.Io, 452 allocator: std.mem.Allocator, 453 repo_path: []const u8, 454 ) !rp.Repo(.xit, repo_opts) { 455 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path }); 456 errdefer repo.deinit(io, allocator); 457 try repo.setMergeAlgorithm(io, allocator, .diff3); 458 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 459 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 460 return repo; 461 } 462 463 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 464 // functions can consume them like any other stream, then run the requested 465 // service 466 fn servePack( 467 comptime repo_opts: rp.RepoOpts(.xit), 468 repo: *rp.Repo(.xit, repo_opts), 469 repo_root_path: []const u8, 470 sess: *ssh.SessionCtx, 471 io: std.Io, 472 allocator: std.mem.Allocator, 473 service: GitService, 474 error_writer: *std.Io.Writer, 475 ) !void { 476 var session_reader_buf: [4096]u8 = undefined; 477 var session_writer_buf: [4096]u8 = undefined; 478 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 479 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 480 481 switch (service) { 482 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 483 .receive_pack => try evt.receivePackAndConsume(repo_opts, io, allocator, repo, &session_reader.interface, &session_writer.interface, .{}, repo_root_path, error_writer), 484 } 485 486 // flush whatever the pack op buffered into our writer adapter 487 session_writer.interface.flush() catch {}; 488 } 489 490 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 491 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 492 defer tokens.deinit(); 493 494 const service_token = tokens.next() orelse return error.InvalidCommand; 495 const dir_token = tokens.next() orelse return error.InvalidCommand; 496 497 const service: GitService = 498 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 499 .upload_pack 500 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 501 .receive_pack 502 else 503 return error.UnsupportedService; 504 505 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 506 } 507 508 const RepoAuthorization = enum { allowed, denied, not_found }; 509 510 fn authorizeRepoKey( 511 io: std.Io, 512 allocator: std.mem.Allocator, 513 admin_repo_path: []const u8, 514 owner_name: []const u8, 515 repo_name: []const u8, 516 service: GitService, 517 fingerprint: *const [ssh.fingerprint_len]u8, 518 ) !RepoAuthorization { 519 var arena = std.heap.ArenaAllocator.init(allocator); 520 defer arena.deinit(); 521 522 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 523 error.RepoNotFound => return .not_found, 524 else => |e| return e, 525 }; 526 defer admin.deinit(io, allocator); 527 528 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 529 const repo = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) orelse { 530 if (service == .upload_pack) return .not_found; 531 const owner = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return .not_found; 532 return if (isKeyInAuthorizedKeys(owner.event.ssh_keys, fingerprint)) .allowed else .denied; 533 }; 534 535 if ((service == .upload_pack and repo.repo.event.read_access == .public) or 536 (service == .receive_pack and repo.repo.event.write_access == .public)) return .allowed; 537 if (try keyBelongsToUser(moment, &arena, repo.repo.event.user_id, fingerprint)) return .allowed; 538 539 const user_id_lists: []const []const u8 = switch (service) { 540 .upload_pack => &.{ repo.repo.event.write_user_ids, repo.repo.event.read_user_ids }, 541 .receive_pack => &.{repo.repo.event.write_user_ids}, 542 }; 543 for (user_id_lists) |user_ids| { 544 var lines = std.mem.tokenizeScalar(u8, user_ids, '\n'); 545 while (lines.next()) |id| { 546 const user_id = try evt.parseEventId(id); 547 if (try keyBelongsToUser(moment, &arena, &user_id, fingerprint)) return .allowed; 548 } 549 } 550 return .denied; 551 } 552 553 fn keyBelongsToUser( 554 moment: evt.AdminDB.HashMap(.read_only), 555 arena: *std.heap.ArenaAllocator, 556 user_id: []const u8, 557 fingerprint: *const [ssh.fingerprint_len]u8, 558 ) !bool { 559 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse return false; 560 return !user.removed and isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint); 561 } 562 563 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 564 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 565 while (it.next()) |line| { 566 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 567 if (std.mem.eql(u8, &fp, fingerprint)) return true; 568 } 569 return false; 570 } 571 572 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 573 // blank or not a parseable "<type> <base64> [comment]" entry 574 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 575 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 576 _ = it.next() orelse return null; // key type 577 const blob_b64 = it.next() orelse return null; 578 579 const decoder = std.base64.standard.Decoder; 580 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 581 var blob_buf: [4096]u8 = undefined; 582 if (blob_len > blob_buf.len) return null; 583 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 584 585 return ssh.formatFingerprint(blob_buf[0..blob_len]); 586 } 587 588 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 589 const body = "ERR haxy ssh: " ++ msg; 590 var packet: [body.len + 4]u8 = undefined; 591 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 592 try sess.writeBytes(line); 593 try sess.exit(1); 594 } 595 596 test "parseGitCommand rejects malformed input" { 597 const allocator = std.testing.allocator; 598 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 599 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 600 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 601 } 602 603 test "parseGitCommand happy paths" { 604 const allocator = std.testing.allocator; 605 606 { 607 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 608 defer parsed.deinit(allocator); 609 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 610 try std.testing.expectEqualStrings("some-repo", parsed.dir); 611 } 612 { 613 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 614 defer parsed.deinit(allocator); 615 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 616 try std.testing.expectEqualStrings("user/proj", parsed.dir); 617 } 618 { 619 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 620 defer parsed.deinit(allocator); 621 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 622 try std.testing.expectEqualStrings("repo", parsed.dir); 623 } 624 } 625