forked from zmap/zgrab
-
Notifications
You must be signed in to change notification settings - Fork 1
/
json.go
364 lines (322 loc) · 10.6 KB
/
json.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
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package x509
import (
"crypto/dsa"
"crypto/ecdsa"
"crypto/rsa"
"encoding/asn1"
"encoding/json"
"strings"
"time"
"github.com/asaskevich/govalidator"
"github.com/zmap/zgrab/ztools/keys"
"github.com/zmap/zgrab/ztools/x509/pkix"
)
type auxKeyUsage struct {
DigitalSignature bool `json:"digital_signature,omitempty"`
ContentCommitment bool `json:"content_commitment,omitempty"`
KeyEncipherment bool `json:"key_encipherment,omitempty"`
DataEncipherment bool `json:"data_encipherment,omitempty"`
KeyAgreement bool `json:"key_agreement,omitempty"`
CertificateSign bool `json:"certificate_sign,omitempty"`
CRLSign bool `json:"crl_sign,omitempty"`
EncipherOnly bool `json:"encipher_only,omitempty"`
DecipherOnly bool `json:"decipher_only,omitempty"`
Value uint32 `json:"value"`
}
// MarshalJSON implements the json.Marshaler interface
func (k KeyUsage) MarshalJSON() ([]byte, error) {
var enc auxKeyUsage
enc.Value = uint32(k)
if k&KeyUsageDigitalSignature > 0 {
enc.DigitalSignature = true
}
if k&KeyUsageContentCommitment > 0 {
enc.ContentCommitment = true
}
if k&KeyUsageKeyEncipherment > 0 {
enc.KeyEncipherment = true
}
if k&KeyUsageDataEncipherment > 0 {
enc.DataEncipherment = true
}
if k&KeyUsageKeyAgreement > 0 {
enc.KeyAgreement = true
}
if k&KeyUsageCertSign > 0 {
enc.CertificateSign = true
}
if k&KeyUsageCRLSign > 0 {
enc.CRLSign = true
}
if k&KeyUsageEncipherOnly > 0 {
enc.EncipherOnly = true
}
if k&KeyUsageDecipherOnly > 0 {
enc.DecipherOnly = true
}
return json.Marshal(&enc)
}
// UnmarshalJSON implements the json.Unmarshler interface
func (k *KeyUsage) UnmarshalJSON(b []byte) error {
var aux auxKeyUsage
if err := json.Unmarshal(b, &aux); err != nil {
return err
}
// TODO: validate the flags match
v := int(aux.Value)
*k = KeyUsage(v)
return nil
}
type auxSignatureAlgorithm struct {
Name string `json:"name,omitempty"`
OID pkix.AuxOID `json:"oid"`
}
// MarshalJSON implements the json.Marshaler interface
func (s *SignatureAlgorithm) MarshalJSON() ([]byte, error) {
aux := auxSignatureAlgorithm{
Name: s.String(),
}
for _, val := range signatureAlgorithmDetails {
if val.algo == *s {
aux.OID = make([]int, len(val.oid))
for idx := range val.oid {
aux.OID[idx] = val.oid[idx]
}
}
}
return json.Marshal(&aux)
}
// UnmarshalJSON implements the json.Unmarshler interface
func (s *SignatureAlgorithm) UnmarshalJSON(b []byte) error {
var aux auxSignatureAlgorithm
if err := json.Unmarshal(b, &aux); err != nil {
return err
}
*s = UnknownSignatureAlgorithm
oid := asn1.ObjectIdentifier(aux.OID.AsSlice())
for _, val := range signatureAlgorithmDetails {
if val.oid.Equal(oid) {
*s = val.algo
break
}
}
return nil
}
type auxPublicKeyAlgorithm struct {
Name string `json:"name,omitempty"`
OID pkix.AuxOID `json:"oid,omitempty"`
}
// MarshalJSON implements the json.Marshaler interface
func (p *PublicKeyAlgorithm) MarshalJSON() ([]byte, error) {
aux := auxPublicKeyAlgorithm{
Name: p.String(),
}
return json.Marshal(&aux)
}
// UnmarshalJSON implements the json.Unmarshaler interface
func (p *PublicKeyAlgorithm) UnmarshalJSON(b []byte) error {
var aux auxPublicKeyAlgorithm
if err := json.Unmarshal(b, &aux); err != nil {
return err
}
panic("unimplemented")
}
type auxValidity struct {
Start string `json:"start"`
End string `json:"end"`
ValidityPeriod int `json:"length"`
}
func (v *validity) MarshalJSON() ([]byte, error) {
aux := auxValidity{
Start: v.NotBefore.UTC().Format(time.RFC3339),
End: v.NotAfter.UTC().Format(time.RFC3339),
ValidityPeriod: int(v.NotAfter.Sub(v.NotBefore).Seconds()),
}
return json.Marshal(&aux)
}
func (v *validity) UnmarshalJSON(b []byte) error {
var aux auxValidity
if err := json.Unmarshal(b, &aux); err != nil {
return err
}
var err error
if v.NotBefore, err = time.Parse(time.RFC3339, aux.Start); err != nil {
return err
}
if v.NotAfter, err = time.Parse(time.RFC3339, aux.End); err != nil {
return err
}
return nil
}
type jsonSubjectKeyInfo struct {
KeyAlgorithm PublicKeyAlgorithm `json:"key_algorithm"`
RSAPublicKey *keys.RSAPublicKey `json:"rsa_public_key,omitempty"`
DSAPublicKey interface{} `json:"dsa_public_key,omitempty"`
ECDSAPublicKey interface{} `json:"ecdsa_public_key,omitempty"`
SPKIFingerprint CertificateFingerprint `json:"fingerprint_sha256"`
}
type jsonSignature struct {
SignatureAlgorithm SignatureAlgorithm `json:"signature_algorithm"`
Value []byte `json:"value"`
Valid bool `json:"valid"`
SelfSigned bool `json:"self_signed"`
}
type fullValidity struct {
validity
ValidityPeriod int
}
type jsonCertificate struct {
Version int `json:"version"`
SerialNumber string `json:"serial_number"`
SignatureAlgorithm SignatureAlgorithm `json:"signature_algorithm"`
Issuer pkix.Name `json:"issuer"`
IssuerDN string `json:"issuer_dn,omitempty"`
Validity fullValidity `json:"validity"`
Subject pkix.Name `json:"subject"`
SubjectDN string `json:"subject_dn,omitempty"`
SubjectKeyInfo jsonSubjectKeyInfo `json:"subject_key_info"`
Extensions *CertificateExtensions `json:"extensions,omitempty"`
UnknownExtensions UnknownCertificateExtensions `json:"unknown_extensions,omitempty"`
Signature jsonSignature `json:"signature"`
FingerprintMD5 CertificateFingerprint `json:"fingerprint_md5"`
FingerprintSHA1 CertificateFingerprint `json:"fingerprint_sha1"`
FingerprintSHA256 CertificateFingerprint `json:"fingerprint_sha256"`
FingerprintNoCT CertificateFingerprint `json:"tbs_noct_fingerprint"`
SPKISubjectFingerprint CertificateFingerprint `json:"spki_subject_fingerprint"`
TBSCertificateFingerprint CertificateFingerprint `json:"tbs_fingerprint"`
ValidationLevel CertValidationLevel `json:"validation_level"`
Names []string `json:"names,omitempty"`
Redacted bool `json:"redacted"`
}
func AddECDSAPublicKeyToKeyMap(keyMap map[string]interface{}, key *ecdsa.PublicKey) {
params := key.Params()
keyMap["p"] = params.P.Bytes()
keyMap["n"] = params.N.Bytes()
keyMap["b"] = params.B.Bytes()
keyMap["gx"] = params.Gx.Bytes()
keyMap["gy"] = params.Gy.Bytes()
keyMap["x"] = key.X.Bytes()
keyMap["y"] = key.Y.Bytes()
keyMap["curve"] = key.Curve.Params().Name
keyMap["length"] = key.Curve.Params().BitSize
}
func AddDSAPublicKeyToKeyMap(keyMap map[string]interface{}, key *dsa.PublicKey) {
keyMap["p"] = key.P.Bytes()
keyMap["q"] = key.Q.Bytes()
keyMap["g"] = key.G.Bytes()
keyMap["y"] = key.Y.Bytes()
}
func (c *Certificate) MarshalJSON() ([]byte, error) {
// Fill out the certificate
jc := new(jsonCertificate)
jc.Version = c.Version
jc.SerialNumber = c.SerialNumber.String()
jc.SignatureAlgorithm = c.SignatureAlgorithm
jc.Issuer = c.Issuer
jc.IssuerDN = c.Issuer.String()
jc.Validity.NotBefore = c.NotBefore
jc.Validity.NotAfter = c.NotAfter
jc.Validity.ValidityPeriod = c.ValidityPeriod
jc.Subject = c.Subject
jc.SubjectDN = c.Subject.String()
jc.SubjectKeyInfo.KeyAlgorithm = c.PublicKeyAlgorithm
if isValidName(c.Subject.CommonName) {
jc.Names = append(jc.Names, c.Subject.CommonName)
}
for _, name := range c.DNSNames {
if isValidName(name) {
jc.Names = append(jc.Names, name)
} else if !strings.Contains(name, ".") { //just a TLD
jc.Names = append(jc.Names, name)
}
}
for _, name := range c.URIs {
if govalidator.IsURL(name) {
jc.Names = append(jc.Names, name)
}
}
for _, name := range c.IPAddresses {
str := name.String()
if govalidator.IsURL(str) {
jc.Names = append(jc.Names, str)
}
}
jc.Names = purgeNameDuplicates(jc.Names)
jc.Redacted = false
for _, name := range jc.Names {
if strings.HasPrefix(name, "?") {
jc.Redacted = true
}
}
// Pull out the key
keyMap := make(map[string]interface{})
jc.SubjectKeyInfo.SPKIFingerprint = c.SPKIFingerprint
switch key := c.PublicKey.(type) {
case *rsa.PublicKey:
rsaKey := new(keys.RSAPublicKey)
rsaKey.PublicKey = key
jc.SubjectKeyInfo.RSAPublicKey = rsaKey
case *dsa.PublicKey:
AddDSAPublicKeyToKeyMap(keyMap, key)
jc.SubjectKeyInfo.DSAPublicKey = keyMap
case *ecdsa.PublicKey:
AddECDSAPublicKeyToKeyMap(keyMap, key)
jc.SubjectKeyInfo.ECDSAPublicKey = keyMap
case *AugmentedECDSA:
pub := key.Pub
keyMap["pub"] = key.Raw.Bytes
params := pub.Params()
keyMap["p"] = params.P.Bytes()
keyMap["n"] = params.N.Bytes()
keyMap["b"] = params.B.Bytes()
keyMap["gx"] = params.Gx.Bytes()
keyMap["gy"] = params.Gy.Bytes()
keyMap["x"] = pub.X.Bytes()
keyMap["y"] = pub.Y.Bytes()
keyMap["curve"] = pub.Curve.Params().Name
keyMap["length"] = pub.Curve.Params().BitSize
//keyMap["asn1_oid"] = c.SignatureAlgorithmOID.String()
jc.SubjectKeyInfo.ECDSAPublicKey = keyMap
}
jc.Extensions, jc.UnknownExtensions = c.jsonifyExtensions()
// TODO: Handle the fact this might not match
jc.Signature.SignatureAlgorithm = jc.SignatureAlgorithm
jc.Signature.Value = c.Signature
jc.Signature.Valid = c.validSignature
if c.Subject.CommonName == c.Issuer.CommonName {
jc.Signature.SelfSigned = true
}
jc.FingerprintMD5 = c.FingerprintMD5
jc.FingerprintSHA1 = c.FingerprintSHA1
jc.FingerprintSHA256 = c.FingerprintSHA256
jc.FingerprintNoCT = c.FingerprintNoCT
jc.SPKISubjectFingerprint = c.SPKISubjectFingerprint
jc.TBSCertificateFingerprint = c.TBSCertificateFingerprint
jc.ValidationLevel = c.ValidationLevel
return json.Marshal(jc)
}
func purgeNameDuplicates(names []string) (out []string) {
hashset := make(map[string]bool, len(names))
for _, name := range names {
if _, inc := hashset[name]; !inc {
hashset[name] = true
}
}
out = make([]string, 0, len(hashset))
for key, _ := range hashset {
out = append(out, key)
}
return
}
func isValidName(name string) (ret bool) {
// Check for wildcards and redacts, ignore malformed urls
if strings.HasPrefix(name, "?.") || strings.HasPrefix(name, "*.") {
ret = isValidName(name[2:])
} else {
ret = govalidator.IsURL(name)
}
return
}