forked from SSLMate/certspotter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
canonicalize.go
92 lines (85 loc) · 2.36 KB
/
canonicalize.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
// Copyright (C) 2019 Opsmate, Inc.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License, v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// This software is distributed WITHOUT A WARRANTY OF ANY KIND.
// See the Mozilla Public License for details.
package certspotter
import (
"encoding/asn1"
)
func canonicalizeRDNString(fromStr string) string {
from := []byte(fromStr)
to := []byte{}
inWhitespace := true
for _, ch := range from {
if ch == ' ' || ch == '\f' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\v' {
if !inWhitespace {
to = append(to, ' ')
}
inWhitespace = true
} else {
if ch >= 'A' && ch <= 'Z' {
to = append(to, ch+32) // convert to lowercase
} else {
to = append(to, ch)
}
inWhitespace = false
}
}
if inWhitespace && len(to) > 0 {
// whack off the space character that we appended
to = to[:len(to)-1]
}
return string(to)
}
func shouldCanonicalizeASN1String(value *asn1.RawValue) bool {
if !value.IsCompound && value.Class == 0 {
return value.Tag == 12 || value.Tag == 19 || value.Tag == 22 || value.Tag == 20 || value.Tag == 26 || value.Tag == 30 || value.Tag == 28
}
return false
}
func canonicalizeATV(oldATV AttributeTypeAndValue) (AttributeTypeAndValue, error) {
if shouldCanonicalizeASN1String(&oldATV.Value) {
str, err := decodeASN1String(&oldATV.Value)
if err != nil {
return AttributeTypeAndValue{}, err
}
str = canonicalizeRDNString(str)
return AttributeTypeAndValue{
Type: oldATV.Type,
Value: asn1.RawValue{
Class: 0,
Tag: asn1.TagUTF8String,
IsCompound: false,
Bytes: []byte(str),
},
}, nil
} else {
return oldATV, nil
}
}
func canonicalizeRDNSet(oldSet RelativeDistinguishedNameSET) (RelativeDistinguishedNameSET, error) {
newSet := make([]AttributeTypeAndValue, len(oldSet))
for i := range oldSet {
var err error
newSet[i], err = canonicalizeATV(oldSet[i])
if err != nil {
return nil, err
}
}
return newSet, nil
}
func CanonicalizeRDNSequence(oldSequence RDNSequence) (RDNSequence, error) {
newSequence := make([]RelativeDistinguishedNameSET, len(oldSequence))
for i := range oldSequence {
var err error
newSequence[i], err = canonicalizeRDNSet(oldSequence[i])
if err != nil {
return nil, err
}
}
return newSequence, nil
}