-
Notifications
You must be signed in to change notification settings - Fork 2k
/
sans.go
284 lines (261 loc) · 8.77 KB
/
sans.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
/*
Copyright 2023 The cert-manager Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pki
import (
"crypto/x509/pkix"
"encoding/asn1"
"errors"
"fmt"
"net"
"strconv"
)
// Copied from x509.go
var (
oidExtensionSubjectAltName = []int{2, 5, 29, 17}
)
// Based on RFC 5280, section 4.2.1.6
// see https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.6
/*
OtherName ::= SEQUENCE {
type-id OBJECT IDENTIFIER,
value [0] EXPLICIT ANY DEFINED BY type-id }
*/
type OtherName struct {
TypeID asn1.ObjectIdentifier
Value asn1.RawValue `asn1:"tag:0,explicit"`
}
// Based on RFC 5280, section 4.2.1.6
// see https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.6
/*
EDIPartyName ::= SEQUENCE {
nameAssigner [0] DirectoryString OPTIONAL,
partyName [1] DirectoryString }
*/
type EDIPartyName struct {
NameAssigner string `asn1:"tag:0,optional"`
PartyName string `asn1:"tag:1"`
}
// Based on RFC 5280, section 4.2.1.6
// see https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.6
/*
GeneralName ::= CHOICE {
otherName [0] OtherName,
rfc822Name [1] IA5String,
dnsName [2] IA5String,
x400Address [3] ORAddress,
directoryName [4] Name,
ediPartyName [5] EDIPartyName,
uniformResourceIdentifier [6] IA5String,
ipAddress [7] OCTET STRING,
registeredID [8] OBJECT IDENTIFIER }
*/
const (
nameTypeOtherName = 0
nameTypeRFC822Name = 1
nameTypeDNSName = 2
nameTypeX400Address = 3
nameTypeDirectoryName = 4
nameTypeEDIPartyName = 5
nameTypeUniformResourceIdentifier = 6
nameTypeIPAddress = 7
nameTypeRegisteredID = 8
)
type GeneralNames struct {
OtherNames []OtherName
RFC822Names []string
DNSNames []string
X400Addresses []asn1.RawValue
DirectoryNames []pkix.RDNSequence
EDIPartyNames []EDIPartyName
UniformResourceIdentifiers []string
IPAddresses []net.IP
RegisteredIDs []asn1.ObjectIdentifier
}
func (gns GeneralNames) Empty() bool {
return len(gns.OtherNames) == 0 &&
len(gns.RFC822Names) == 0 &&
len(gns.DNSNames) == 0 &&
len(gns.X400Addresses) == 0 &&
len(gns.DirectoryNames) == 0 &&
len(gns.EDIPartyNames) == 0 &&
len(gns.UniformResourceIdentifiers) == 0 &&
len(gns.IPAddresses) == 0 &&
len(gns.RegisteredIDs) == 0
}
// adapted from https://cs.opensource.google/go/go/+/master:src/crypto/x509/parser.go;l=373-416;drc=16d3040a84be821d801b75bd1a3d8ab4cc89ee36
func UnmarshalSANs(value []byte) (GeneralNames, error) {
var gns GeneralNames
err := forEachSAN(value, func(v asn1.RawValue) error {
switch v.Tag {
case nameTypeOtherName:
var otherName OtherName
if _, err := asn1.UnmarshalWithParams(v.FullBytes, &otherName, fmt.Sprintf("tag:%d", nameTypeOtherName)); err != nil {
return err
}
gns.OtherNames = append(gns.OtherNames, otherName)
case nameTypeRFC822Name:
email := string(v.Bytes)
if err := isIA5String(email); err != nil {
return errors.New("x509: SAN rfc822Name is malformed")
}
gns.RFC822Names = append(gns.RFC822Names, email)
case nameTypeDNSName:
name := string(v.Bytes)
if err := isIA5String(name); err != nil {
return errors.New("x509: SAN dNSName is malformed")
}
gns.DNSNames = append(gns.DNSNames, string(name))
case nameTypeX400Address:
gns.X400Addresses = append(gns.X400Addresses, v)
case nameTypeDirectoryName:
var rdn pkix.RDNSequence
if _, err := asn1.UnmarshalWithParams(v.FullBytes, &rdn, fmt.Sprintf("tag:%d", nameTypeDirectoryName)); err != nil {
return err
}
gns.DirectoryNames = append(gns.DirectoryNames, rdn)
case nameTypeEDIPartyName:
var edipn EDIPartyName
if _, err := asn1.UnmarshalWithParams(v.FullBytes, &edipn, fmt.Sprintf("tag:%d", nameTypeEDIPartyName)); err != nil {
return err
}
gns.EDIPartyNames = append(gns.EDIPartyNames, edipn)
case nameTypeUniformResourceIdentifier:
uriStr := string(v.Bytes)
if err := isIA5String(uriStr); err != nil {
return errors.New("x509: SAN uniformResourceIdentifier is malformed")
}
gns.UniformResourceIdentifiers = append(gns.UniformResourceIdentifiers, uriStr)
case nameTypeIPAddress:
switch len(v.Bytes) {
case net.IPv4len, net.IPv6len:
gns.IPAddresses = append(gns.IPAddresses, v.Bytes)
default:
return errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(v.Bytes)))
}
case nameTypeRegisteredID:
var oid asn1.ObjectIdentifier
if _, err := asn1.UnmarshalWithParams(v.FullBytes, &oid, fmt.Sprintf("tag:%d", nameTypeRegisteredID)); err != nil {
return err
}
gns.RegisteredIDs = append(gns.RegisteredIDs, oid)
default:
return asn1.StructuralError{Msg: "bad SAN choice"}
}
return nil
})
return gns, err
}
func forEachSAN(extension []byte, callback func(v asn1.RawValue) error) error {
var seq asn1.RawValue
rest, err := asn1.Unmarshal(extension, &seq)
if err != nil {
return err
} else if len(rest) != 0 {
return fmt.Errorf("x509: trailing data after X.509 extension")
}
if !seq.IsCompound || seq.Tag != asn1.TagSequence || seq.Class != asn1.ClassUniversal {
return asn1.StructuralError{Msg: "bad SAN sequence"}
}
rest = seq.Bytes
for len(rest) > 0 {
var v asn1.RawValue
rest, err = asn1.Unmarshal(rest, &v)
if err != nil {
return err
}
if err := callback(v); err != nil {
return err
}
}
return nil
}
// adapted from https://cs.opensource.google/go/go/+/master:src/crypto/x509/x509.go;l=1059-1103;drc=e2d9574b14b3db044331da0c6fadeb62315c644a
// MarshalSANs marshals a list of addresses into a the contents of an X.509
// SubjectAlternativeName extension.
func MarshalSANs(gns GeneralNames, hasSubject bool) (pkix.Extension, error) {
var rawValues []asn1.RawValue
addMarshalable := func(tag int, val interface{}) error {
fullBytes, err := asn1.MarshalWithParams(val, fmt.Sprint("tag:", tag))
if err != nil {
return err
}
rawValues = append(rawValues, asn1.RawValue{FullBytes: fullBytes})
return nil
}
addIA5String := func(tag int, val string) error {
if err := isIA5String(val); err != nil {
return fmt.Errorf("x509: %q cannot be encoded as an IA5String", val)
}
rawValues = append(rawValues, asn1.RawValue{Tag: tag, Class: asn1.ClassContextSpecific, Bytes: []byte(val)})
return nil
}
// Maintain the order of the SANs as produced by the Go x509 library.
for _, val := range gns.DNSNames {
if err := addIA5String(nameTypeDNSName, val); err != nil {
return pkix.Extension{}, err
}
}
for _, val := range gns.RFC822Names {
if err := addIA5String(nameTypeRFC822Name, val); err != nil {
return pkix.Extension{}, err
}
}
for _, rawIP := range gns.IPAddresses {
// If possible, we always want to encode IPv4 addresses in 4 bytes.
ip := rawIP.To4()
if ip == nil {
ip = rawIP
}
rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIPAddress, Class: asn1.ClassContextSpecific, Bytes: ip})
}
for _, val := range gns.UniformResourceIdentifiers {
if err := addIA5String(nameTypeUniformResourceIdentifier, val); err != nil {
return pkix.Extension{}, err
}
}
// Add support for the remaining SAN types.
for _, val := range gns.OtherNames {
if err := addMarshalable(nameTypeOtherName, val); err != nil {
return pkix.Extension{}, err
}
}
for _, val := range gns.X400Addresses {
if err := addMarshalable(nameTypeX400Address, val); err != nil {
return pkix.Extension{}, err
}
}
for _, val := range gns.DirectoryNames {
if err := addMarshalable(nameTypeDirectoryName, val); err != nil {
return pkix.Extension{}, err
}
}
for _, val := range gns.EDIPartyNames {
if err := addMarshalable(nameTypeEDIPartyName, val); err != nil {
return pkix.Extension{}, err
}
}
for _, val := range gns.RegisteredIDs {
if err := addMarshalable(nameTypeRegisteredID, val); err != nil {
return pkix.Extension{}, err
}
}
byteValue, err := asn1.Marshal(rawValues)
if err != nil {
return pkix.Extension{}, err
}
return pkix.Extension{
Id: oidExtensionSubjectAltName,
Critical: !hasSubject,
Value: byteValue,
}, nil
}