forked from micromdm/scep
/
depot.go
400 lines (353 loc) · 9.67 KB
/
depot.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package file
import (
"bufio"
"bytes"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io"
"io/ioutil"
"math/big"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
// NewFileDepot returns a new cert depot.
func NewFileDepot(path string) (*fileDepot, error) {
f, err := os.OpenFile(fmt.Sprintf("%s/index.txt", path),
os.O_RDONLY|os.O_CREATE, 0666)
if err != nil {
return nil, err
}
defer f.Close()
return &fileDepot{dirPath: path}, nil
}
type fileDepot struct {
dirPath string
}
func (d *fileDepot) CA(pass []byte) ([]*x509.Certificate, *rsa.PrivateKey, error) {
caPEM, err := d.getFile("ca.pem")
if err != nil {
return nil, nil, err
}
cert, err := loadCert(caPEM.Data)
if err != nil {
return nil, nil, err
}
keyPEM, err := d.getFile("ca.key")
if err != nil {
return nil, nil, err
}
key, err := loadKey(keyPEM.Data, pass)
if err != nil {
return nil, nil, err
}
return []*x509.Certificate{cert}, key, nil
}
// file permissions
const (
certPerm = 0444
serialPerm = 0400
dbPerm = 0600
)
// Put adds a certificate to the depot
func (d *fileDepot) Put(cn string, crt *x509.Certificate) error {
if crt == nil {
return errors.New("crt is nil")
}
if crt.Raw == nil {
return errors.New("data is nil")
}
data := crt.Raw
if err := os.MkdirAll(d.dirPath, 0755); err != nil {
return err
}
serial, err := d.Serial()
if err != nil {
return err
}
name := d.path(cn) + "." + serial.String() + ".pem"
file, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, certPerm)
if err != nil {
return err
}
defer file.Close()
if _, err := file.Write(pemCert(data)); err != nil {
os.Remove(name)
return err
}
if err := d.writeDB(cn, serial, cn+"."+serial.String()+".pem", crt); err != nil {
// TODO : remove certificate in case of writeDB problems
return err
}
if err := d.incrementSerial(serial); err != nil {
return err
}
return nil
}
func (d *fileDepot) Serial() (*big.Int, error) {
name := d.path("serial")
s := big.NewInt(2)
if err := d.check("serial"); err != nil {
// assuming it doesnt exist, create
if err := d.writeSerial(s); err != nil {
return nil, err
}
return s, nil
}
file, err := os.Open(name)
if err != nil {
return nil, err
}
defer file.Close()
r := bufio.NewReader(file)
data, err := r.ReadString('\r')
if err != nil && err != io.EOF {
return nil, err
}
data = strings.TrimSuffix(data, "\r")
data = strings.TrimSuffix(data, "\n")
serial, ok := s.SetString(data, 16)
if !ok {
return nil, errors.New("could not convert " + string(data) + " to serial number")
}
return serial, nil
}
func makeOpenSSLTime(t time.Time) string {
y := (int(t.Year()) % 100)
validDate := fmt.Sprintf("%02d%02d%02d%02d%02d%02dZ", y, t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
return validDate
}
func makeDn(cert *x509.Certificate) string {
var dn bytes.Buffer
if len(cert.Subject.Country) > 0 && len(cert.Subject.Country[0]) > 0 {
dn.WriteString("/C=" + cert.Subject.Country[0])
}
if len(cert.Subject.Province) > 0 && len(cert.Subject.Province[0]) > 0 {
dn.WriteString("/ST=" + cert.Subject.Province[0])
}
if len(cert.Subject.Locality) > 0 && len(cert.Subject.Locality[0]) > 0 {
dn.WriteString("/L=" + cert.Subject.Locality[0])
}
if len(cert.Subject.Organization) > 0 && len(cert.Subject.Organization[0]) > 0 {
dn.WriteString("/O=" + cert.Subject.Organization[0])
}
if len(cert.Subject.OrganizationalUnit) > 0 && len(cert.Subject.OrganizationalUnit[0]) > 0 {
dn.WriteString("/OU=" + cert.Subject.OrganizationalUnit[0])
}
if len(cert.Subject.CommonName) > 0 {
dn.WriteString("/CN=" + cert.Subject.CommonName)
}
if len(cert.EmailAddresses) > 0 {
dn.WriteString("/emailAddress=" + cert.EmailAddresses[0])
}
return dn.String()
}
// Determine if the cadb already has a valid certificate with the same name
func (d *fileDepot) HasCN(cn string, allowTime int, cert *x509.Certificate, revokeOldCertificate bool) error {
var addDB bytes.Buffer
var candidates map[string]string
candidates = make(map[string]string)
dn := makeDn(cert)
if err := os.MkdirAll(d.dirPath, 0755); err != nil {
return err
}
name := d.path("index.txt")
file, err := os.Open(name)
if err != nil {
return err
}
defer file.Close()
// Loop over index.txt, determine if a certificate is valid and can be revoked
// revoke certificate in DB if requested
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if strings.HasSuffix(line, dn) {
// Removing revoked certificate from candidates, if any
if strings.HasPrefix(line, "R\t") {
entries := strings.Split(line, "\t")
serial := strings.ToUpper(entries[3])
candidates[serial] = line
delete(candidates, serial)
addDB.WriteString(line + "\n")
// Test & add certificate candidates, if any
} else if strings.HasPrefix(line, "V\t") {
issueDate, err := strconv.Atoi(strings.Replace(strings.Split(line, "\t")[1], "Z", "", 1))
if err != nil {
return errors.New("Could not get expiry date from ca db")
}
minimalRenewDate, err := strconv.Atoi(strings.Replace(makeOpenSSLTime(time.Now().AddDate(0, 0, allowTime).UTC()), "Z", "", 1))
if err != nil {
return errors.New("Could not calculate expiry date")
}
entries := strings.Split(line, "\t")
serial := strings.ToUpper(entries[3])
// all non renewable certificates
if minimalRenewDate < issueDate && allowTime > 0 {
candidates[serial] = "no"
} else {
candidates[serial] = line
}
}
} else {
addDB.WriteString(line + "\n")
}
}
file.Close()
for key, value := range candidates {
if value == "no" {
return errors.New("DN " + dn + " already exists")
}
if revokeOldCertificate {
fmt.Println("Revoking certificate with serial " + key + " from DB. Recreation of CRL needed.")
entries := strings.Split(value, "\t")
addDB.WriteString("R\t" + entries[1] + "\t" + makeOpenSSLTime(time.Now()) + "\t" + strings.ToUpper(entries[3]) + "\t" + entries[4] + "\t" + entries[5] + "\n")
}
}
if err := scanner.Err(); err != nil {
return err
}
if revokeOldCertificate {
file, err := os.OpenFile(name, os.O_CREATE|os.O_RDWR, dbPerm)
if err != nil {
return err
}
if _, err := file.Write(addDB.Bytes()); err != nil {
return err
}
}
return nil
}
func (d *fileDepot) writeDB(cn string, serial *big.Int, filename string, cert *x509.Certificate) error {
var dbEntry bytes.Buffer
// Revoke old certificate
if err := d.HasCN(cn, 0, cert, true); err != nil {
return err
}
if err := os.MkdirAll(d.dirPath, 0755); err != nil {
return err
}
name := d.path("index.txt")
file, err := os.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_APPEND, dbPerm)
if err != nil {
return fmt.Errorf("could not append to "+name+" : %q\n", err.Error())
}
defer file.Close()
// Format of the caDB, see http://pki-tutorial.readthedocs.io/en/latest/cadb.html
// STATUSFLAG EXPIRATIONDATE REVOCATIONDATE(or emtpy) SERIAL_IN_HEX CERTFILENAME_OR_'unknown' Certificate_DN
serialHex := strings.ToUpper(fmt.Sprintf("%x", cert.SerialNumber))
validDate := makeOpenSSLTime(cert.NotAfter)
dn := makeDn(cert)
// Valid
dbEntry.WriteString("V\t")
// Valid till
dbEntry.WriteString(validDate + "\t")
// Empty (not revoked)
dbEntry.WriteString("\t")
// Serial in Hex
dbEntry.WriteString(serialHex + "\t")
// Certificate file name
dbEntry.WriteString(filename + "\t")
// Certificate DN
dbEntry.WriteString(dn)
dbEntry.WriteString("\n")
if _, err := file.Write(dbEntry.Bytes()); err != nil {
return err
}
return nil
}
func (d *fileDepot) writeSerial(serial *big.Int) error {
if err := os.MkdirAll(d.dirPath, 0755); err != nil {
return err
}
name := d.path("serial")
os.Remove(name)
file, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, serialPerm)
if err != nil {
return err
}
defer file.Close()
if _, err := file.WriteString(fmt.Sprintf("%x\n", serial.Bytes())); err != nil {
os.Remove(name)
return err
}
return nil
}
// read serial and increment
func (d *fileDepot) incrementSerial(s *big.Int) error {
serial := s.Add(s, big.NewInt(1))
if err := d.writeSerial(serial); err != nil {
return err
}
return nil
}
type file struct {
Info os.FileInfo
Data []byte
}
func (d *fileDepot) check(path string) error {
name := d.path(path)
_, err := os.Stat(name)
if err != nil {
return err
}
return nil
}
func (d *fileDepot) getFile(path string) (*file, error) {
if err := d.check(path); err != nil {
return nil, err
}
fi, err := os.Stat(d.path(path))
if err != nil {
return nil, err
}
b, err := ioutil.ReadFile(d.path(path))
return &file{fi, b}, err
}
func (d *fileDepot) path(name string) string {
return filepath.Join(d.dirPath, name)
}
const (
rsaPrivateKeyPEMBlockType = "RSA PRIVATE KEY"
certificatePEMBlockType = "CERTIFICATE"
)
// load an encrypted private key from disk
func loadKey(data []byte, password []byte) (*rsa.PrivateKey, error) {
pemBlock, _ := pem.Decode(data)
if pemBlock == nil {
return nil, errors.New("PEM decode failed")
}
if pemBlock.Type != rsaPrivateKeyPEMBlockType {
return nil, errors.New("unmatched type or headers")
}
b, err := x509.DecryptPEMBlock(pemBlock, password)
if err != nil {
return nil, err
}
return x509.ParsePKCS1PrivateKey(b)
}
// load an encrypted private key from disk
func loadCert(data []byte) (*x509.Certificate, error) {
pemBlock, _ := pem.Decode(data)
if pemBlock == nil {
return nil, errors.New("PEM decode failed")
}
if pemBlock.Type != certificatePEMBlockType {
return nil, errors.New("unmatched type or headers")
}
return x509.ParseCertificate(pemBlock.Bytes)
}
func pemCert(derBytes []byte) []byte {
pemBlock := &pem.Block{
Type: certificatePEMBlockType,
Headers: nil,
Bytes: derBytes,
}
out := pem.EncodeToMemory(pemBlock)
return out
}