From a827e1e4c2661d63e80ad4c697c64c6c89dbcd82 Mon Sep 17 00:00:00 2001 From: Matthew John Cheetham Date: Tue, 24 Nov 2026 10:15:44 +0000 Subject: [PATCH 1/3] urlmatch: expose host glob matching The '*' glob matching of host names used by the http..* family of configuration is buried inside match_urls(), and requires both sides to be wrapped up in a fully normalized url_info. An upcoming safe.host setting wants to match host names using the same rules, so that '*.example.com' means the same thing there as it does in http..*, but its entries are not URLs and so cannot be fed through url_normalize(). Split the label-wise comparison out into urlmatch_host(), which takes a bare host and pattern, and keep match_host() as a thin wrapper over it. Assisted-by: Claude Opus 5.5 Signed-off-by: Matthew John Cheetham --- urlmatch.c | 18 +++++++++++------- urlmatch.h | 12 ++++++++++++ 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/urlmatch.c b/urlmatch.c index 20bc2d009cd0dd..02d13b75ec6050 100644 --- a/urlmatch.c +++ b/urlmatch.c @@ -77,14 +77,9 @@ static const char *end_of_token(const char *s, int c, size_t n) return next; } -static int match_host(const struct url_info *url_info, - const struct url_info *pattern_info) +int urlmatch_host(const char *url, size_t url_len, + const char *pat, size_t pat_len) { - const char *url = url_info->url + url_info->host_off; - const char *pat = pattern_info->url + pattern_info->host_off; - int url_len = url_info->host_len; - int pat_len = pattern_info->host_len; - while (url_len && pat_len) { const char *url_next = end_of_token(url, '.', url_len); const char *pat_next = end_of_token(pat, '.', pat_len); @@ -112,6 +107,15 @@ static int match_host(const struct url_info *url_info, return (!url_len && !pat_len); } +static int match_host(const struct url_info *url_info, + const struct url_info *pattern_info) +{ + return urlmatch_host(url_info->url + url_info->host_off, + url_info->host_len, + pattern_info->url + pattern_info->host_off, + pattern_info->host_len); +} + static char *url_normalize_1(const char *url, struct url_info *out_info, bool allow_globs) { /* diff --git a/urlmatch.h b/urlmatch.h index db1a335e728ea3..d6c663a24534ca 100644 --- a/urlmatch.h +++ b/urlmatch.h @@ -49,6 +49,18 @@ char *url_parse(const char *, struct url_info *); */ char *url_normalize_pattern(const char *url, struct url_info *out_info); +/* + * Match the host name "url" (of length "url_len") against the host + * pattern "pat" (of length "pat_len"), neither of which need be NUL + * terminated. A dot-separated component of "pat" consisting solely of + * '*' matches exactly one component of "url"; all other components + * must match exactly (callers are expected to have normalized case). + * + * Returns 1 on a match and 0 otherwise. + */ +int urlmatch_host(const char *url, size_t url_len, + const char *pat, size_t pat_len); + struct urlmatch_item { size_t hostmatch_len; size_t pathmatch_len; From 015cac297c744624dba4f7a29f2455c834d6b862 Mon Sep 17 00:00:00 2001 From: Matthew John Cheetham Date: Tue, 24 Nov 2026 10:19:35 +0000 Subject: [PATCH 2/3] transport: add safe.host to restrict remote hosts There is no way to limit which remote hosts Git will talk to. protocol.allow can restrict *how* Git connects, but once a protocol such as ssh is allowed, a remote URL, whether typed by the user, recorded in .gitmodules or produced by url..insteadOf, can point Git at any host. Environments that want to make sure source code only travels to and from known hosting services, e.g. an organisation's GitHub or Azure DevOps instance, have to resort to network-level controls. Introduce a multi-valued safe.host setting, modelled on safe.directory, that lists the hosts Git may connect to. When it is unset every host is allowed, preserving today's behaviour. Like the other safe.* settings it is only read from protected configuration, so that a repository cannot widen (or narrow) the list for itself. Entries take the form "[://][:]". The scheme and port are optional and match anything when omitted, so that trusting a host is simply a matter of naming it, while "https://example.com" or "on-prem-tfs:8080" can be used to be more specific. Requiring a scheme would make the common case more verbose, and would leave scp-like ssh URLs, which have no scheme, awkward to describe. Treating a missing port as "the scheme's default port" was considered too, but the trust being expressed is in the host, and users are unlikely to expect "example.com" to reject ssh://example.com:2222. Host names accept the same single-component '*' wildcard as http..*, plus a bare '*' to match any host so that e.g. "https://*" can require HTTPS without naming hosts. Enforce the setting for the git and ssh transports in git_connect(), where the host and port have already been parsed out of the URL, just before connecting. HTTP is left to a following commit, as curl may be redirected to other hosts behind our back. Other remote helpers are not covered, since Git cannot know where they connect; protocol.allow remains the tool for those. Assisted-by: Claude Opus 5.5 Signed-off-by: Matthew John Cheetham --- Documentation/config/safe.adoc | 52 ++++++++ connect.c | 35 +++++ t/meson.build | 1 + t/t5816-safe-host.sh | 218 +++++++++++++++++++++++++++++++ transport.c | 227 +++++++++++++++++++++++++++++++++ transport.h | 32 +++++ 6 files changed, 565 insertions(+) create mode 100755 t/t5816-safe-host.sh diff --git a/Documentation/config/safe.adoc b/Documentation/config/safe.adoc index 99fbfc06188c52..42d6bd6d1d3c53 100644 --- a/Documentation/config/safe.adoc +++ b/Documentation/config/safe.adoc @@ -68,3 +68,55 @@ which id the original user has. If that is not what you would prefer and want git to only trust repositories that are owned by root instead, then you can remove the `SUDO_UID` variable from root's environment before invoking git. + +safe.host:: + These config entries specify the remote hosts that Git is allowed + to connect to, e.g. when cloning, fetching or pushing. If + `safe.host` is not set, Git connects to any host. Once it is set, + Git refuses to connect to a host that does not match one of the + entries. ++ +Each entry has the form `[://][:]`: ++ +-- +* `` is a host name or IP address, matched case-insensitively. + IPv6 addresses must be enclosed in square brackets, e.g. `[::1]`. + A dot-separated component consisting only of `*` matches exactly one + component of the host name, so `*.example.com` matches + `git.example.com`, but neither `example.com` nor `a.b.example.com`. + A `` of `*` matches any host. +* ``, if given, limits the entry to connections made using + that URL scheme, e.g. `https` or `ssh`. Without it, the entry matches + connections made using any scheme. Remote URLs of the scp-like form + `[@]:` use the `ssh` scheme. +* ``, if given, limits the entry to connections to that port. + Without it, the entry matches connections to any port. If the remote + URL does not specify a port, the default port for its scheme is + assumed, e.g. 443 for `https` or 22 for `ssh`. +-- ++ +For example, `example.com` allows connections to `example.com` using +any scheme and port, `https://example.com` allows only HTTPS +connections to it, `on-prem-tfs:8080` allows connections to +`on-prem-tfs` on port 8080 only, and `https://*` allows HTTPS +connections to any host. Entries with any other form, e.g. containing a +user name or a path, are ignored with a warning. ++ +This is a multi-valued setting, i.e. you can add more than one host via +`git config --add`. To reset the list of safe hosts (e.g. to override +any such hosts specified in the system config), add a `safe.host` +entry with an empty value. If no entries follow it, Git will refuse to +connect to any remote host. Setting `safe.host` to `*` allows +connections to all hosts, as if it had not been set at all. ++ +This config setting is only respected in protected configuration (see +<>). This prevents untrusted repositories from tampering with this +value. ++ +Repositories on the local filesystem, including those accessed via +`file://` URLs, are not subject to this check. Neither are remote +helpers (see linkgit:gitremote-helpers[7]), as Git cannot know which +hosts they connect to; use `protocol.allow` to restrict them instead. +For `ssh`, the host checked is the one named in the remote URL, before +any aliasing performed by the SSH client's own configuration. Proxies, +e.g. those configured via `core.gitProxy`, are not checked. diff --git a/connect.c b/connect.c index 87d2e8bccd365d..5ae37586231630 100644 --- a/connect.c +++ b/connect.c @@ -799,6 +799,28 @@ static char *host_end(char **hoststart, int removebrackets) #define STR_(s) # s #define STR(s) STR_(s) +/* + * Die unless safe.host allows connecting to "userandhost" (which may + * carry a "user@" prefix) on "port" (NULL for the scheme's default). + */ +static void check_host_allowed(const char *scheme, const char *userandhost, + const char *port) +{ + const char *host = strrchr(userandhost, '@'); + + /* + * No host name contains a '/', but OpenSSH parses a destination + * like "ssh://user@host:port" as a URI, port and all, which would + * slip past the port check below. + */ + if (strchr(userandhost, '/') && safe_hosts_restricted()) + die(_("connecting to ssh host '%s' is not allowed by safe.host"), + userandhost); + + transport_check_host_allowed(scheme, host ? host + 1 : userandhost, + port ? strtoul(port, NULL, 10) : 0); +} + static void get_host_and_port(char **host, const char **port) { char *colon, *end; @@ -815,6 +837,17 @@ static void get_host_and_port(char **host, const char **port) } } +static void check_hostandport_allowed(const char *scheme, + const char *hostandport) +{ + char *host = xstrdup(hostandport); + const char *port = NULL; + + get_host_and_port(&host, &port); + check_host_allowed(scheme, host, port); + free(host); +} + static void enable_keepalive(int sockfd) { int ka = 1; @@ -1294,6 +1327,7 @@ static struct child_process *git_connect_git(int fd[2], char *hostandport, target_host = xstrdup(hostandport); transport_check_allowed("git"); + check_hostandport_allowed("git", hostandport); if (strchr(target_host, '\n') || strchr(path, '\n')) die(_("newline is forbidden in git:// hosts and repo paths")); @@ -1531,6 +1565,7 @@ struct child_process *git_connect(int fd[2], const char *url, strbuf_release(&cmd); return NULL; } + check_host_allowed("ssh", ssh_host, port); conn->trace2_child_class = "transport/ssh"; fill_ssh_args(conn, ssh_host, port, version, flags); } else { diff --git a/t/meson.build b/t/meson.build index 3ca7b271040a62..63f9dce4e27f6c 100644 --- a/t/meson.build +++ b/t/meson.build @@ -769,6 +769,7 @@ integration_tests = [ 't5813-proto-disable-ssh.sh', 't5814-proto-disable-ext.sh', 't5815-submodule-protos.sh', + 't5816-safe-host.sh', 't5900-repo-selection.sh', 't6000-rev-list-misc.sh', 't6001-rev-list-graft.sh', diff --git a/t/t5816-safe-host.sh b/t/t5816-safe-host.sh new file mode 100755 index 00000000000000..51a54a54daad4b --- /dev/null +++ b/t/t5816-safe-host.sh @@ -0,0 +1,218 @@ +#!/bin/sh + +test_description='safe.host restricts the remote hosts Git connects to' + +. ./test-lib.sh + +test_expect_success 'setup' ' + test_commit one && + git init --bare repo.git && + git push repo.git HEAD && + + write_script ssh-wrapper <<-\EOF && + echo "$*" >>"$TRASH_DIRECTORY/ssh-log" + # Ignore the host and port; the command is the last argument. + for cmd + do + : + done + cd "$TRASH_DIRECTORY" && + eval "$cmd" + EOF + GIT_SSH="$PWD/ssh-wrapper" && + GIT_SSH_VARIANT=ssh && + export GIT_SSH GIT_SSH_VARIANT TRASH_DIRECTORY +' + +# Usage: check_safe_hosts (allow|deny) [...] +# +# Configure each given entry in the global config, and then check that +# "git ls-remote " is allowed to connect, or is denied before it +# even tries to. +check_safe_hosts () { + expect=$1 && + url=$2 && + shift 2 && + test_when_finished "git config --global --unset-all safe.host || :" && + { git config --global --unset-all safe.host || :; } && + for entry in "$@" + do + git config --global --add safe.host "$entry" || return 1 + done && + rm -f ssh-log && + case "$expect" in + allow) + git ls-remote "$url" >out && + test_grep refs/heads/ out + ;; + deny) + test_must_fail git ls-remote "$url" 2>err && + test_grep "is not allowed by safe.host" err && + test_path_is_missing ssh-log + ;; + esac +} + +test_expect_success 'all hosts are allowed when safe.host is unset' ' + check_safe_hosts allow "ssh://host.example.com$PWD/repo.git" +' + +test_expect_success 'listed host is allowed' ' + check_safe_hosts allow "ssh://host.example.com$PWD/repo.git" \ + other.example.com host.example.com +' + +test_expect_success 'unlisted host is denied' ' + check_safe_hosts deny "ssh://evil.example.com$PWD/repo.git" \ + host.example.com +' + +test_expect_success 'denial names the connection and suggests how to allow it' ' + test_when_finished "git config --global --unset-all safe.host" && + git config --global safe.host host.example.com && + test_must_fail git clone "ssh://evil.example.com$PWD/repo.git" 2>err && + test_grep "connecting to .ssh://evil.example.com. is not allowed by safe.host" err && + test_grep "git config --global --add safe.host ssh://evil.example.com$" err && + test_must_fail git ls-remote "evil.example.com:repo.git" 2>err && + test_grep "git config --global --add safe.host ssh://evil.example.com$" err && + test_must_fail git ls-remote "ssh://evil.example.com:22$PWD/repo.git" 2>err && + test_grep "git config --global --add safe.host ssh://evil.example.com$" err && + test_must_fail git ls-remote "ssh://evil.example.com:2222$PWD/repo.git" 2>err && + test_grep "git config --global --add safe.host ssh://evil.example.com:2222$" err && + test_must_fail git ls-remote "ssh://[::2]$PWD/repo.git" 2>err && + test_grep "git config --global --add safe.host .ssh://\[::2\].$" err +' + +test_expect_success 'denial names the scheme when only other schemes are allowed' ' + test_must_fail git -c safe.host=git://host.example.com \ + ls-remote "ssh://host.example.com$PWD/repo.git" 2>err && + test_grep "connecting to .ssh://host.example.com. is not allowed by safe.host" err +' + +test_expect_success 'hosts are matched case-insensitively' ' + check_safe_hosts allow "ssh://Host.Example.COM$PWD/repo.git" \ + HOST.example.com +' + +test_expect_success 'scp-like syntax is matched as ssh' ' + check_safe_hosts allow "git@host.example.com:repo.git" \ + ssh://host.example.com:22 && + check_safe_hosts deny "git@evil.example.com:repo.git" \ + host.example.com +' + +test_expect_success 'scheme limits the entry to that scheme' ' + check_safe_hosts allow "ssh://host.example.com$PWD/repo.git" \ + ssh://host.example.com && + check_safe_hosts deny "ssh://host.example.com$PWD/repo.git" \ + https://host.example.com && + check_safe_hosts deny "git://host.example.com/repo.git" \ + ssh://host.example.com +' + +test_expect_success 'entry without a port matches any port' ' + check_safe_hosts allow "ssh://host.example.com:2222$PWD/repo.git" \ + host.example.com && + check_safe_hosts allow "[host.example.com:2222]:repo.git" \ + host.example.com +' + +test_expect_success 'entry with a port matches only that port' ' + check_safe_hosts allow "ssh://host.example.com:2222$PWD/repo.git" \ + host.example.com:2222 && + check_safe_hosts allow "[host.example.com:2222]:repo.git" \ + host.example.com:2222 && + check_safe_hosts deny "ssh://host.example.com$PWD/repo.git" \ + host.example.com:2222 && + check_safe_hosts allow "ssh://host.example.com$PWD/repo.git" \ + host.example.com:22 && + check_safe_hosts deny "git://host.example.com:9419/repo.git" \ + host.example.com:9418 +' + +test_expect_success 'wildcard matches exactly one host component' ' + check_safe_hosts allow "ssh://git.example.com$PWD/repo.git" \ + "*.example.com" && + check_safe_hosts deny "ssh://example.com$PWD/repo.git" \ + "*.example.com" && + check_safe_hosts deny "ssh://a.b.example.com$PWD/repo.git" \ + "*.example.com" +' + +test_expect_success 'wildcard host matches any host' ' + check_safe_hosts allow "ssh://host.example.com$PWD/repo.git" \ + "ssh://*" && + check_safe_hosts deny "ssh://host.example.com$PWD/repo.git" \ + "https://*" +' + +test_expect_success 'IPv6 literals must be bracketed' ' + check_safe_hosts allow "ssh://[::1]$PWD/repo.git" "[::1]" && + check_safe_hosts allow "ssh://[::1]:2222$PWD/repo.git" "[::1]:2222" && + check_safe_hosts deny "ssh://[::1]$PWD/repo.git" "[::2]" +' + +test_expect_success 'ssh destinations that look like URIs are denied' ' + check_safe_hosts deny "ssh://ssh://u@[host.example.com:2222]$PWD/repo.git" \ + "*:22" && + check_safe_hosts deny "ssh://[ssh://u@host.example.com:2222]$PWD/repo.git" \ + "*:22" +' + +test_expect_success 'invalid entries are ignored with a warning' ' + test_when_finished "git config --global --unset-all safe.host" && + for entry in host.example.com/repo.git user@host.example.com \ + host.example.com: host.example.com:0 host.example.com:65536 \ + "[::1" ::1 "://host.example.com" + do + git config --global --add safe.host "$entry" || return 1 + done && + test_must_fail git ls-remote "ssh://host.example.com$PWD/repo.git" 2>err && + test_grep "is not allowed by safe.host" err && + for entry in host.example.com/repo.git user@host.example.com \ + host.example.com: host.example.com:0 host.example.com:65536 \ + "[::1" ::1 "://host.example.com" + do + test_grep -F "ignoring invalid safe.host entry $SQ$entry$SQ" err || + return 1 + done +' + +test_expect_success 'trailing slash is tolerated' ' + check_safe_hosts allow "ssh://host.example.com$PWD/repo.git" \ + ssh://host.example.com/ +' + +test_expect_success '"*" allows all hosts' ' + check_safe_hosts allow "ssh://host.example.com$PWD/repo.git" \ + other.example.com "*" +' + +test_expect_success 'empty value resets the list' ' + check_safe_hosts deny "ssh://host.example.com$PWD/repo.git" \ + "*" host.example.com "" && + check_safe_hosts allow "ssh://host.example.com$PWD/repo.git" \ + "*" "" host.example.com && + check_safe_hosts deny "ssh://other.example.com$PWD/repo.git" \ + "*" "" host.example.com +' + +test_expect_success 'safe.host is respected on the command line' ' + test_must_fail git -c safe.host=host.example.com \ + ls-remote "ssh://evil.example.com$PWD/repo.git" 2>err && + test_grep "is not allowed by safe.host" err +' + +test_expect_success 'safe.host is ignored in repository config' ' + test_config safe.host other.example.com && + check_safe_hosts allow "ssh://host.example.com$PWD/repo.git" && + check_safe_hosts deny "ssh://other.example.com$PWD/repo.git" \ + host.example.com +' + +test_expect_success 'local repositories are not affected' ' + check_safe_hosts allow repo.git "" && + check_safe_hosts allow "file://$PWD/repo.git" "" +' + +test_done diff --git a/transport.c b/transport.c index 25e2c14a7bde24..aa405b5a04b8f8 100644 --- a/transport.c +++ b/transport.c @@ -19,6 +19,8 @@ #include "refspec.h" #include "branch.h" #include "url.h" +#include "urlmatch.h" +#include "quote.h" #include "submodule.h" #include "strbuf.h" #include "string-list.h" @@ -1204,6 +1206,231 @@ void transport_check_allowed(const char *type) die(_("transport '%s' not allowed"), type); } +struct safe_host { + char *scheme; /* NULL matches any scheme */ + char *host; /* "*" matches any host */ + unsigned int port; /* 0 matches any port */ +}; + +static struct { + int initialized; + /* -1 until the first safe.host entry is seen */ + int allow_all; + struct safe_host *entries; + size_t nr, alloc; +} safe_hosts; + +static void clear_safe_hosts(void) +{ + for (size_t i = 0; i < safe_hosts.nr; i++) { + free(safe_hosts.entries[i].scheme); + free(safe_hosts.entries[i].host); + } + safe_hosts.nr = 0; +} + +static char *xmemdupz_tolower(const char *s, size_t len) +{ + char *ret = xmemdupz(s, len); + + for (char *p = ret; *p; p++) + *p = tolower(*p); + return ret; +} + +/* + * Parse a safe.host entry of the form "[://][:]", + * where may be a bracketed IPv6 literal. A single trailing '/' + * is tolerated so that copy-pasted URLs like "https://example.com/" + * work, but anything else (paths, user names, queries) is rejected. + */ +static int parse_safe_host(const char *value, struct safe_host *out) +{ + const char *scheme_end, *host, *host_end, *p; + unsigned long port = 0; + + scheme_end = strstr(value, "://"); + if (scheme_end) { + if (scheme_end == value) + return -1; + for (p = value; p < scheme_end; p++) + if (!is_urlschemechar(p == value, *p)) + return -1; + host = scheme_end + 3; + } else { + host = value; + } + + if (*host == '[') { + host_end = strchr(++host, ']'); + if (!host_end) + return -1; + p = host_end + 1; + } else { + host_end = host + strcspn(host, ":/"); + p = host_end; + } + + if (host_end == host || + host + strcspn(host, "@?#[]/ \t") < host_end) + return -1; + + if (*p == ':') { + char *end; + + if (!isdigit(*++p)) + return -1; + errno = 0; + port = strtoul(p, &end, 10); + if (errno || !port || port > 65535) + return -1; + p = end; + } + + if (*p == '/') + p++; + if (*p) + return -1; + + out->scheme = scheme_end ? + xmemdupz_tolower(value, scheme_end - value) : NULL; + out->host = xmemdupz_tolower(host, host_end - host); + out->port = port; + return 0; +} + +static int safe_hosts_cb(const char *key, const char *value, + const struct config_context *ctx UNUSED, + void *data UNUSED) +{ + struct safe_host entry; + + if (strcmp(key, "safe.host")) + return 0; + + if (safe_hosts.allow_all < 0) + safe_hosts.allow_all = 0; + + if (!value || !*value) { + clear_safe_hosts(); + safe_hosts.allow_all = 0; + } else if (!strcmp(value, "*")) { + safe_hosts.allow_all = 1; + } else if (parse_safe_host(value, &entry)) { + warning(_("ignoring invalid safe.host entry '%s'"), value); + } else { + ALLOC_GROW(safe_hosts.entries, safe_hosts.nr + 1, + safe_hosts.alloc); + safe_hosts.entries[safe_hosts.nr++] = entry; + } + + return 0; +} + +static void read_safe_hosts(void) +{ + if (safe_hosts.initialized) + return; + safe_hosts.initialized = 1; + safe_hosts.allow_all = -1; + + git_protected_config(safe_hosts_cb, NULL); + + /* No safe.host configured at all means every host is allowed. */ + if (safe_hosts.allow_all < 0) + safe_hosts.allow_all = 1; +} + +static unsigned int default_port(const char *scheme) +{ + if (!strcmp(scheme, "http")) + return 80; + if (!strcmp(scheme, "https")) + return 443; + if (!strcmp(scheme, "ftp")) + return 21; + if (!strcmp(scheme, "ftps")) + return 990; + if (!strcmp(scheme, "ssh")) + return 22; + if (!strcmp(scheme, "git")) + return DEFAULT_GIT_PORT; + return 0; +} + +int safe_hosts_restricted(void) +{ + read_safe_hosts(); + return !safe_hosts.allow_all; +} + +int is_host_allowed(const char *scheme, const char *host, unsigned int port) +{ + size_t len = strlen(host); + char *lower; + int ret = 0; + + if (!safe_hosts_restricted()) + return 1; + + if (len >= 2 && host[0] == '[' && host[len - 1] == ']') { + host++; + len -= 2; + } + lower = xmemdupz_tolower(host, len); + + if (!port) + port = default_port(scheme); + + for (size_t i = 0; i < safe_hosts.nr; i++) { + const struct safe_host *e = &safe_hosts.entries[i]; + + if (e->scheme && strcmp(e->scheme, scheme)) + continue; + if (e->port && e->port != port) + continue; + if (strcmp(e->host, "*") && + !urlmatch_host(lower, len, e->host, strlen(e->host))) + continue; + + ret = 1; + break; + } + + free(lower); + return ret; +} + +void format_safe_host_entry(struct strbuf *buf, const char *scheme, + const char *host, unsigned int port) +{ + strbuf_addf(buf, "%s://", scheme); + if (strchr(host, ':') && *host != '[') + strbuf_addf(buf, "[%s]", host); + else + strbuf_addstr(buf, host); + if (port && port != default_port(scheme)) + strbuf_addf(buf, ":%u", port); +} + +void transport_check_host_allowed(const char *scheme, const char *host, + unsigned int port) +{ + struct strbuf entry = STRBUF_INIT, quoted = STRBUF_INIT; + + if (is_host_allowed(scheme, host, port)) + return; + + format_safe_host_entry(&entry, scheme, host, port); + sq_quote_buf_pretty("ed, entry.buf); + + die(_("connecting to '%s' is not allowed by safe.host\n" + "To allow such connections, call:\n" + "\n" + "\tgit config --global --add safe.host %s"), + entry.buf, quoted.buf); +} + static struct transport_vtable bundle_vtable = { .get_refs_list = get_refs_from_bundle, .fetch_refs = fetch_refs_from_bundle, diff --git a/transport.h b/transport.h index 39193d0077a312..86317f76700a15 100644 --- a/transport.h +++ b/transport.h @@ -8,6 +8,7 @@ #include "connect.h" struct fetch_object_info_results; +struct strbuf; struct git_transport_options { unsigned thin : 1; @@ -187,6 +188,37 @@ int is_transport_allowed(const char *type, int from_user); */ void transport_check_allowed(const char *type); +/* + * Returns 1 if safe.host limits the hosts Git may connect to, or 0 if + * every host is allowed. + */ +int safe_hosts_restricted(void); + +/* + * Check whether the safe.host configuration permits connecting to + * "host" on "port" using the URL scheme "scheme" (e.g. "https" or + * "ssh"). A "port" of 0 means the default port for "scheme". "host" + * must not include any "user@" prefix; IPv6 literals may be given + * with or without surrounding brackets. + */ +int is_host_allowed(const char *scheme, const char *host, unsigned int port); + +/* + * Append to "buf" the narrowest safe.host entry that allows connecting + * to "host" on "port" using "scheme", with the same meaning of the + * arguments as for is_host_allowed(), e.g. "https://example.com" or + * "ssh://[::1]:2222". The port is omitted if it is the scheme's default. + */ +void format_safe_host_entry(struct strbuf *buf, const char *scheme, + const char *host, unsigned int port); + +/* + * Like is_host_allowed(), but die() with advice on how to allow the + * connection if it is not allowed. + */ +void transport_check_host_allowed(const char *scheme, const char *host, + unsigned int port); + /* Transport options which apply to git:// and scp-style URLs */ /* The program to use on the remote side to send a pack */ From 8189ec15f58cc671513fc9578ea1d0ea11b9d0b4 Mon Sep 17 00:00:00 2001 From: Matthew John Cheetham Date: Tue, 24 Nov 2026 10:24:43 +0000 Subject: [PATCH 3/3] http: enforce safe.host The previous commit taught the git and ssh transports to refuse to connect to hosts not listed in safe.host. HTTP needs more care, as the URL handed to the remote helper is only where the conversation starts: curl may follow redirects to other hosts (for the initial request by default, or for any request with http.followRedirects set to true), and the dumb HTTP walker can be pointed at other hosts via http-alternates. Check the remote URL up front in http_init(), so that a disallowed remote fails before any connection is attempted, with the same advice the native transports give. This also covers the other callers of http_init(), such as "git http-fetch" downloading packfile URIs, and bundle URIs fetched through the remote helper. For everything else, have curl call back to check its effective URL: - CURLOPT_SOCKOPTFUNCTION runs after curl creates each socket but before it connects it, so a redirect to a disallowed host is refused before any TCP or TLS traffic (and so before any client certificate is presented). Unlike CURLOPT_OPENSOCKETFUNCTION it does not require us to create the socket ourselves, which would not mix well with our socket() wrapper on Windows. - CURLOPT_PREREQFUNCTION runs before each request is sent. This catches requests that curl sends over a connection it reuses, e.g. one to an HTTP proxy, where no new socket is created. The callbacks are only installed when safe.host restricts the allowed hosts, so the default configuration is unaffected. Name resolution of a disallowed redirect target can still happen, as there is no hook that sees every lookup (e.g. those satisfied from curl's DNS cache). CURLOPT_PREREQFUNCTION needs libcurl 7.80.0, which is newer than the oldest version we support. Rather than letting redirects slip through reused connections when built against, or running with, an older libcurl, do not follow redirects at all in that case when safe.host is restricted. This breaks setups that rely on redirects, but only for users who opted into safe.host, and fails closed. Check http-alternates explicitly as well, so that an alternate on a disallowed host is skipped with a warning, just like one using a disallowed protocol, rather than surfacing as a failed request. Assisted-by: Claude Opus 5.5 Signed-off-by: Matthew John Cheetham --- Documentation/config/http.adoc | 3 +- Documentation/config/safe.adoc | 19 +++-- git-curl-compat.h | 7 ++ http-walker.c | 5 ++ http.c | 141 +++++++++++++++++++++++++++++++++ http.h | 6 ++ t/lib-httpd/apache.conf | 1 + t/meson.build | 1 + t/t5817-safe-host-http.sh | 98 +++++++++++++++++++++++ 9 files changed, 275 insertions(+), 6 deletions(-) create mode 100755 t/t5817-safe-host-http.sh diff --git a/Documentation/config/http.adoc b/Documentation/config/http.adoc index 792a71b41350d4..5469fc3e6ba46e 100644 --- a/Documentation/config/http.adoc +++ b/Documentation/config/http.adoc @@ -375,7 +375,8 @@ http.followRedirects:: the initial request to a remote, but not for subsequent follow-up HTTP requests. Since git uses the redirected URL as the base for the follow-up requests, this is generally - sufficient. The default is `initial`. + sufficient. The default is `initial`. Redirects to hosts not + allowed by `safe.host` are refused regardless of this setting. http..*:: Any of the http.* options above can be applied selectively to some URLs. diff --git a/Documentation/config/safe.adoc b/Documentation/config/safe.adoc index 42d6bd6d1d3c53..6c13e7a8a98798 100644 --- a/Documentation/config/safe.adoc +++ b/Documentation/config/safe.adoc @@ -115,8 +115,17 @@ value. + Repositories on the local filesystem, including those accessed via `file://` URLs, are not subject to this check. Neither are remote -helpers (see linkgit:gitremote-helpers[7]), as Git cannot know which -hosts they connect to; use `protocol.allow` to restrict them instead. -For `ssh`, the host checked is the one named in the remote URL, before -any aliasing performed by the SSH client's own configuration. Proxies, -e.g. those configured via `core.gitProxy`, are not checked. +helpers (see linkgit:gitremote-helpers[7]) other than Git's own helpers +for `http`, `https`, `ftp` and `ftps`, as Git cannot know which hosts +they connect to; use `protocol.allow` to restrict them instead. For +`ssh`, the host checked is the one named in the remote URL, before any +aliasing performed by the SSH client's own configuration. Proxies, +e.g. those configured via `http.proxy` or `core.gitProxy`, are not +checked. ++ +For HTTP(S), the host of each redirect (see `http.followRedirects`) and +of each `http-alternates` entry is checked as well, before Git connects +or sends any request to it. If Git was built with, or is running +against, a libcurl older than 7.80.0, it cannot check every request +that follows a redirect, and so does not follow redirects at all when +`safe.host` limits the allowed hosts. diff --git a/git-curl-compat.h b/git-curl-compat.h index 25678b5dbd2c80..ddda734008c761 100644 --- a/git-curl-compat.h +++ b/git-curl-compat.h @@ -52,6 +52,13 @@ #define GIT_CURL_HAVE_CURLINFO_RETRY_AFTER 1 #endif +/** + * CURLOPT_PREREQFUNCTION was added in 7.80.0, released in November 2021. + */ +#if LIBCURL_VERSION_NUM >= 0x075000 +#define GIT_CURL_HAVE_CURLOPT_PREREQFUNCTION 1 +#endif + /** * CURLOPT_PROTOCOLS_STR and CURLOPT_REDIR_PROTOCOLS_STR were added in 7.85.0, * released in August 2022. diff --git a/http-walker.c b/http-walker.c index abafca84d65441..e7e7a2a0b79ad2 100644 --- a/http-walker.c +++ b/http-walker.c @@ -196,6 +196,11 @@ static int is_alternate_allowed(const char *url) warning("ignoring alternate with restricted protocol: %s", url); return 0; } + if (!http_is_url_allowed(url, 1)) { + warning(_("ignoring alternate on host not allowed by safe.host: %s"), + url); + return 0; + } return 1; } diff --git a/http.c b/http.c index 4af3c29c769559..0f7c9a9e8efa30 100644 --- a/http.c +++ b/http.c @@ -1070,6 +1070,125 @@ static void proto_list_append(struct strbuf *list, const char *proto) strbuf_addstr(list, proto); } +static int parse_url_host(const char *url, char **scheme, char **host, + unsigned int *port) +{ + struct url_info info; + + if (!url_normalize(url, &info)) + return -1; + + *scheme = xmemdupz(info.url, info.scheme_len); + *host = xmemdupz(info.url + info.host_off, info.host_len); + *port = info.port_len ? strtoul(info.url + info.port_off, NULL, 10) : 0; + free(info.url); + return 0; +} + +int http_is_url_allowed(const char *url, int quiet) +{ + char *scheme, *host; + unsigned int port; + int ret; + + if (!safe_hosts_restricted()) + return 1; + + if (parse_url_host(url, &scheme, &host, &port) < 0) { + if (!quiet) + error(_("unable to determine host for safe.host check")); + return 0; + } + + ret = is_host_allowed(scheme, host, port); + if (!ret && !quiet) { + struct strbuf entry = STRBUF_INIT; + + format_safe_host_entry(&entry, scheme, host, port); + error(_("connecting to '%s' is not allowed by safe.host"), + entry.buf); + strbuf_release(&entry); + } + + free(scheme); + free(host); + return ret; +} + +static int check_effective_url(CURL *curl) +{ + static char *last_reported; + char *effective_url = NULL; + const char *url; + + if (curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, + &effective_url) != CURLE_OK) + effective_url = NULL; + url = effective_url ? effective_url : ""; + if (http_is_url_allowed(url, 1)) + return 1; + + /* curl may try several addresses for one URL; complain only once */ + if (!last_reported || strcmp(last_reported, url)) { + http_is_url_allowed(url, 0); + free(last_reported); + last_reported = xstrdup(url); + } + return 0; +} + +/* + * curl calls this after creating each socket, but before connecting it, + * so that we never connect to a host that safe.host does not allow, + * e.g. when following a redirect. + */ +static int check_safe_hosts_sockopt(void *curl, curl_socket_t fd UNUSED, + curlsocktype purpose UNUSED) +{ + return check_effective_url(curl) ? CURL_SOCKOPT_OK : CURL_SOCKOPT_ERROR; +} + +#ifdef GIT_CURL_HAVE_CURLOPT_PREREQFUNCTION +/* + * curl calls this before sending each request, which also covers those + * sent over a reused connection, e.g. to a proxy, where no new socket + * is created. + */ +static int check_safe_hosts_prereq(void *curl, + char *conn_primary_ip UNUSED, + char *conn_local_ip UNUSED, + int conn_primary_port UNUSED, + int conn_local_port UNUSED) +{ + return check_effective_url(curl) ? + CURL_PREREQFUNC_OK : CURL_PREREQFUNC_ABORT; +} +#endif + +/* + * Install the safe.host callbacks on "curl". Their data pointers must + * be set to each handle duplicated from it; see get_active_slot(). + */ +static void init_safe_hosts_callbacks(CURL *curl) +{ + int vets_every_request = 0; + + curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, + check_safe_hosts_sockopt); +#ifdef GIT_CURL_HAVE_CURLOPT_PREREQFUNCTION + vets_every_request = curl_easy_setopt(curl, CURLOPT_PREREQFUNCTION, + check_safe_hosts_prereq) == CURLE_OK; +#endif + + /* + * Without CURLOPT_PREREQFUNCTION (at build or run time), curl + * could follow a redirect to another host over a connection it + * reuses, e.g. one to a proxy, without asking us. Follow none. + */ + if (!vets_every_request) + http_follow_config = HTTP_FOLLOW_NONE; +} + static long get_curl_allowed_protocols(int from_user, struct strbuf *list) { long bits = 0; @@ -1391,6 +1510,17 @@ void http_init(struct remote *remote, const char *url, int proactive_auth) char *normalized_url; struct urlmatch_config config = URLMATCH_CONFIG_INIT; + if (safe_hosts_restricted()) { + char *scheme, *host; + unsigned int port; + + if (parse_url_host(url, &scheme, &host, &port) < 0) + die(_("unable to determine host for safe.host check")); + transport_check_host_allowed(scheme, host, port); + free(scheme); + free(host); + } + config.section = "http"; config.key = NULL; config.collect_fn = http_options; @@ -1511,6 +1641,8 @@ void http_init(struct remote *remote, const char *url, int proactive_auth) set_long_from_env(&http_max_retry_time, "GIT_HTTP_MAX_RETRY_TIME"); curl_default = get_curl_handle(); + if (safe_hosts_restricted()) + init_safe_hosts_callbacks(curl_default); } void http_cleanup(void) @@ -1610,6 +1742,15 @@ struct active_request_slot *get_active_slot(void) slot->curl = curl_easy_duphandle(curl_default); if (!slot->curl) die("curl_easy_duphandle failed"); + if (safe_hosts_restricted()) { + /* point the callbacks at this handle, not curl_default */ + curl_easy_setopt(slot->curl, CURLOPT_SOCKOPTDATA, + slot->curl); +#ifdef GIT_CURL_HAVE_CURLOPT_PREREQFUNCTION + curl_easy_setopt(slot->curl, CURLOPT_PREREQDATA, + slot->curl); +#endif + } curl_session_count++; } diff --git a/http.h b/http.h index 729c51904d39ad..6be418f307c7c9 100644 --- a/http.h +++ b/http.h @@ -68,6 +68,12 @@ void step_active_slots(void); void http_init(struct remote *remote, const char *url, int proactive_auth); void http_cleanup(void); + +/* + * Returns 1 if safe.host allows connecting to the host named in "url", + * or 0 otherwise, in which case an error is reported unless "quiet". + */ +int http_is_url_allowed(const char *url, int quiet); struct curl_slist *http_copy_default_headers(void); extern long int git_curl_ipresolve; diff --git a/t/lib-httpd/apache.conf b/t/lib-httpd/apache.conf index 4149fc1078a877..1515572f8c99f8 100644 --- a/t/lib-httpd/apache.conf +++ b/t/lib-httpd/apache.conf @@ -205,6 +205,7 @@ RewriteRule ^/smart-redir-temp/(.*)$ /smart/$1 [R=302] RewriteRule ^/smart-redir-auth/(.*)$ /auth/smart/$1 [R=301] RewriteRule ^/smart-redir-limited/(.*)/info/refs$ /smart/$1/info/refs [R=301] RewriteRule ^/ftp-redir/(.*)$ ftp://localhost:1000/$1 [R=302] +RewriteRule ^/smart-redir-localhost/(.*)$ %{REQUEST_SCHEME}://localhost:%{SERVER_PORT}/smart/$1 [R=302] RewriteRule ^/loop-redir/x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-(.*) /$1 [R=302] RewriteRule ^/loop-redir/(.*)$ /loop-redir/x-$1 [R=302] diff --git a/t/meson.build b/t/meson.build index 63f9dce4e27f6c..dc2e53d9ec24bf 100644 --- a/t/meson.build +++ b/t/meson.build @@ -770,6 +770,7 @@ integration_tests = [ 't5814-proto-disable-ext.sh', 't5815-submodule-protos.sh', 't5816-safe-host.sh', + 't5817-safe-host-http.sh', 't5900-repo-selection.sh', 't6000-rev-list-misc.sh', 't6001-rev-list-graft.sh', diff --git a/t/t5817-safe-host-http.sh b/t/t5817-safe-host-http.sh new file mode 100755 index 00000000000000..67761d2e3cf7f3 --- /dev/null +++ b/t/t5817-safe-host-http.sh @@ -0,0 +1,98 @@ +#!/bin/sh + +test_description='safe.host restricts the hosts Git connects to over HTTP' + +. ./test-lib.sh +. "$TEST_DIRECTORY"/lib-httpd.sh +start_httpd + +# Without CURLOPT_PREREQFUNCTION, Git cannot check where a redirect leads +# before following it, and so does not follow any. +test_lazy_prereq CURL_PREREQFUNCTION ' + curl_version=$(git version --build-options | sed -n "s/^libcurl: //p") && + test -n "$curl_version" && + lowest=$(printf "%s\n" 7.80.0 "$curl_version" | + sort -t. -k1,1n -k2,2n -k3,3n | head -n 1) && + test "$lowest" = 7.80.0 +' + +test_expect_success 'setup' ' + test_commit one && + git init --bare "$HTTPD_DOCUMENT_ROOT_PATH/repo.git" && + git push "$HTTPD_DOCUMENT_ROOT_PATH/repo.git" HEAD +' + +test_expect_success 'listed host is allowed' ' + git -c safe.host=127.0.0.1 ls-remote "$HTTPD_URL/smart/repo.git" >out && + test_grep refs/heads/ out +' + +test_expect_success 'unlisted host is denied before connecting' ' + test_must_fail git -c safe.host=example.com \ + ls-remote "$HTTPD_URL/smart/never-requested.git" 2>err && + test_grep "connecting to .$HTTPD_URL. is not allowed by safe.host" err && + test_grep "git config --global --add safe.host $HTTPD_URL$" err && + test_grep ! never-requested "$HTTPD_ROOT_PATH/access.log" +' + +test_expect_success 'scheme and port are checked' ' + git -c safe.host="$HTTPD_PROTO://127.0.0.1:$LIB_HTTPD_PORT" \ + ls-remote "$HTTPD_URL/smart/repo.git" && + test_must_fail git -c safe.host=127.0.0.1:1 \ + ls-remote "$HTTPD_URL/smart/repo.git" 2>err && + test_grep "connecting to .$HTTPD_URL. is not allowed by safe.host" err && + test_must_fail git -c safe.host=ssh://127.0.0.1 \ + ls-remote "$HTTPD_URL/smart/repo.git" 2>err && + test_grep "connecting to .$HTTPD_URL. is not allowed by safe.host" err +' + +test_expect_success 'redirect to another host is followed by default' ' + git ls-remote "$HTTPD_URL/smart-redir-localhost/repo.git" >out && + test_grep refs/heads/ out +' + +test_expect_success CURL_PREREQFUNCTION 'redirect to listed host is followed' ' + git -c safe.host=127.0.0.1 -c safe.host=localhost \ + ls-remote "$HTTPD_URL/smart-redir-localhost/repo.git" >out && + test_grep refs/heads/ out +' + +test_expect_success 'redirect to unlisted host is denied' ' + test_must_fail git -c safe.host=127.0.0.1 \ + ls-remote "$HTTPD_URL/smart-redir-localhost/repo.git" 2>err && + if test_have_prereq CURL_PREREQFUNCTION + then + test_grep "connecting to .$HTTPD_PROTO://localhost:$LIB_HTTPD_PORT. is not allowed by safe.host" err + fi +' + +test_expect_success !CURL_PREREQFUNCTION 'redirects are not followed' ' + test_must_fail git -c safe.host=127.0.0.1 \ + ls-remote "$HTTPD_URL/smart-redir-perm/repo.git" +' + +test_expect_success CURL_PREREQFUNCTION 'http-alternates on unlisted hosts are ignored' ' + victim=$HTTPD_DOCUMENT_ROOT_PATH/victim.git && + git init --bare "$victim" && + git -C "$victim" --work-tree=. commit --allow-empty -m secret && + git -C "$victim" repack -ad && + git -C "$victim" update-server-info && + oid=$(git -C "$victim" rev-parse HEAD) && + + evil=$HTTPD_DOCUMENT_ROOT_PATH/evil.git && + git init --template= --bare "$evil" && + mkdir "$evil/info" && + # do this by hand to avoid object existence check + printf "%s\\t%s\\n" $oid refs/heads/main >"$evil/info/refs" && + echo "$HTTPD_PROTO://localhost:$LIB_HTTPD_PORT/dumb/victim.git/objects" \ + >"$evil/objects/info/http-alternates" && + + test_must_fail git -c http.followRedirects=true -c safe.host=127.0.0.1 \ + clone "$HTTPD_URL/dumb/evil.git" evil-denied 2>err && + test_grep "ignoring alternate on host not allowed by safe.host" err && + git -c http.followRedirects=true \ + -c safe.host=127.0.0.1 -c safe.host=localhost \ + clone "$HTTPD_URL/dumb/evil.git" evil-allowed +' + +test_done