package traffic import ( "crypto/rand" "crypto/rsa" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "errors" "fmt" "io/fs" "math/big" "os" "sync" "time" "github.com/lqqyt2423/go-mitmproxy/cert" ) // The MITM CA files under the traffic directory's _ca, in go-mitmproxy's format // (cert/self_sign_ca.go): a CA either side wrote loads on the other. const ( caKeyName = "mitmproxy-ca.pem" // the PKCS#8 key, then the certificate, in PEM caCertName = "mitmproxy-ca-cert.pem" // the certificate in PEM (CACertPath) caCerName = "mitmproxy-ca-cert.cer" // the same certificate, for clients that want .cer ) // loadCA returns the MITM CA kept under dir/_ca, creating it first if there is // no key. // // go-mitmproxy would create it itself (cert.NewSelfSignCA): it looks for the key, // generates one (a few hundred milliseconds of RSA), then writes the three files // with os.Create, by path. A symlink, a hard link or a directory planted in _ca // during the generation made it create files outside the data directory, or // overwrite one there, and no check made before the call can see a change made // during it. So go-mitmproxy never gets the path: the files are created here, // under the verified _ca root, with O_CREATE|O_EXCL (which fails on any existing // name and never follows a symlink, dangling or not), and go-mitmproxy gets the // loaded CA through Options.NewCaFunc. An existing file is used as it is, never // overwritten; a certificate without its key is refused rather than left beside // a new key it does not match. func loadCA(dir string) (cert.CA, error) { ca, err := openCADir(dir) if err != nil { return nil, err } defer ca.Close() data, err := readCAKey(ca) created := false if errors.Is(err, fs.ErrNotExist) { for _, name := range []string{caCertName, caCerName} { if _, err := ca.Lstat(name); !errors.Is(err, fs.ErrNotExist) { return nil, fmt.Errorf("%s exists without %s: remove it, or restore the key", name, caKeyName) } } if data, err = newCAFile(); err != nil { return nil, err } if err := createFile(ca, caKeyName, data, 0o600); err != nil { return nil, err } created = true } else if err != nil { return nil, err } c, err := parseCA(data) if err != nil { return nil, fmt.Errorf("%s: %w", caKeyName, err) } certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.RootCert.Raw}) for _, name := range []string{caCertName, caCerName} { err := createFile(ca, name, certPEM, 0o644) if errors.Is(err, fs.ErrExist) && !created { continue // the existing key's certificate: kept as it is } if err != nil { return nil, err } } return &mitmCA{ca: c, certs: make(map[string]*tls.Certificate)}, nil } // createFile creates ca/name at perm and writes data to it. O_CREATE|O_EXCL fails // on any existing name (a file, a directory, a hard link, a symlink even // dangling, which it never follows), so the only file written is the one created. func createFile(ca *os.Root, name string, data []byte, perm os.FileMode) error { f, err := ca.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL|noFollow, perm) if err != nil { return err } err = f.Chmod(perm) // the umask may have masked bits off perm; f is the file just created if err == nil { _, err = f.Write(data) } if err == nil { err = f.Sync() } if cerr := f.Close(); err == nil { err = cerr } if err != nil { ca.Remove(name) } return err } // newCAFile generates a CA as go-mitmproxy's createCert does and returns the // content of its key file. func newCAFile() ([]byte, error) { key, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return nil, err } template := &x509.Certificate{ SerialNumber: big.NewInt(time.Now().UnixNano() / 100000), Subject: pkix.Name{ CommonName: "mitmproxy", Organization: []string{"mitmproxy"}, }, NotBefore: time.Now().Add(-time.Hour * 48), NotAfter: time.Now().Add(time.Hour * 24 * 365 * 3), BasicConstraintsValid: true, IsCA: true, SignatureAlgorithm: x509.SHA256WithRSA, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, ExtKeyUsage: []x509.ExtKeyUsage{ x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageEmailProtection, x509.ExtKeyUsageTimeStamping, x509.ExtKeyUsageCodeSigning, x509.ExtKeyUsageMicrosoftCommercialCodeSigning, x509.ExtKeyUsageMicrosoftServerGatedCrypto, x509.ExtKeyUsageNetscapeServerGatedCrypto, }, } der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) if err != nil { return nil, err } k, err := x509.MarshalPKCS8PrivateKey(key) if err != nil { return nil, err } out := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: k}) return append(out, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})...), nil } // parseCA reads a key file as go-mitmproxy's load() does: an RSA key (PKCS#8 or // PKCS#1), then the certificate. func parseCA(data []byte) (*cert.SelfSignCA, error) { keyBlock, rest := pem.Decode(data) if keyBlock == nil { return nil, errors.New("no private key") } certBlock, _ := pem.Decode(rest) if certBlock == nil { return nil, errors.New("no certificate") } var key *rsa.PrivateKey k, err := x509.ParsePKCS8PrivateKey(keyBlock.Bytes) if err != nil { if key, err = x509.ParsePKCS1PrivateKey(keyBlock.Bytes); err != nil { return nil, err } } else if key, _ = k.(*rsa.PrivateKey); key == nil { return nil, errors.New("not an RSA private key") } crt, err := x509.ParseCertificate(certBlock.Bytes) if err != nil { return nil, err } return &cert.SelfSignCA{PrivateKey: *key, RootCert: *crt}, nil } // maxHostCerts bounds the host certificates mitmCA keeps, as go-mitmproxy's LRU // of 100 does. const maxHostCerts = 100 // mitmCA is the cert.CA go-mitmproxy signs with: the CA loaded from _ca and the // host certificates signed with it. cert.SelfSignCA keeps those in a cache only // its own constructors set up, and they read or create the files by path. type mitmCA struct { ca *cert.SelfSignCA mu sync.Mutex certs map[string]*tls.Certificate } func (m *mitmCA) GetRootCA() *x509.Certificate { return &m.ca.RootCert } func (m *mitmCA) GetCert(host string) (*tls.Certificate, error) { m.mu.Lock() c := m.certs[host] m.mu.Unlock() if c != nil { return c, nil } c, err := m.ca.DummyCert(host) if err != nil { return nil, err } m.mu.Lock() if len(m.certs) >= maxHostCerts { clear(m.certs) } m.certs[host] = c m.mu.Unlock() return c, nil }