internal/gitpin/gitpin.go
161 lines · 5143 bytes
1// Package gitpin runs git against a user-supplied http or https remote
2// only at addresses resolved and checked immediately before: mirror
3// sync (#279) and repo import (#298).
4package gitpin
5
6import (
7 "context"
8 "fmt"
9 "net"
10 "net/url"
11 "os/exec"
12 "strconv"
13 "strings"
14
15 "gitbay.org/gitbay/internal/toolpath"
16 "gitbay.org/gitbay/internal/webhook"
17)
18
19// Lookup resolves a host to its addresses.
20type Lookup func(ctx context.Context, host string) ([]net.IP, error)
21
22// LookupIP is the system resolver.
23func LookupIP(ctx context.Context, host string) ([]net.IP, error) {
24 return net.DefaultResolver.LookupIP(ctx, "ip", host)
25}
26
27// Remote is a URL whose host resolved to IPs, every one of which passed
28// the address check.
29type Remote struct {
30 URL *url.URL
31 IPs []net.IP
32}
33
34// Resolve parses raw, requires http or https, resolves the host with
35// lookup, and refuses it when it resolves to nothing or, unless
36// allowLocal, to any private or local address.
37func Resolve(ctx context.Context, lookup Lookup, raw string, allowLocal bool) (Remote, error) {
38 u, err := url.Parse(raw)
39 if err != nil {
40 return Remote{}, err
41 }
42 if u.Scheme != "https" && u.Scheme != "http" {
43 return Remote{}, fmt.Errorf("URL scheme %q is not http or https", u.Scheme)
44 }
45 host := u.Hostname()
46 if host == "" {
47 return Remote{}, fmt.Errorf("URL has no host")
48 }
49 if err := CheckHost(host); err != nil {
50 return Remote{}, err
51 }
52 ips, err := lookup(ctx, host)
53 if err != nil {
54 return Remote{}, fmt.Errorf("resolving %s: %w", host, err)
55 }
56 if len(ips) == 0 {
57 // An empty resolve list would leave curl to resolve the host itself.
58 return Remote{}, fmt.Errorf("%s resolves to no address", host)
59 }
60 if err := webhook.CheckAddrs(host, ips, allowLocal); err != nil {
61 return Remote{}, err
62 }
63 return Remote{URL: u, IPs: ips}, nil
64}
65
66// CheckHost refuses a host written as a number in a form other than
67// an IP literal: 127.1, 2130706433 and 0x7f.1 are loopback to curl's
68// parser but not to Go's, so they are refused rather than left to a
69// resolver.
70func CheckHost(host string) error {
71 if net.ParseIP(host) == nil && numericHost(host) {
72 return fmt.Errorf("host %q is a numeric address in a form other than dotted decimal; write it as a.b.c.d", host)
73 }
74 return nil
75}
76
77// numericHost reports whether every label of host is a decimal, octal
78// or hex number, the shapes inet_aton reads as an IPv4 address.
79func numericHost(host string) bool {
80 for _, label := range strings.Split(strings.TrimSuffix(host, "."), ".") {
81 digits, base := label, "0123456789"
82 if rest, ok := strings.CutPrefix(strings.ToLower(label), "0x"); ok {
83 digits, base = rest, "0123456789abcdef"
84 }
85 if strings.Trim(strings.ToLower(digits), base) != "" || label == "" {
86 return false
87 }
88 }
89 return true
90}
91
92// Args are git's leading -c options for r: curl's resolve list pins
93// the host, and any other name on the same port, to the checked
94// addresses, and with redirects off a server
95// cannot send git on to a host nobody checked. An address literal
96// needs no pin.
97func (r Remote) Args() []string {
98 args := []string{"-c", "http.followRedirects=false"}
99 host := r.URL.Hostname()
100 if net.ParseIP(host) != nil {
101 return args
102 }
103 port := r.URL.Port()
104 if port == "" {
105 port = "443"
106 if r.URL.Scheme == "http" {
107 port = "80"
108 }
109 }
110 addrs := make([]string, len(r.IPs))
111 for i, ip := range r.IPs {
112 if ip.To4() == nil {
113 addrs[i] = "[" + ip.String() + "]"
114 } else {
115 addrs[i] = ip.String()
116 }
117 }
118 pinned := port + ":" + strings.Join(addrs, ",")
119 // The wildcard entry catches a lookup under any other spelling of
120 // the host, so it too lands on the checked addresses.
121 return append(args, "-c", "http.curloptResolve="+host+":"+pinned,
122 "-c", "http.curloptResolve=*:"+pinned)
123}
124
125// Env is git's whole environment for a pinned remote. No system or
126// global gitconfig: a proxy, URL rewrite or redirect setting there
127// would take git around the pin.
128func Env(home string) []string {
129 return []string{"GIT_TERMINAL_PROMPT=0", "HOME=" + home,
130 "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null"}
131}
132
133// VersionOK accepts the output of `git version` for git 2.37 or later,
134// the first release with http.curloptResolve. An older git ignores the
135// setting and would resolve the host itself.
136func VersionOK(out string) error {
137 fields := strings.Fields(out)
138 if len(fields) >= 3 && fields[0] == "git" && fields[1] == "version" {
139 parts := strings.Split(fields[2], ".")
140 if len(parts) >= 2 {
141 major, err1 := strconv.Atoi(parts[0])
142 minor, err2 := strconv.Atoi(parts[1])
143 if err1 == nil && err2 == nil {
144 if major > 2 || major == 2 && minor >= 37 {
145 return nil
146 }
147 return fmt.Errorf("git %s is older than 2.37 and cannot pin remote addresses", fields[2])
148 }
149 }
150 }
151 return fmt.Errorf("cannot read git version from %q", strings.TrimSpace(out))
152}
153
154// CheckGit runs the server's git and refuses one that cannot pin.
155func CheckGit(ctx context.Context) error {
156 out, err := exec.CommandContext(ctx, toolpath.Look("git"), "version").Output()
157 if err != nil {
158 return fmt.Errorf("running git version: %v", err)
159 }
160 return VersionOK(string(out))
161}