Debian Codegraph @

utils.go

raw symbols SCIP
1 package main
2
3 import (
4 "bytes"
5 "crypto/sha1"
6 "crypto/x509"
7 "encoding/asn1"
8 "encoding/hex"
9 "regexp"
10 "strings"
11 )
12
13 // normalizeFingerprint converts a string fingerprint to hex, removing leading
14 // "0x", if present.
15 func normalizeFingerprint(sfpr string) []byte {
16 if len(sfpr) == 0 {
17 return nil
18 }
19
20 if strings.HasPrefix(sfpr, "0x") {
21 sfpr = sfpr[2:]
22 }
23
24 hfpr, err := hex.DecodeString(sfpr)
25 if err != nil {
26 return nil
27 }
28
29 return hfpr
30 }
31
32 // certHasFingerprint checks if the given certificate has the given fingerprint.
33 func certHasFingerprint(cert *x509.Certificate, fpr []byte) bool {
34 if len(fpr) == 0 {
35 return false
36 }
37
38 return bytes.HasSuffix(certFingerprint(cert), fpr)
39 }
40
41 // certHexFingerprint calculated the hex SHA1 fingerprint of a certificate.
42 func certHexFingerprint(cert *x509.Certificate) string {
43 return hex.EncodeToString(certFingerprint(cert))
44 }
45
46 // certFingerprint calculated the SHA1 fingerprint of a certificate.
47 func certFingerprint(cert *x509.Certificate) []byte {
48 if len(cert.Raw) == 0 {
49 return nil
50 }
51
52 fpr := sha1.Sum(cert.Raw)
53 return fpr[:]
54 }
55
56 // normalizeEmail attempts to extract an email address from a user-id string.
57 func normalizeEmail(email string) string {
58 name, _, email := parseUserID(email)
59
60 if len(email) > 0 {
61 return email
62 }
63
64 if strings.ContainsRune(name, '@') {
65 return name
66 }
67
68 return ""
69 }
70
71 var (
72 oidEmailAddress = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1}
73 oidCommonName = asn1.ObjectIdentifier{2, 5, 4, 3}
74 )
75
76 // certHasEmail checks if a certificate contains the given email address in its
77 // subject (CN/emailAddress) or SAN fields.
78 func certHasEmail(cert *x509.Certificate, email string) bool {
79 for _, other := range certEmails(cert) {
80 if other == email {
81 return true
82 }
83 }
84
85 return false
86 }
87
88 // borrowed from http://emailregex.com/
89 var emailRegexp = regexp.MustCompile(`(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)`)
90
91 // certEmails extracts email addresses from a certificate's subject
92 // (CN/emailAddress) and SAN extensions.
93 func certEmails(cert *x509.Certificate) []string {
94 // From SAN
95 emails := cert.EmailAddresses
96
97 // From CN and emailAddress fields in subject.
98 for _, name := range cert.Subject.Names {
99 if !name.Type.Equal(oidEmailAddress) && !name.Type.Equal(oidCommonName) {
100 continue
101 }
102
103 if email, isStr := name.Value.(string); isStr && emailRegexp.MatchString(email) {
104 emails = append(emails, email)
105 }
106 }
107
108 return emails
109 }