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