(* Copyright (c) 2024-2026 Thomas Gazagnaire Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open Ssh_fixture (* {1 Authenticating as OpenSSH does} A fixture HOME holds an ~/.ssh/config, a known_hosts and key files; a fixture agent answers on a Unix socket; the ocaml-git SSH server accepts one key for one user. The key files were made with ssh-keygen: [keys/agent_ed25519] is the agent's key, [keys/locked_ed25519] the same key encrypted with a passphrase, and [keys/other_ed25519] a key the server refuses. *) let key name = match Ssh.Hostkey.privkey_of_openssh (read_file ("keys/" ^ name)) with | Ok (k, _) -> k | Error e -> Alcotest.failf "keys/%s: %s" name e let blob k = Ssh.Hostkey.blob_of_pubkey (Ssh.Hostkey.pub_of_priv k) (* An agent holding [keys] (draft-miller-ssh-agent section 3): it lists them and signs with them, and counts the signatures it makes. *) let fixture_agent ~sw ~net ~path keys signed = let sock = Eio.Net.listen ~sw ~backlog:4 net (`Unix path) in let answer msg = let open Ssh.Core in let c = cursor msg in let typ = read_uint8 c in let body = if typ = 11 then collect (fun buf -> let buf = write_uint8 12 buf in let buf = write_uint32 (Int32.of_int (List.length keys)) buf in List.fold_left (fun buf k -> write_string (blob k) buf |> write_string "fixture") buf keys) else if typ = 13 then ( let kb = read_string c in let data = read_string c in let flags = read_uint32 c in match List.find_opt (fun k -> blob k = kb) keys with | None -> "\005" | Some k -> let alg = match k with | Ssh.Hostkey.Ed25519_priv _ -> Ssh.Hostkey.Ed25519 | Ssh.Hostkey.P256_priv _ -> Ssh.Hostkey.Ecdsa_p256 | Ssh.Hostkey.P384_priv _ -> Ssh.Hostkey.Ecdsa_p384 | Ssh.Hostkey.P521_priv _ -> Ssh.Hostkey.Ecdsa_p521 | Ssh.Hostkey.Rsa_priv _ -> if Int32.logand flags 4l <> 0l then Ssh.Hostkey.Rsa_sha512 else Ssh.Hostkey.Rsa_sha256 in incr signed; let sg = Ssh.Hostkey.sign alg k data in collect (fun buf -> write_uint8 14 buf |> write_string (collect (fun b -> write_string (Ssh.Hostkey.string_of_alg alg) b |> write_string sg)))) else "\005" in collect (fun buf -> write_uint32 (Int32.of_int (String.length body)) buf |> write_raw body) in Eio.Fiber.fork_daemon ~sw (fun () -> let rec loop () = Eio.Switch.run (fun csw -> let flow, _ = Eio.Net.accept ~sw:csw sock in let buf = Buffer.create 256 and chunk = Cstruct.create 4096 in let rec read () = match Ssh.Agent.frame (Buffer.contents buf) with | `Frame (msg, _) -> Eio.Flow.copy_string (answer msg) flow | `Short _ -> ( match Eio.Flow.single_read flow chunk with | n -> Buffer.add_string buf (Cstruct.to_string ~len:n chunk); read () | exception End_of_file -> ()) | `Invalid _ -> () in read ()); loop () in loop ()) let fixture_port = 7475 (* The server's host key, recorded for [127.0.0.1] on the fixture port in a file only UserKnownHostsFile names, after an ecdsa line for the same host. *) let fixture_known_hosts () = Fmt.str "[127.0.0.1]:%d ecdsa-sha2-nistp256 \ AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEmKSENjQEezOmxkZMy7opKgwFB9nkt5YRrYMjNuG5N87uRgg6CLrbo5wAdT/y6v0mKV0U2w0WZ2YB/++Tpockg=\n\ [127.0.0.1]:%d ssh-ed25519 %s\n" fixture_port fixture_port (Base64.encode_string (blob host_key)) let fixture_config ~identity_files ~identities_only = String.concat "\n" ([ "Host fixture-alias"; " HostName 127.0.0.1"; Fmt.str " Port %d" fixture_port; " User fixture-user"; " UserKnownHostsFile ~/.ssh/known_hosts.d/%h"; ] @ List.map (fun f -> " IdentityFile ~/.ssh/" ^ f) identity_files @ (if identities_only then [ " IdentitiesOnly yes" ] else []) @ [ "Host *"; " User wrong-user"; ""; "" ]) let with_env name value f = let saved = Sys.getenv_opt name in Unix.putenv name value; Fun.protect ~finally:(fun () -> Unix.putenv name (Option.value saved ~default:"")) f (* A socket path holds at most 104 bytes on macOS, its NUL included, and 108 on Linux (sun_path). *) let max_socket_path = 103 (* Run [f] with the path of an agent socket in a directory of its own, removed when [f] returns. The directory is made under the working directory when the relative path fits [max_socket_path], so the socket's name stays short wherever the checkout is; otherwise it is made under the temporary directory or /tmp. A check's temporary directory can lie as deep as its build directory, and /tmp is not writable in every sandbox. A path that fits under none is refused by name. The agent and the ssh client both run from the same working directory. *) let with_agent_socket f = let fits dir = String.length Fpath.(to_string (v dir / "gsa000000" / "agent.sock")) <= max_socket_path in let candidates = [ "."; Filename.get_temp_dir_name (); "/tmp" ] in let dir = List.find_map (fun temp_dir -> if not (fits temp_dir) then None else match Filename.temp_dir ~temp_dir "gsa" "" with | dir -> Some dir | exception Sys_error _ -> None) candidates in match dir with | None -> Alcotest.failf "no directory of %s holds a socket path of at most %d bytes" (String.concat " or " candidates) max_socket_path | Some dir -> let sock = Fpath.(to_string (v dir / "agent.sock")) in Fun.protect ~finally:(fun () -> (try Unix.unlink sock with Unix.Unix_error (Unix.ENOENT, _, _) -> ()); Unix.rmdir dir) (fun () -> f sock) (* Run [f] with HOME at a fixture holding [config], the known_hosts and the key files, and SSH_AUTH_SOCK at a fixture agent holding [agent_keys] (unset when [None]). [f] is given the result of resolving "fixture-alias" and of a fetch over it from an ocaml-git server that accepts [keys/agent_ed25519] for [fixture-user] alone, and the agent's signature count. *) let with_openssh_fixture ?known_hosts ~config ~agent_keys f = let home = Filename.temp_dir "git-ssh-openssh" "" in let ssh = Filename.concat home ".ssh" in Unix.mkdir ssh 0o700; Unix.mkdir (Filename.concat ssh "known_hosts.d") 0o700; let write rel content = Out_channel.with_open_bin (Filename.concat ssh rel) (fun oc -> output_string oc content) in write "config" config; write "known_hosts.d/127.0.0.1" (Option.value known_hosts ~default:(fixture_known_hosts ())); List.iter (fun k -> write k (read_file ("keys/" ^ k))) [ "agent_ed25519"; "locked_ed25519"; "other_ed25519" ]; with_agent_socket @@ fun sock -> let signed = ref 0 in let accepted = blob (key "agent_ed25519") in with_env "HOME" home @@ fun () -> with_env "SSH_AUTH_SOCK" (if agent_keys = None then "" else sock) @@ fun () -> Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let real_net = Eio.Stdenv.net env in Option.iter (fun keys -> fixture_agent ~sw ~net:real_net ~path:sock keys signed) agent_keys; let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in let srepo = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gso" "")) in let blob_h = Git_eio.Repository.write_blob srepo "openssh fixture\n" in let tree = Git_eio.Repository.write_tree srepo (Git.Tree.v [ Git.Tree.entry ~perm:`Normal ~name:"F" blob_h ]) in let a = Git.User.v ~name:"n" ~email:"n@e" ~date:0L () in let chash = Git_eio.Repository.write_commit srepo (Git.Commit.v ~tree ~author:a ~committer:a (Some "c\n")) in Git_eio.Repository.write_ref srepo "refs/heads/main" chash; let authenticate user = function | Ssh.Server.Pubkey p -> user = "fixture-user" && p.Ssh.Server.pubkey |> Ssh.Hostkey.blob_of_pubkey = accepted && (Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user p) | Ssh.Server.Authnone -> false | Ssh.Server.Password _ -> false in let dst = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gsod" "")) in let resolved = Git_ssh.resolve ~fs ~net:real_net ~host:"fixture-alias" () in let result = ref (Error (`Msg "client did not run")) in let ready, announce = Eio.Promise.create () in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Git_ssh.serve ~max_connections:64 ~sw:ssw ~on_listen:(Eio.Promise.resolve announce) ~net ~mono ~host_key ~authenticate ~addr:(`Tcp (Eio.Net.Ipaddr.V4.loopback, fixture_port)) srepo) (fun () -> let (_ : int) = Test_helpers.announced_port ~clock ready in result := match resolved with | Error ((`Msg _ | `Auth _) as e) -> Error e | Ok (t : Git_ssh.target) -> Git_ssh.fetch ~authenticator:t.authenticator ~sw ~net ~mono ~port:t.port ~user:t.user t.credential ~host:t.host ~dst ~ref_name:"main" "/srv"); f ~resolved ~fetched:!result ~signed:!signed ~commit:chash (* A server that runs the command and sends nothing on its channel, while it answers every keepalive: the keepalives keep the session, and the channel's progress bound ends it, at two windows an order of magnitude apart, with the host, the port and curl's words. *) let test_hung_command () = List.iter (fun n -> Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let authenticate _ = function | Ssh.Server.Pubkey p -> Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user:"git" p | Ssh.Server.Authnone -> false | Ssh.Server.Password _ -> false in let sock = Eio.Net.listen ~sw ~backlog:1 ~reuse_addr:true net (`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) in let port = match Eio.Net.listening_addr sock with | `Tcp (_, port) -> port | `Unix _ -> Alcotest.fail "a TCP listener has a TCP address" in let window = Mtime.Span.(n * ms) in let alive = { Ssh_eio.Client.interval = Mtime.Span.(n / 8 * ms); count_max = 3 } in let result = Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Eio.Net.accept_fork ~sw:ssw sock ~on_error:raise (fun flow _ -> Ssh_eio.Server.serve ~mono flow ~host_key ~authenticate ~on_event:(fun _ _ -> ())); Eio.Fiber.await_cancel ()) (fun () -> let stall = Eio_net.Progress.v ~mono ~limit:1 ~window in Git_ssh.ls_refs ~alive ~stall ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" "/hung.git") in match result with | Ok _ -> Alcotest.fail "a hung command advertised refs" | Error e -> Alcotest.(check string) (Fmt.str "at %dms" n) (Fmt.str "ssh: connection to 127.0.0.1 port %d: Operation too slow. Less \ than 1 bytes/sec transferred the last %g seconds" port (float_of_int n /. 1000.)) (Fmt.str "%a" Git_ssh.pp_error e)) [ 200; 2000 ] (* ServerAliveInterval, ServerAliveCountMax and ConnectTimeout reach the target as ~/.ssh/config writes them. *) let test_openssh_alive () = let config = fixture_config ~identity_files:[ "agent_ed25519" ] ~identities_only:true in let config = "Host fixture-alias\n\ \ ServerAliveInterval 1m\n\ \ ServerAliveCountMax 5\n\ \ ConnectTimeout 7\n" ^ config in with_openssh_fixture ~config ~agent_keys:(Some [ key "agent_ed25519" ]) @@ fun ~resolved ~fetched:_ ~signed:_ ~commit:_ -> match resolved with | Error (`Msg m) -> Alcotest.failf "resolve: %s" m | Error (`Auth e) -> Alcotest.failf "resolve: %a" Git_ssh.pp_auth_error e | Ok t -> let span = Alcotest.(option (testable Mtime.Span.pp Mtime.Span.equal)) in Alcotest.(check span) "ServerAliveInterval" (Some Mtime.Span.(60 * s)) t.server_alive_interval; Alcotest.(check (option int)) "ServerAliveCountMax" (Some 5) t.server_alive_count_max; Alcotest.(check span) "ConnectTimeout" (Some Mtime.Span.(7 * s)) t.connect_timeout let fetched_ok ~fetched ~commit = match fetched with | Error e -> Alcotest.failf "fetch: %a" Git_ssh.pp_error e | Ok h -> Alcotest.(check bool) "fetched the commit" true (Git.Hash.equal h commit) (* An encrypted IdentityFile whose key the agent holds is signed by the agent; HostName, Port, User and UserKnownHostsFile come from ~/.ssh/config. *) let test_openssh_agent () = with_openssh_fixture ~config: (fixture_config ~identity_files:[ "locked_ed25519" ] ~identities_only:true) ~agent_keys:(Some [ key "agent_ed25519" ]) @@ fun ~resolved ~fetched ~signed ~commit -> (match resolved with | Error (`Msg m) -> Alcotest.failf "resolve: %s" m | Error (`Auth e) -> Alcotest.failf "resolve: %a" Git_ssh.pp_auth_error e | Ok t -> Alcotest.(check string) "HostName" "127.0.0.1" t.host; Alcotest.(check int) "Port" fixture_port t.port; Alcotest.(check string) "User, first value wins" "fixture-user" t.user); fetched_ok ~fetched ~commit; Alcotest.(check int) "the agent signed once" 1 signed (* The server refuses the first identity; the agent's key, offered next, authenticates. *) let test_openssh_next_identity () = with_openssh_fixture ~config: (fixture_config ~identity_files:[ "other_ed25519" ] ~identities_only:false) ~agent_keys:(Some [ key "agent_ed25519" ]) @@ fun ~resolved:_ ~fetched ~signed ~commit -> fetched_ok ~fetched ~commit; Alcotest.(check int) "the agent signed once" 1 signed (* [m], the refusal's sentence, holds each [(what, sub)] of [subs]. *) let names m subs = List.iter (fun (what, sub) -> Alcotest.(check bool) (what ^ ": " ^ m) true (contains ~sub m)) subs (* The authentication [fetched] ended in, as [Denied], or a failure. *) let denied fetched = match fetched with | Ok _ -> Alcotest.fail "the server accepts none of the keys offered" | Error (`Host_key e) -> Alcotest.failf "%a" Git_ssh.pp_host_key_error e | Error (`Msg m) -> Alcotest.failf "denied, untyped: %s" m | Error (`Auth (Git_ssh.No_identity _ as e)) -> Alcotest.failf "a key was offered: %a" Git_ssh.pp_auth_error e | Error (`Auth (Git_ssh.Denied { user; host; offered; why } as e)) -> (user, host, offered, why, Fmt.str "%a" Git_ssh.pp_auth_error e) (* With no agent, the encrypted file is refused naming itself, as the user writes it, and the fix: the caller's authentication, not the transport. *) let test_openssh_locked_without_agent () = with_openssh_fixture ~config: (fixture_config ~identity_files:[ "locked_ed25519" ] ~identities_only:true) ~agent_keys:None @@ fun ~resolved:_ ~fetched ~signed:_ ~commit:_ -> let _, _, offered, why, _ = denied fetched in Alcotest.(check (list string)) "the key offered" [ "~/.ssh/locked_ed25519" ] offered; Alcotest.(check bool) ("names the file and ssh-add: " ^ why) true (contains ~sub:"`ssh-add ~/.ssh/locked_ed25519`" why) (* RFC 4252 sec 7: a server that accepts none of the keys offered ends the authentication, as OpenSSH's "Permission denied (publickey)": [Denied], naming the user, the host and the keys offered, and the sentence names how to give ssh another key. *) let test_openssh_denied () = with_openssh_fixture ~config: (fixture_config ~identity_files:[ "other_ed25519" ] ~identities_only:true) ~agent_keys:None @@ fun ~resolved:_ ~fetched ~signed:_ ~commit:_ -> let user, host, offered, why, m = denied fetched in Alcotest.(check string) "the user" "fixture-user" user; Alcotest.(check string) "the host" "127.0.0.1" host; Alcotest.(check (list string)) "the key offered" [ "~/.ssh/other_ed25519" ] offered; Alcotest.(check string) "the client's reason" "no identity was accepted" why; Alcotest.(check string) "the sentence" "ssh: fixture-user@127.0.0.1: permission denied for ~/.ssh/other_ed25519 \ (no identity was accepted); add the key the server knows with ssh-add" m (* No agent key and no IdentityFile this client can use: resolving refuses before any connection, as [No_identity], naming the files read as the user writes them, and the sentence names how to give ssh a key: ssh-add, or, since IdentitiesOnly keeps the agent's other keys out, an IdentityFile. *) let no_identity ~identities_only ~cure = with_openssh_fixture ~config:(fixture_config ~identity_files:[ "absent" ] ~identities_only) ~agent_keys:None @@ fun ~resolved ~fetched:_ ~signed:_ ~commit:_ -> match resolved with | Ok _ -> Alcotest.fail "no identity is left to authenticate with" | Error (`Msg m) -> Alcotest.failf "no identity, untyped: %s" m | Error (`Auth (Git_ssh.Denied _ as e)) -> Alcotest.failf "nothing was offered: %a" Git_ssh.pp_auth_error e | Error (`Auth (Git_ssh.No_identity { files; identities_only = only } as e)) -> Alcotest.(check (list string)) "the files read" [ "~/.ssh/absent" ] files; Alcotest.(check bool) "IdentitiesOnly" identities_only only; Alcotest.(check string) "the sentence" cure (Fmt.str "%a" Git_ssh.pp_auth_error e) let test_openssh_no_identity () = no_identity ~identities_only:false ~cure: "ssh: no usable key in ssh-agent or at ~/.ssh/absent; add one with \ ssh-add"; no_identity ~identities_only:true ~cure: "ssh: no usable key at ~/.ssh/absent (IdentitiesOnly is set); name your \ key with IdentityFile in ~/.ssh/config" (* OpenSSH's fingerprint of a key: SHA256: and the unpadded base64 of the SHA-256 of its blob. *) let fingerprint k = "SHA256:" ^ Base64.encode_string ~pad:false Hash.SHA256.(to_raw_string (digest_string (blob k))) let host_line () = Fmt.str "[127.0.0.1]:%d ssh-ed25519 %s" fixture_port (Base64.encode_string (blob host_key)) let same_key what want got = Alcotest.(check string) what (blob want) (Ssh.Hostkey.blob_of_pubkey got) (* ssh_config(5), StrictHostKeyChecking yes: a host known_hosts does not name is refused before anything is sent, as [Unknown_host]. The refusal names the host, the key type and the fingerprint the server offered, and the line that would trust it. *) let test_openssh_unknown_host () = with_openssh_fixture ~known_hosts:"" ~config: (fixture_config ~identity_files:[ "agent_ed25519" ] ~identities_only:true) ~agent_keys:None @@ fun ~resolved:_ ~fetched ~signed:_ ~commit:_ -> match fetched with | Ok _ -> Alcotest.fail "an unknown host is refused" | Error (`Msg m) -> Alcotest.failf "refused, untyped: %s" m | Error (`Auth e) -> Alcotest.failf "%a" Git_ssh.pp_auth_error e | Error (`Host_key (Git_ssh.Changed_key _ as e)) -> Alcotest.failf "an unknown host, not a changed key: %a" Git_ssh.pp_host_key_error e | Error (`Host_key (Git_ssh.Unknown_host { host; offered } as e)) -> let host_name = Fmt.str "[127.0.0.1]:%d" fixture_port in Alcotest.(check string) "the host" host_name host; same_key "the offered key" host_key offered; names (Fmt.str "%a" Git_ssh.pp_host_key_error e) [ ("the host", host_name); ("the key type", "ssh-ed25519"); ("the fingerprint", fingerprint host_key); ("the line to add", host_line ()); ] (* A host whose recorded key is not the one it offers is refused as [Changed_key], naming both fingerprints: OpenSSH's "REMOTE HOST IDENTIFICATION HAS CHANGED". *) let test_openssh_changed_key () = let recorded = key "other_ed25519" in with_openssh_fixture ~known_hosts: (Fmt.str "[127.0.0.1]:%d ssh-ed25519 %s\n" fixture_port (Base64.encode_string (blob recorded))) ~config: (fixture_config ~identity_files:[ "agent_ed25519" ] ~identities_only:true) ~agent_keys:None @@ fun ~resolved:_ ~fetched ~signed:_ ~commit:_ -> match fetched with | Ok _ -> Alcotest.fail "a changed host key is refused" | Error (`Msg m) -> Alcotest.failf "refused, untyped: %s" m | Error (`Auth e) -> Alcotest.failf "%a" Git_ssh.pp_auth_error e | Error (`Host_key (Git_ssh.Unknown_host _ as e)) -> Alcotest.failf "a changed key, not an unknown host: %a" Git_ssh.pp_host_key_error e | Error (`Host_key (Git_ssh.Changed_key { host; offered; recorded = r } as e)) -> let host_name = Fmt.str "[127.0.0.1]:%d" fixture_port in Alcotest.(check string) "the host" host_name host; same_key "the offered key" host_key offered; Alcotest.(check (list string)) "the recorded keys" [ blob recorded ] (List.map Ssh.Hostkey.blob_of_pubkey r); names (Fmt.str "%a" Git_ssh.pp_host_key_error e) [ ("the host", host_name); ("that it changed", "has changed"); ("the offered fingerprint", fingerprint host_key); ("the recorded fingerprint", fingerprint recorded); ] let suite = ( "git_ssh_auth", [ Alcotest.test_case "openssh: agent signs an encrypted IdentityFile" `Quick test_openssh_agent; Alcotest.test_case "openssh: the next identity after a refusal" `Quick test_openssh_next_identity; Alcotest.test_case "openssh: encrypted key without an agent is named" `Quick test_openssh_locked_without_agent; Alcotest.test_case "openssh: a key the server does not know is denied" `Quick test_openssh_denied; Alcotest.test_case "openssh: no identity is refused before connecting" `Quick test_openssh_no_identity; Alcotest.test_case "openssh: an unknown host is refused, naming its key" `Quick test_openssh_unknown_host; Alcotest.test_case "openssh: a changed host key names both fingerprints" `Quick test_openssh_changed_key; Alcotest.test_case "a hung command ends at the channel's progress bound" `Quick test_hung_command; Alcotest.test_case "openssh: ServerAlive* and ConnectTimeout" `Quick test_openssh_alive; ] )