fix: SubKeyId may not be same AuthorityKeyId for self-signed CA (#4093)

In situations when cert is its own CA the SubKeyId is not
same as AuthorityKeyId

Refer
https://cs.opensource.google/go/go/+/refs/tags/go1.18.2:src/crypto/x509/x509.go;l=1525

This PR handles this by validating the SubKeyId with correct value
that is expected, extends the current TOFU style.
This commit is contained in:
Harshavardhana
2022-05-23 05:13:20 -07:00
committed by GitHub
parent 907555c849
commit 83d81ea590
2 changed files with 181 additions and 100 deletions
+2 -100
View File
@@ -19,19 +19,14 @@ package cmd
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"fmt"
"math/rand"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"time"
@@ -71,8 +66,10 @@ var aliasSetCmd = cli.Command{
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS URL ACCESSKEY SECRETKEY
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
@@ -359,101 +356,6 @@ func mainAliasSet(cli *cli.Context, deprecated bool) error {
return nil
}
// promptTrustSelfSignedCert connects to the given endpoint and
// checks whether the peer certificate can be verified.
// If not, it computes a fingerprint of the peer certificate
// public key, asks the user to confirm the fingerprint and
// adds the peer certificate to the local trust store in the
// CAs directory.
func promptTrustSelfSignedCert(ctx context.Context, endpoint, alias string) (*x509.Certificate, *probe.Error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, probe.NewError(err)
}
// no need to probe certs for http endpoints.
if req.URL.Scheme == "http" {
return nil, nil
}
client := http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{
RootCAs: globalRootCAs, // make sure to use loaded certs before probing
},
},
}
_, tlsErr := client.Do(req)
if tlsErr == nil {
// certs are already trusted system wide, nothing to do.
return nil, nil
}
if tlsErr != nil && !strings.Contains(tlsErr.Error(), "certificate signed by unknown authority") {
return nil, probe.NewError(tlsErr)
}
// Now, we fetch the peer certificate, compute the SHA-256 of
// public key and let the user confirm the fingerprint.
// If the user confirms, we store the peer certificate in the CAs
// directory and retry.
peerCert, err := fetchPeerCertificate(ctx, endpoint)
if err != nil {
return nil, probe.NewError(err)
}
// Check that the subject key id is equal to the authority key id.
// If true, the certificate is its own issuer, and therefore, a
// self-signed certificate.
// Otherwise, the certificate has been issued by some other
// certificate that is just not trusted
if !bytes.Equal(peerCert.SubjectKeyId, peerCert.AuthorityKeyId) {
return nil, probe.NewError(tlsErr)
}
fingerprint := sha256.Sum256(peerCert.RawSubjectPublicKeyInfo)
fmt.Printf("Fingerprint of %s public key: %s\nConfirm public key y/N: ", color.GreenString(alias), color.YellowString(hex.EncodeToString(fingerprint[:])))
answer, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return nil, probe.NewError(err)
}
if answer = strings.ToLower(answer); answer != "y\n" && answer != "yes\n" {
return nil, probe.NewError(tlsErr)
}
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: peerCert.Raw})
if err = os.WriteFile(filepath.Join(mustGetCAsDir(), alias+".crt"), certPEM, 0o644); err != nil {
return nil, probe.NewError(err)
}
return peerCert, nil
}
// fetchPeerCertificate uses the given transport to fetch the peer
// certificate from the given endpoint.
func fetchPeerCertificate(ctx context.Context, endpoint string) (*x509.Certificate, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
client := http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if resp.TLS == nil || len(resp.TLS.PeerCertificates) == 0 {
return nil, fmt.Errorf("Unable to read remote TLS certificate")
}
return resp.TLS.PeerCertificates[0], nil
}
// configurePeerCertificate adds the peer certificate to the
// TLS root CAs of s3Config. Once configured, any client
// initialized with this config trusts the given peer certificate.
+179
View File
@@ -0,0 +1,179 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"bufio"
"bytes"
"context"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/asn1"
"encoding/hex"
"encoding/pem"
"fmt"
"math/big"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/minio/mc/pkg/probe"
)
func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, e error) {
// pkcs1PublicKey reflects the ASN.1 structure of a PKCS #1 public key.
type pkcs1PublicKey struct {
N *big.Int
E int
}
switch pub := pub.(type) {
case *rsa.PublicKey:
publicKeyBytes, e = asn1.Marshal(pkcs1PublicKey{
N: pub.N,
E: pub.E,
})
if e != nil {
return nil, e
}
case *ecdsa.PublicKey:
publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
case ed25519.PublicKey:
publicKeyBytes = pub
default:
return nil, fmt.Errorf("x509: unsupported public key type: %T", pub)
}
return publicKeyBytes, nil
}
// promptTrustSelfSignedCert connects to the given endpoint and
// checks whether the peer certificate can be verified.
// If not, it computes a fingerprint of the peer certificate
// public key, asks the user to confirm the fingerprint and
// adds the peer certificate to the local trust store in the
// CAs directory.
func promptTrustSelfSignedCert(ctx context.Context, endpoint, alias string) (*x509.Certificate, *probe.Error) {
req, e := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if e != nil {
return nil, probe.NewError(e)
}
// no need to probe certs for http endpoints.
if req.URL.Scheme == "http" {
return nil, nil
}
client := http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{
RootCAs: globalRootCAs, // make sure to use loaded certs before probing
},
},
}
_, te := client.Do(req)
if te == nil {
// certs are already trusted system wide, nothing to do.
return nil, nil
}
if te != nil && !strings.Contains(te.Error(), "certificate signed by unknown authority") {
return nil, probe.NewError(te)
}
// Now, we fetch the peer certificate, compute the SHA-256 of
// public key and let the user confirm the fingerprint.
// If the user confirms, we store the peer certificate in the CAs
// directory and retry.
peerCert, e := fetchPeerCertificate(ctx, endpoint)
if e != nil {
return nil, probe.NewError(e)
}
if peerCert.IsCA && len(peerCert.AuthorityKeyId) == 0 {
// If peerCert is its own CA then AuthorityKeyId will be empty
// which means the SubjeyKeyId is the sha1.Sum(publicKeyBytes)
// Refer - SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:
publicKeyBytes, e := marshalPublicKey(peerCert.PublicKey)
if e != nil {
return nil, probe.NewError(e)
}
h := sha1.Sum(publicKeyBytes)
if !bytes.Equal(h[:], peerCert.SubjectKeyId) {
return nil, probe.NewError(te)
}
} else {
// Check that the subject key id is equal to the authority key id.
// If true, the certificate is its own issuer, and therefore, a
// self-signed certificate. Otherwise, the certificate has been
// issued by some other certificate that is just not trusted.
if !bytes.Equal(peerCert.SubjectKeyId, peerCert.AuthorityKeyId) {
return nil, probe.NewError(te)
}
}
fingerprint := sha256.Sum256(peerCert.RawSubjectPublicKeyInfo)
fmt.Printf("Fingerprint of %s public key: %s\nConfirm public key y/N: ", color.GreenString(alias), color.YellowString(hex.EncodeToString(fingerprint[:])))
answer, e := bufio.NewReader(os.Stdin).ReadString('\n')
if e != nil {
return nil, probe.NewError(e)
}
if answer = strings.ToLower(answer); answer != "y\n" && answer != "yes\n" {
return nil, probe.NewError(te)
}
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: peerCert.Raw})
if e = os.WriteFile(filepath.Join(mustGetCAsDir(), alias+".crt"), certPEM, 0o644); e != nil {
return nil, probe.NewError(e)
}
return peerCert, nil
}
// fetchPeerCertificate uses the given transport to fetch the peer
// certificate from the given endpoint.
func fetchPeerCertificate(ctx context.Context, endpoint string) (*x509.Certificate, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
client := http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if resp.TLS == nil || len(resp.TLS.PeerCertificates) == 0 {
return nil, fmt.Errorf("Unable to read remote TLS certificate")
}
return resp.TLS.PeerCertificates[0], nil
}