Fix host mismatch in libgit2

Depending on libgit2 version or from its dependencies, the hostname may or may not contain ports

Signed-off-by: Paulo Gomes <paulo.gomes@weave.works>
This commit is contained in:
Paulo Gomes 2022-01-26 17:25:18 +00:00
parent 4aad17445b
commit 9479d04779
No known key found for this signature in database
GPG Key ID: 9995233870E99BEE
1 changed files with 11 additions and 6 deletions

View File

@ -185,16 +185,21 @@ func knownHostsCallback(host string, knownHosts []byte) git2go.CertificateCheckC
// First, attempt to split the configured host and port to validate // First, attempt to split the configured host and port to validate
// the port-less hostname given to the callback. // the port-less hostname given to the callback.
h, _, err := net.SplitHostPort(host) hostWithoutPort, _, err := net.SplitHostPort(host)
if err != nil { if err != nil {
// SplitHostPort returns an error if the host is missing // SplitHostPort returns an error if the host is missing
// a port, assume the host has no port. // a port, assume the host has no port.
h = host hostWithoutPort = host
} }
// Check if the configured host matches the hostname given to // Different versions of libgit handle this differently.
// the callback. // This fixes the case in which ports may be sent back.
if h != hostname { hostnameWithoutPort, _, err := net.SplitHostPort(hostname)
if err != nil {
hostnameWithoutPort = hostname
}
if hostnameWithoutPort != hostWithoutPort {
return git2go.ErrorCodeUser return git2go.ErrorCodeUser
} }
@ -202,7 +207,7 @@ func knownHostsCallback(host string, knownHosts []byte) git2go.CertificateCheckC
// given to the callback match. Use the configured host (that // given to the callback match. Use the configured host (that
// includes the port), and normalize it, so we can check if there // includes the port), and normalize it, so we can check if there
// is an entry for the hostname _and_ port. // is an entry for the hostname _and_ port.
h = knownhosts.Normalize(host) h := knownhosts.Normalize(host)
for _, k := range kh { for _, k := range kh {
if k.matches(h, cert.Hostkey) { if k.matches(h, cert.Hostkey) {
return git2go.ErrorCodeOK return git2go.ErrorCodeOK