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