-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCertificate.go
361 lines (321 loc) · 10.1 KB
/
Certificate.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
package libICP
import (
"encoding/pem"
"io/ioutil"
"reflect"
"sync"
"time"
"github.com/OpenICP-BR/asn1"
"github.com/LK4D4/trylock"
)
type Certificate struct {
base certificate_pack
Serial string
Subject string
SubjectMap map[string]string
Issuer string
IssuerMap map[string]string
NotBefore time.Time
NotAfter time.Time
SubjectKeyId string
AuthorityKeyId string
FingerPrintAlg string
FingerPrint []byte
FingerPrintHuman string
ext_key_usage ext_key_usage
ext_basic_constraints ext_basic_constraints
ext_crl_distribution_points ext_crl_distribution_points
// This is the crl published by this certificate, not the crl about this certificate
crl certificate_list
// These are calculated based on the CRL made by this cert issuer
CRL_LastUpdate time.Time
CRL_NextUpdate time.Time
CRL_Status CRLStatus
CRL_LastCheck time.Time
CRL_LastError CodedError
crl_lock *trylock.Mutex
}
// Accepts PEM, DER and a mix of both.
func NewCertificateFromFile(path string) ([]*Certificate, []CodedError) {
dat, err := ioutil.ReadFile(path)
if err != nil {
merr := NewMultiError("failed to read certificate file", ERR_READ_FILE, nil, err)
merr.SetParam("path", path)
return nil, []CodedError{merr}
}
return NewCertificateFromBytes(dat)
}
// Accepts PEM, DER and a mix of both.
func NewCertificateFromBytes(raw []byte) ([]*Certificate, []CodedError) {
var block *pem.Block
certs := make([]*Certificate, 0)
merrs := make([]CodedError, 0)
// Try decoding all certificate PEM blocks
rest := raw
for {
block, rest = pem.Decode(rest)
if block == nil {
break
}
if block.Type == "CERTIFICATE" {
new_cert := Certificate{}
new_cert.init()
_, merr := new_cert.load_from_der(block.Bytes)
certs = append(certs, &new_cert)
merrs = append(merrs, merr)
}
}
// Try decoding the rest as DER certificates
for {
var merr CodedError
// Finished reading file?
if rest == nil || len(rest) < 42 {
break
}
new_cert := Certificate{}
new_cert.init()
rest, merr = new_cert.load_from_der(rest)
certs = append(certs, &new_cert)
merrs = append(merrs, merr)
}
// Avoid returining an array of nils.
for _, merr := range merrs {
if merr != nil {
return certs, merrs
}
}
return certs, nil
}
// Accepts PEM, DER and a mix of both.
func new_CRL_from_file(path string) ([]certificate_list, []CodedError) {
dat, err := ioutil.ReadFile(path)
if err != nil {
merr := NewMultiError("failed to read CRL file", ERR_READ_FILE, nil, err)
merr.SetParam("path", path)
return nil, []CodedError{merr}
}
return new_CRL_from_bytes(dat)
}
// Accepts PEM, DER and a mix of both.
func new_CRL_from_bytes(raw []byte) ([]certificate_list, []CodedError) {
var block *pem.Block
crls := make([]certificate_list, 0)
merrs := make([]CodedError, 0)
// Try decoding all CRLs PEM blocks
rest := raw
for {
block, rest = pem.Decode(rest)
if block == nil {
break
}
if block.Type == "X509 CRL" {
new_crl := certificate_list{}
_, merr := new_crl.LoadFromDER(block.Bytes)
crls = append(crls, new_crl)
merrs = append(merrs, merr)
}
}
// Try decoding the rest as DER CRL
for {
var merr CodedError
// Finished reading file?
if rest == nil || len(rest) < 42 {
break
}
new_crl := certificate_list{}
rest, merr = new_crl.LoadFromDER(rest)
crls = append(crls, new_crl)
merrs = append(merrs, merr)
}
// Avoid returining an array of nils.
for _, merr := range merrs {
if merr != nil {
return crls, merrs
}
}
return crls, nil
}
func (cert *Certificate) load_from_der(data []byte) ([]byte, CodedError) {
rest, err := asn1.Unmarshal(data, &cert.base)
if err != nil {
merr := NewMultiError("failed to parse DER certificate", ERR_PARSE_CERT, nil, err)
merr.SetParam("raw-data", data)
return rest, merr
}
if cerr := cert.finish_parsing(); cerr != nil {
return rest, cerr
}
return rest, nil
}
func (cert *Certificate) init() {
if cert.crl_lock == nil {
cert.crl_lock = new(trylock.Mutex)
}
}
// func (cert Certificate) ValidFor(usage CERT_USAGE) CodedError {
// }
func (cert Certificate) is_crl_outdated() bool {
now := time.Now()
return now.After(cert.CRL_NextUpdate) && !cert.CRL_NextUpdate.IsZero()
}
// Returns true if the subject is equal to the issuer.
func (cert Certificate) IsSelfSigned() bool {
eq := reflect.DeepEqual(cert.SubjectMap, cert.IssuerMap)
if eq || cert.SubjectKeyId == cert.AuthorityKeyId {
return true
}
return false
}
// Returns true if this certificate is a certificate authority. This is checked via the following extensions: key usage and basic constraints extension. (see RFC 5280 Section 4.2.1.3 and Section 4.2.1.9, respectively)
func (cert Certificate) IsCA() bool {
return cert.ext_key_usage.Exists && cert.ext_key_usage.KeyCertSign && cert.ext_basic_constraints.Exists && cert.ext_basic_constraints.CA
}
// This checks ONLY the digital signature and if the issuer is a CA (via the BasicConstraints and KeyUsage extensions). It will fail if any of those two extensions are not present.
//
// Possible errors are: ERR_UNKOWN_ALGORITHM, ERR_NOT_CA, ERR_PARSE_RSA_PUBKEY, ERR_BAD_SIGNATURE
func (cert Certificate) verify_signed_by(issuer Certificate) []CodedError {
ans_errs := make([]CodedError, 0)
// Check CA permission from issuer
if !issuer.ext_key_usage.Exists || !issuer.ext_key_usage.KeyCertSign {
merr := NewMultiError("issuer is not a certificate authority (Key Usage extension)", ERR_NOT_CA, nil)
merr.SetParam("issuer.Subject", issuer.Subject)
ans_errs = append(ans_errs, merr)
}
if !issuer.ext_basic_constraints.Exists || !issuer.ext_basic_constraints.CA {
merr := NewMultiError("issuer is not a certificate authority (Basic Constraints extension)", ERR_NOT_CA, nil)
merr.SetParam("issuer.Subject", issuer.Subject)
ans_errs = append(ans_errs, merr)
}
// Get key
pubkey, err := issuer.base.TBSCertificate.SubjectPublicKeyInfo.RSAPubKey()
if err != nil {
ans_errs = append(ans_errs, NewMultiError("failed to RSA parse public key", ERR_PARSE_RSA_PUBKEY, nil, err))
}
if len(ans_errs) > 0 {
return ans_errs
}
// Verify signature
cerr := VerifySignaure(cert.base, pubkey)
if err == nil {
return nil
}
return []CodedError{cerr}
}
func (cert *Certificate) setCRL(crl certificate_list) {
cert.crl = crl
cert.CRL_LastCheck = cert.crl.TBSCertList.ThisUpdate
cert.CRL_NextUpdate = cert.crl.TBSCertList.NextUpdate
}
func (cert *Certificate) finish_parsing() CodedError {
cert.Serial = "0x" + cert.base.TBSCertificate.SerialNumber.Text(16)
cert.Subject = cert.base.TBSCertificate.Subject.String()
cert.SubjectMap = cert.base.TBSCertificate.Subject.Map()
cert.Issuer = cert.base.TBSCertificate.Issuer.String()
cert.IssuerMap = cert.base.TBSCertificate.Issuer.Map()
cert.NotBefore = cert.base.TBSCertificate.Validity.NotBeforeTime
cert.NotAfter = cert.base.TBSCertificate.Validity.NotAfterTime
hasher, hash_alg, merr := get_hasher(cert.base.GetSignatureAlgorithm())
if merr != nil {
return merr
}
cert.FingerPrintAlg = hash2name(hash_alg)
cert.FingerPrint = run_hash(hasher, cert.base.GetRawContent())
cert.FingerPrintHuman = hash2name(hash_alg) + " = " + nice_hex(cert.FingerPrint)
return cert.parse_extensions()
}
func (cert *Certificate) parse_extensions() CodedError {
for _, ext := range cert.base.TBSCertificate.Extensions {
id := ext.ExtnID
switch {
case id.Equal(idSubjectKeyIdentifier):
ext_key_id := ext_subject_key_id{}
if err := ext_key_id.FromExtension(ext); err != nil {
return err
}
cert.SubjectKeyId = nice_hex(ext_key_id.KeyId)
case id.Equal(idAuthorityKeyIdentifier):
ext_key_id := ext_authority_key_id{}
if err := ext_key_id.FromExtension(ext); err != nil {
return err
}
cert.AuthorityKeyId = nice_hex(ext_key_id.KeyId)
case id.Equal(idCeBasicConstraints):
if err := cert.ext_basic_constraints.FromExtension(ext); err != nil {
return err
}
case id.Equal(idCeKeyUsage):
if err := cert.ext_key_usage.FromExtension(ext); err != nil {
return err
}
case id.Equal(idCeCRLDistributionPoint):
if err := cert.ext_crl_distribution_points.FromExtension(ext); err != nil {
return err
}
default:
if ext.Critical {
merr := NewMultiError("unsupported critical extension", ERR_UNSUPORTED_CRITICAL_EXTENSION, nil)
merr.SetParam("extension id", id)
return merr
}
}
}
return nil
}
func (cert *Certificate) check_against_issuer_crl(issuer *Certificate) {
cert.CRL_LastCheck = issuer.crl.TBSCertList.ThisUpdate
if issuer.CRL_LastError != nil || cert.CRL_LastCheck.IsZero() {
cert.CRL_Status = CRL_UNSURE_OR_NOT_FOUND
return
}
if issuer.crl_has_cert(*cert) {
cert.CRL_Status = CRL_REVOKED
} else {
cert.CRL_Status = CRL_NOT_REVOKED
}
}
func (cert Certificate) crl_has_cert(end_cert Certificate) bool {
return cert.crl.TBSCertList.HasCert(end_cert.base.TBSCertificate.SerialNumber)
}
func (cert *Certificate) process_CRL(new_crl certificate_list) CodedError {
// Verify signature
pubkey, err := cert.base.TBSCertificate.SubjectPublicKeyInfo.RSAPubKey()
if err != nil {
return NewMultiError("failed to RSA parse public key", ERR_PARSE_RSA_PUBKEY, nil, err)
}
cerr := VerifySignaure(new_crl, pubkey)
if cerr != nil {
return cerr
}
// Check for critical extensions
if ext := cert.crl.TBSCertList.HasCriticalExtension(); ext != nil {
merr := NewMultiError("unsupported critical extension on CRL", ERR_UNSUPORTED_CRITICAL_EXTENSION, nil)
merr.SetParam("ExtnId", ext)
return merr
}
cert.setCRL(new_crl)
return nil
}
func (cert *Certificate) download_crl(wg *sync.WaitGroup) {
if !cert.crl_lock.TryLock() {
wg.Done()
return
}
defer cert.crl_lock.Unlock()
var last_error CodedError
for _, url := range cert.ext_crl_distribution_points.URLs {
var buf []byte
buf, _, last_error = http_get(url)
if last_error != nil {
continue
}
crls, _ := new_CRL_from_bytes(buf)
for _, crl := range crls {
last_error = cert.process_CRL(crl)
if last_error == nil {
break
}
}
}
cert.CRL_LastError = last_error
wg.Done()
}