-
Notifications
You must be signed in to change notification settings - Fork 7
/
cert.go
91 lines (75 loc) · 2.36 KB
/
cert.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"crypto/tls"
"crypto/x509"
"log"
"os"
"github.com/elazarl/goproxy"
cfsr "github.com/cloudflare/cfssl/csr"
"github.com/cloudflare/cfssl/initca"
)
func fileExists(filename string) bool {
_, err := os.Stat(filename)
return !os.IsNotExist(err)
}
func setGoproxyCA(tlsCert tls.Certificate) {
var err error
if tlsCert.Leaf, err = x509.ParseCertificate(tlsCert.Certificate[0]); err != nil {
log.Fatal("Unable to parse ca", err)
}
goproxy.GoproxyCa = tlsCert
goproxy.OkConnect = &goproxy.ConnectAction{Action: goproxy.ConnectAccept, TLSConfig: goproxy.TLSConfigFromCA(&tlsCert)}
goproxy.MitmConnect = &goproxy.ConnectAction{Action: goproxy.ConnectMitm, TLSConfig: goproxy.TLSConfigFromCA(&tlsCert)}
goproxy.HTTPMitmConnect = &goproxy.ConnectAction{Action: goproxy.ConnectHTTPMitm, TLSConfig: goproxy.TLSConfigFromCA(&tlsCert)}
goproxy.RejectConnect = &goproxy.ConnectAction{Action: goproxy.ConnectReject, TLSConfig: goproxy.TLSConfigFromCA(&tlsCert)}
}
func loadCA() {
if fileExists(Flags.cert) && fileExists(Flags.key) {
tlsCert, err := tls.LoadX509KeyPair(Flags.cert, Flags.key)
if err != nil {
log.Fatal("Unable to load CA certificate and key", err)
}
setGoproxyCA(tlsCert)
} else {
if fileExists(Flags.cert) {
log.Fatalf("CA certificate exists, but found no corresponding key at %s", Flags.key)
} else if fileExists(Flags.key) {
log.Fatalf("CA key exists, but found no corresponding certificate at %s", Flags.cert)
}
log.Println("No CA found, generating certificate and key")
tlsCert, err := generateCA()
if err != nil {
log.Fatal("Unable to generate CA certificate and key", err)
}
setGoproxyCA(tlsCert)
}
}
func generateCA() (tls.Certificate, error) {
csr := cfsr.CertificateRequest{
CN: "tlsproxy CA",
KeyRequest: cfsr.NewKeyRequest(),
}
certPEM, _, keyPEM, err := initca.New(&csr)
if err != nil {
return tls.Certificate{}, err
}
caOut, err := os.Create(Flags.cert)
if err != nil {
return tls.Certificate{}, err
}
defer caOut.Close()
_, err = caOut.Write(certPEM)
if err != nil {
return tls.Certificate{}, err
}
keyOut, err := os.OpenFile(Flags.key, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return tls.Certificate{}, err
}
defer keyOut.Close()
_, err = keyOut.Write(keyPEM)
if err != nil {
return tls.Certificate{}, err
}
return tls.X509KeyPair(certPEM, keyPEM)
}