Debian Codegraph @

signer.go

raw symbols SCIP
1 package goproxy
2
3 import (
4 "crypto"
5 "crypto/ecdsa"
6 "crypto/elliptic"
7 "crypto/rsa"
8 "crypto/sha1"
9 "crypto/tls"
10 "crypto/x509"
11 "crypto/x509/pkix"
12 "fmt"
13 "math/big"
14 "math/rand"
15 "net"
16 "runtime"
17 "sort"
18 "time"
19 )
20
21 func hashSorted(lst []string) []byte {
22 c := make([]string, len(lst))
23 copy(c, lst)
24 sort.Strings(c)
25 h := sha1.New()
26 for _, s := range c {
27 h.Write([]byte(s + ","))
28 }
29 return h.Sum(nil)
30 }
31
32 func hashSortedBigInt(lst []string) *big.Int {
33 rv := new(big.Int)
34 rv.SetBytes(hashSorted(lst))
35 return rv
36 }
37
38 var goproxySignerVersion = ":goroxy1"
39
40 func signHost(ca tls.Certificate, hosts []string) (cert *tls.Certificate, err error) {
41 var x509ca *x509.Certificate
42
43 // Use the provided ca and not the global GoproxyCa for certificate generation.
44 if x509ca, err = x509.ParseCertificate(ca.Certificate[0]); err != nil {
45 return
46 }
47
48 start := time.Unix(time.Now().Unix()-2592000, 0) // 2592000 = 30 day
49 end := time.Unix(time.Now().Unix()+31536000, 0) // 31536000 = 365 day
50
51 serial := big.NewInt(rand.Int63())
52 template := x509.Certificate{
53 // TODO(elazar): instead of this ugly hack, just encode the certificate and hash the binary form.
54 SerialNumber: serial,
55 Issuer: x509ca.Subject,
56 Subject: pkix.Name{
57 Organization: []string{"GoProxy untrusted MITM proxy Inc"},
58 },
59 NotBefore: start,
60 NotAfter: end,
61
62 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
63 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
64 BasicConstraintsValid: true,
65 }
66 for _, h := range hosts {
67 if ip := net.ParseIP(h); ip != nil {
68 template.IPAddresses = append(template.IPAddresses, ip)
69 } else {
70 template.DNSNames = append(template.DNSNames, h)
71 template.Subject.CommonName = h
72 }
73 }
74
75 hash := hashSorted(append(hosts, goproxySignerVersion, ":"+runtime.Version()))
76 var csprng CounterEncryptorRand
77 if csprng, err = NewCounterEncryptorRandFromKey(ca.PrivateKey, hash); err != nil {
78 return
79 }
80
81 var certpriv crypto.Signer
82 switch ca.PrivateKey.(type) {
83 case *rsa.PrivateKey:
84 if certpriv, err = rsa.GenerateKey(&csprng, 2048); err != nil {
85 return
86 }
87 case *ecdsa.PrivateKey:
88 if certpriv, err = ecdsa.GenerateKey(elliptic.P256(), &csprng); err != nil {
89 return
90 }
91 default:
92 err = fmt.Errorf("unsupported key type %T", ca.PrivateKey)
93 }
94
95 var derBytes []byte
96 if derBytes, err = x509.CreateCertificate(&csprng, &template, x509ca, certpriv.Public(), ca.PrivateKey); err != nil {
97 return
98 }
99 return &tls.Certificate{
100 Certificate: [][]byte{derBytes, ca.Certificate[0]},
101 PrivateKey: certpriv,
102 }, nil
103 }
104
105 func init() {
106 // Avoid deterministic random numbers
107 rand.Seed(time.Now().UnixNano())
108 }