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