Source file
src/crypto/x509/x509_test.go
1
2
3
4
5 package x509
6
7 import (
8 "bytes"
9 "crypto"
10 "crypto/dsa"
11 "crypto/ecdh"
12 "crypto/ecdsa"
13 "crypto/ed25519"
14 "crypto/elliptic"
15 "crypto/rand"
16 "crypto/rsa"
17 _ "crypto/sha256"
18 _ "crypto/sha512"
19 "crypto/x509/pkix"
20 "encoding/asn1"
21 "encoding/base64"
22 "encoding/gob"
23 "encoding/hex"
24 "encoding/pem"
25 "fmt"
26 "internal/testenv"
27 "io"
28 "math"
29 "math/big"
30 "net"
31 "net/url"
32 "os/exec"
33 "reflect"
34 "runtime"
35 "slices"
36 "strings"
37 "testing"
38 "time"
39 )
40
41 func TestParsePKCS1PrivateKey(t *testing.T) {
42 block, _ := pem.Decode([]byte(pemPrivateKey))
43 priv, err := ParsePKCS1PrivateKey(block.Bytes)
44 if err != nil {
45 t.Errorf("Failed to parse private key: %s", err)
46 return
47 }
48 if priv.PublicKey.N.Cmp(rsaPrivateKey.PublicKey.N) != 0 ||
49 priv.PublicKey.E != rsaPrivateKey.PublicKey.E ||
50 priv.D.Cmp(rsaPrivateKey.D) != 0 ||
51 priv.Primes[0].Cmp(rsaPrivateKey.Primes[0]) != 0 ||
52 priv.Primes[1].Cmp(rsaPrivateKey.Primes[1]) != 0 {
53 t.Errorf("got:%+v want:%+v", priv, rsaPrivateKey)
54 }
55
56
57
58 data := []byte("0\x16\x02\x00\x02\x02\u007f\x00\x02\x0200\x02\x0200\x02\x02\x00\x01\x02\x02\u007f\x00")
59 if _, err := ParsePKCS1PrivateKey(data); err == nil {
60 t.Errorf("parsing invalid private key did not result in an error")
61 }
62 }
63
64 func TestPKCS1MismatchPublicKeyFormat(t *testing.T) {
65
66 const pkixPublicKey = "30820122300d06092a864886f70d01010105000382010f003082010a0282010100dd5a0f37d3ca5232852ccc0e81eebec270e2f2c6c44c6231d852971a0aad00aa7399e9b9de444611083c59ea919a9d76c20a7be131a99045ec19a7bb452d647a72429e66b87e28be9e8187ed1d2a2a01ef3eb2360706bd873b07f2d1f1a72337aab5ec94e983e39107f52c480d404915e84d75a3db2cfd601726a128cb1d7f11492d4bdb53272e652276667220795c709b8a9b4af6489cbf48bb8173b8fb607c834a71b6e8bf2d6aab82af3c8ad7ce16d8dcf58373a6edc427f7484d09744d4c08f4e19ed07adbf6cb31243bc5d0d1145e77a08a6fc5efd208eca67d6abf2d6f38f58b6fdd7c28774fb0cc03fc4935c6e074842d2e1479d3d8787249258719f90203010001"
67 const errorContains = "use ParsePKIXPublicKey instead"
68 derBytes, _ := hex.DecodeString(pkixPublicKey)
69 _, err := ParsePKCS1PublicKey(derBytes)
70 if !strings.Contains(err.Error(), errorContains) {
71 t.Errorf("expected error containing %q, got %s", errorContains, err)
72 }
73 }
74
75 func TestMarshalInvalidPublicKey(t *testing.T) {
76 _, err := MarshalPKIXPublicKey(&ecdsa.PublicKey{})
77 if err == nil {
78 t.Errorf("expected error, got MarshalPKIXPublicKey success")
79 }
80 _, err = MarshalPKIXPublicKey(&ecdsa.PublicKey{
81 Curve: elliptic.P256(),
82 X: big.NewInt(1), Y: big.NewInt(2),
83 })
84 if err == nil {
85 t.Errorf("expected error, got MarshalPKIXPublicKey success")
86 }
87 }
88
89 func testParsePKIXPublicKey(t *testing.T, pemBytes string) (pub any) {
90 block, _ := pem.Decode([]byte(pemBytes))
91 pub, err := ParsePKIXPublicKey(block.Bytes)
92 if err != nil {
93 t.Fatalf("Failed to parse public key: %s", err)
94 }
95
96 pubBytes2, err := MarshalPKIXPublicKey(pub)
97 if err != nil {
98 t.Errorf("Failed to marshal public key for the second time: %s", err)
99 return
100 }
101 if !bytes.Equal(pubBytes2, block.Bytes) {
102 t.Errorf("Reserialization of public key didn't match. got %x, want %x", pubBytes2, block.Bytes)
103 }
104 return
105 }
106
107 func TestParsePKIXPublicKey(t *testing.T) {
108 t.Run("RSA", func(t *testing.T) {
109 pub := testParsePKIXPublicKey(t, pemPublicKey)
110 _, ok := pub.(*rsa.PublicKey)
111 if !ok {
112 t.Errorf("Value returned from ParsePKIXPublicKey was not an RSA public key")
113 }
114 })
115 t.Run("Ed25519", func(t *testing.T) {
116 pub := testParsePKIXPublicKey(t, pemEd25519Key)
117 _, ok := pub.(ed25519.PublicKey)
118 if !ok {
119 t.Errorf("Value returned from ParsePKIXPublicKey was not an Ed25519 public key")
120 }
121 })
122 t.Run("X25519", func(t *testing.T) {
123 pub := testParsePKIXPublicKey(t, pemX25519Key)
124 k, ok := pub.(*ecdh.PublicKey)
125 if !ok || k.Curve() != ecdh.X25519() {
126 t.Errorf("Value returned from ParsePKIXPublicKey was not an X25519 public key")
127 }
128 })
129 }
130
131 var pemPublicKey = `-----BEGIN PUBLIC KEY-----
132 MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3VoPN9PKUjKFLMwOge6+
133 wnDi8sbETGIx2FKXGgqtAKpzmem53kRGEQg8WeqRmp12wgp74TGpkEXsGae7RS1k
134 enJCnma4fii+noGH7R0qKgHvPrI2Bwa9hzsH8tHxpyM3qrXslOmD45EH9SxIDUBJ
135 FehNdaPbLP1gFyahKMsdfxFJLUvbUycuZSJ2ZnIgeVxwm4qbSvZInL9Iu4FzuPtg
136 fINKcbbovy1qq4KvPIrXzhbY3PWDc6btxCf3SE0JdE1MCPThntB62/bLMSQ7xdDR
137 FF53oIpvxe/SCOymfWq/LW849Ytv3Xwod0+wzAP8STXG4HSELS4UedPYeHJJJYcZ
138 +QIDAQAB
139 -----END PUBLIC KEY-----
140 `
141
142 var pemPrivateKey = testingKey(`
143 -----BEGIN RSA TESTING KEY-----
144 MIICXAIBAAKBgQCxoeCUW5KJxNPxMp+KmCxKLc1Zv9Ny+4CFqcUXVUYH69L3mQ7v
145 IWrJ9GBfcaA7BPQqUlWxWM+OCEQZH1EZNIuqRMNQVuIGCbz5UQ8w6tS0gcgdeGX7
146 J7jgCQ4RK3F/PuCM38QBLaHx988qG8NMc6VKErBjctCXFHQt14lerd5KpQIDAQAB
147 AoGAYrf6Hbk+mT5AI33k2Jt1kcweodBP7UkExkPxeuQzRVe0KVJw0EkcFhywKpr1
148 V5eLMrILWcJnpyHE5slWwtFHBG6a5fLaNtsBBtcAIfqTQ0Vfj5c6SzVaJv0Z5rOd
149 7gQF6isy3t3w9IF3We9wXQKzT6q5ypPGdm6fciKQ8RnzREkCQQDZwppKATqQ41/R
150 vhSj90fFifrGE6aVKC1hgSpxGQa4oIdsYYHwMzyhBmWW9Xv/R+fPyr8ZwPxp2c12
151 33QwOLPLAkEA0NNUb+z4ebVVHyvSwF5jhfJxigim+s49KuzJ1+A2RaSApGyBZiwS
152 rWvWkB471POAKUYt5ykIWVZ83zcceQiNTwJBAMJUFQZX5GDqWFc/zwGoKkeR49Yi
153 MTXIvf7Wmv6E++eFcnT461FlGAUHRV+bQQXGsItR/opIG7mGogIkVXa3E1MCQARX
154 AAA7eoZ9AEHflUeuLn9QJI/r0hyQQLEtrpwv6rDT1GCWaLII5HJ6NUFVf4TTcqxo
155 6vdM4QGKTJoO+SaCyP0CQFdpcxSAuzpFcKv0IlJ8XzS/cy+mweCMwyJ1PFEc4FX6
156 wg/HcAJWY60xZTJDFN+Qfx8ZQvBEin6c2/h+zZi5IVY=
157 -----END RSA TESTING KEY-----
158 `)
159
160
161 var pemEd25519Key = `
162 -----BEGIN PUBLIC KEY-----
163 MCowBQYDK2VwAyEAGb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE=
164 -----END PUBLIC KEY-----
165 `
166
167
168 var pemX25519Key = `
169 -----BEGIN PUBLIC KEY-----
170 MCowBQYDK2VuAyEA5yGXrH/6OzxuWEhEWS01/f4OP+Of3Yrddy6/J1kDTVM=
171 -----END PUBLIC KEY-----
172 `
173
174 func TestPKIXMismatchPublicKeyFormat(t *testing.T) {
175
176 const pkcs1PublicKey = "308201080282010100817cfed98bcaa2e2a57087451c7674e0c675686dc33ff1268b0c2a6ee0202dec710858ee1c31bdf5e7783582e8ca800be45f3275c6576adc35d98e26e95bb88ca5beb186f853b8745d88bc9102c5f38753bcda519fb05948d5c77ac429255ff8aaf27d9f45d1586e95e2e9ba8a7cb771b8a09dd8c8fed3f933fd9b439bc9f30c475953418ef25f71a2b6496f53d94d39ce850aa0cc75d445b5f5b4f4ee4db78ab197a9a8d8a852f44529a007ac0ac23d895928d60ba538b16b0b087a7f903ed29770e215019b77eaecc360f35f7ab11b6d735978795b2c4a74e5bdea4dc6594cd67ed752a108e666729a753ab36d6c4f606f8760f507e1765be8cd744007e629020103"
177 const errorContains = "use ParsePKCS1PublicKey instead"
178 derBytes, _ := hex.DecodeString(pkcs1PublicKey)
179 _, err := ParsePKIXPublicKey(derBytes)
180 if !strings.Contains(err.Error(), errorContains) {
181 t.Errorf("expected error containing %q, got %s", errorContains, err)
182 }
183 }
184
185 var testPrivateKey *rsa.PrivateKey
186
187 func init() {
188 block, _ := pem.Decode([]byte(pemPrivateKey))
189
190 var err error
191 if testPrivateKey, err = ParsePKCS1PrivateKey(block.Bytes); err != nil {
192 panic("Failed to parse private key: " + err.Error())
193 }
194 }
195
196 func bigFromString(s string) *big.Int {
197 ret := new(big.Int)
198 ret.SetString(s, 10)
199 return ret
200 }
201
202 func fromBase10(base10 string) *big.Int {
203 i := new(big.Int)
204 i.SetString(base10, 10)
205 return i
206 }
207
208 func bigFromHexString(s string) *big.Int {
209 ret := new(big.Int)
210 ret.SetString(s, 16)
211 return ret
212 }
213
214 var rsaPrivateKey = &rsa.PrivateKey{
215 PublicKey: rsa.PublicKey{
216 N: bigFromString("124737666279038955318614287965056875799409043964547386061640914307192830334599556034328900586693254156136128122194531292927142396093148164407300419162827624945636708870992355233833321488652786796134504707628792159725681555822420087112284637501705261187690946267527866880072856272532711620639179596808018872997"),
217 E: 65537,
218 },
219 D: bigFromString("69322600686866301945688231018559005300304807960033948687567105312977055197015197977971637657636780793670599180105424702854759606794705928621125408040473426339714144598640466128488132656829419518221592374964225347786430566310906679585739468938549035854760501049443920822523780156843263434219450229353270690889"),
220 Primes: []*big.Int{
221 bigFromString("11405025354575369741595561190164746858706645478381139288033759331174478411254205003127028642766986913445391069745480057674348716675323735886284176682955723"),
222 bigFromString("10937079261204603443118731009201819560867324167189758120988909645641782263430128449826989846631183550578761324239709121189827307416350485191350050332642639"),
223 },
224 }
225
226 func TestMarshalRSAPrivateKey(t *testing.T) {
227 priv := &rsa.PrivateKey{
228 PublicKey: rsa.PublicKey{
229 N: fromBase10("16346378922382193400538269749936049106320265317511766357599732575277382844051791096569333808598921852351577762718529818072849191122419410612033592401403764925096136759934497687765453905884149505175426053037420486697072448609022753683683718057795566811401938833367954642951433473337066311978821180526439641496973296037000052546108507805269279414789035461158073156772151892452251106173507240488993608650881929629163465099476849643165682709047462010581308719577053905787496296934240246311806555924593059995202856826239801816771116902778517096212527979497399966526283516447337775509777558018145573127308919204297111496233"),
230 E: 3,
231 },
232 D: fromBase10("10897585948254795600358846499957366070880176878341177571733155050184921896034527397712889205732614568234385175145686545381899460748279607074689061600935843283397424506622998458510302603922766336783617368686090042765718290914099334449154829375179958369993407724946186243249568928237086215759259909861748642124071874879861299389874230489928271621259294894142840428407196932444474088857746123104978617098858619445675532587787023228852383149557470077802718705420275739737958953794088728369933811184572620857678792001136676902250566845618813972833750098806496641114644760255910789397593428910198080271317419213080834885003"),
233 Primes: []*big.Int{
234 fromBase10("1025363189502892836833747188838978207017355117492483312747347695538428729137306368764177201532277413433182799108299960196606011786562992097313508180436744488171474690412562218914213688661311117337381958560443"),
235 fromBase10("3467903426626310123395340254094941045497208049900750380025518552334536945536837294961497712862519984786362199788654739924501424784631315081391467293694361474867825728031147665777546570788493758372218019373"),
236 fromBase10("4597024781409332673052708605078359346966325141767460991205742124888960305710298765592730135879076084498363772408626791576005136245060321874472727132746643162385746062759369754202494417496879741537284589047"),
237 },
238 }
239
240 derBytes := MarshalPKCS1PrivateKey(priv)
241
242 priv2, err := ParsePKCS1PrivateKey(derBytes)
243 if err != nil {
244 t.Errorf("error parsing serialized key: %s", err)
245 return
246 }
247 if priv.PublicKey.N.Cmp(priv2.PublicKey.N) != 0 ||
248 priv.PublicKey.E != priv2.PublicKey.E ||
249 priv.D.Cmp(priv2.D) != 0 ||
250 len(priv2.Primes) != 3 ||
251 priv.Primes[0].Cmp(priv2.Primes[0]) != 0 ||
252 priv.Primes[1].Cmp(priv2.Primes[1]) != 0 ||
253 priv.Primes[2].Cmp(priv2.Primes[2]) != 0 {
254 t.Errorf("got:%+v want:%+v", priv, priv2)
255 }
256 }
257
258 func TestMarshalRSAPublicKey(t *testing.T) {
259 pub := &rsa.PublicKey{
260 N: fromBase10("16346378922382193400538269749936049106320265317511766357599732575277382844051791096569333808598921852351577762718529818072849191122419410612033592401403764925096136759934497687765453905884149505175426053037420486697072448609022753683683718057795566811401938833367954642951433473337066311978821180526439641496973296037000052546108507805269279414789035461158073156772151892452251106173507240488993608650881929629163465099476849643165682709047462010581308719577053905787496296934240246311806555924593059995202856826239801816771116902778517096212527979497399966526283516447337775509777558018145573127308919204297111496233"),
261 E: 3,
262 }
263 derBytes := MarshalPKCS1PublicKey(pub)
264 pub2, err := ParsePKCS1PublicKey(derBytes)
265 if err != nil {
266 t.Errorf("ParsePKCS1PublicKey: %s", err)
267 }
268 if pub.N.Cmp(pub2.N) != 0 || pub.E != pub2.E {
269 t.Errorf("ParsePKCS1PublicKey = %+v, want %+v", pub, pub2)
270 }
271
272
273
274
275 derBytes2, err := asn1.Marshal(*pub)
276 if err != nil {
277 t.Errorf("Marshal(rsa.PublicKey): %v", err)
278 } else if !bytes.Equal(derBytes, derBytes2) {
279 t.Errorf("Marshal(rsa.PublicKey) = %x, want %x", derBytes2, derBytes)
280 }
281 pub3 := new(rsa.PublicKey)
282 rest, err := asn1.Unmarshal(derBytes, pub3)
283 if err != nil {
284 t.Errorf("Unmarshal(rsa.PublicKey): %v", err)
285 }
286 if len(rest) != 0 || pub.N.Cmp(pub3.N) != 0 || pub.E != pub3.E {
287 t.Errorf("Unmarshal(rsa.PublicKey) = %+v, %q want %+v, %q", pub, rest, pub2, []byte(nil))
288 }
289
290 publicKeys := []struct {
291 derBytes []byte
292 expectedErrSubstr string
293 }{
294 {
295 derBytes: []byte{
296 0x30, 6,
297 0x02, 1,
298 17,
299 0x02, 1,
300 3,
301 },
302 }, {
303 derBytes: []byte{
304 0x30, 6,
305 0x02, 1,
306 0xff,
307 0x02, 1,
308 3,
309 },
310 expectedErrSubstr: "zero or negative",
311 }, {
312 derBytes: []byte{
313 0x30, 6,
314 0x02, 1,
315 17,
316 0x02, 1,
317 0xff,
318 },
319 expectedErrSubstr: "zero or negative",
320 }, {
321 derBytes: []byte{
322 0x30, 6,
323 0x02, 1,
324 17,
325 0x02, 1,
326 3,
327 1,
328 },
329 expectedErrSubstr: "trailing data",
330 }, {
331 derBytes: []byte{
332 0x30, 9,
333 0x02, 1,
334 17,
335 0x02, 4,
336 0x7f, 0xff, 0xff, 0xff,
337 },
338 }, {
339 derBytes: []byte{
340 0x30, 10,
341 0x02, 1,
342 17,
343 0x02, 5,
344 0x00, 0x80, 0x00, 0x00, 0x00,
345 },
346
347
348
349
350
351 expectedErrSubstr: "large",
352 },
353 }
354
355 for i, test := range publicKeys {
356 shouldFail := len(test.expectedErrSubstr) > 0
357 pub, err := ParsePKCS1PublicKey(test.derBytes)
358 if shouldFail {
359 if err == nil {
360 t.Errorf("#%d: unexpected success, got %#v", i, pub)
361 } else if !strings.Contains(err.Error(), test.expectedErrSubstr) {
362 t.Errorf("#%d: expected error containing %q, got %s", i, test.expectedErrSubstr, err)
363 }
364 } else {
365 if err != nil {
366 t.Errorf("#%d: unexpected failure: %s", i, err)
367 continue
368 }
369 reserialized := MarshalPKCS1PublicKey(pub)
370 if !bytes.Equal(reserialized, test.derBytes) {
371 t.Errorf("#%d: failed to reserialize: got %x, expected %x", i, reserialized, test.derBytes)
372 }
373 }
374 }
375 }
376
377 type matchHostnamesTest struct {
378 pattern, host string
379 ok bool
380 }
381
382 var matchHostnamesTests = []matchHostnamesTest{
383 {"a.b.c", "a.b.c", true},
384 {"a.b.c", "b.b.c", false},
385 {"", "b.b.c", false},
386 {"a.b.c", "", false},
387 {"example.com", "example.com", true},
388 {"example.com", "www.example.com", false},
389 {"*.example.com", "example.com", false},
390 {"*.example.com", "www.example.com", true},
391 {"*.example.com", "www.example.com.", true},
392 {"*.example.com", "xyz.www.example.com", false},
393 {"*.example.com", "https://www.example.com", false},
394 {"*.example..com", "www.example..com", false},
395 {"www.example..com", "www.example..com", true},
396 {"*.*.example.com", "xyz.www.example.com", false},
397 {"*.www.*.com", "xyz.www.example.com", false},
398 {"*bar.example.com", "foobar.example.com", false},
399 {"f*.example.com", "foobar.example.com", false},
400 {"www.example.com", "*.example.com", false},
401 {"", ".", false},
402 {".", "", false},
403 {".", ".", false},
404 {"example.com", "example.com.", true},
405 {"example.com.", "example.com", false},
406 {"example.com.", "example.com.", true},
407 {"*.com.", "example.com.", false},
408 {"*.com.", "example.com", false},
409 {"*.com", "example.com", true},
410 {"*.com", "example.com.", true},
411 {"foo:bar", "foo:bar", true},
412 {"*.foo:bar", "xxx.foo:bar", false},
413 {"*.2.3.4", "1.2.3.4", false},
414 {"*.2.3.4", "[1.2.3.4]", false},
415 {"*:4860:4860::8888", "2001:4860:4860::8888", false},
416 {"*:4860:4860::8888", "[2001:4860:4860::8888]", false},
417 {"2001:4860:4860::8888", "2001:4860:4860::8888", false},
418 {"2001:4860:4860::8888", "[2001:4860:4860::8888]", false},
419 {"[2001:4860:4860::8888]", "2001:4860:4860::8888", false},
420 {"[2001:4860:4860::8888]", "[2001:4860:4860::8888]", false},
421 }
422
423 func TestMatchHostnames(t *testing.T) {
424 for i, test := range matchHostnamesTests {
425 c := &Certificate{DNSNames: []string{test.pattern}}
426 r := c.VerifyHostname(test.host) == nil
427 if r != test.ok {
428 t.Errorf("#%d mismatch got: %t want: %t when matching '%s' against '%s'", i, r, test.ok, test.host, test.pattern)
429 }
430 }
431 }
432
433 func TestMatchIP(t *testing.T) {
434
435 c := &Certificate{
436 DNSNames: []string{"*.foo.bar.baz"},
437 Subject: pkix.Name{
438 CommonName: "*.foo.bar.baz",
439 },
440 }
441 err := c.VerifyHostname("quux.foo.bar.baz")
442 if err != nil {
443 t.Fatalf("VerifyHostname(quux.foo.bar.baz): %v", err)
444 }
445
446
447
448 c = &Certificate{
449 DNSNames: []string{"*.2.3.4"},
450 Subject: pkix.Name{
451 CommonName: "*.2.3.4",
452 },
453 }
454 err = c.VerifyHostname("1.2.3.4")
455 if err == nil {
456 t.Fatalf("VerifyHostname(1.2.3.4) should have failed, did not")
457 }
458
459 c = &Certificate{
460 IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
461 }
462 err = c.VerifyHostname("127.0.0.1")
463 if err != nil {
464 t.Fatalf("VerifyHostname(127.0.0.1): %v", err)
465 }
466 err = c.VerifyHostname("::1")
467 if err != nil {
468 t.Fatalf("VerifyHostname(::1): %v", err)
469 }
470 err = c.VerifyHostname("[::1]")
471 if err != nil {
472 t.Fatalf("VerifyHostname([::1]): %v", err)
473 }
474 }
475
476 func TestCertificateParse(t *testing.T) {
477 s, _ := base64.StdEncoding.DecodeString(certBytes)
478 certs, err := ParseCertificates(s)
479 if err != nil {
480 t.Error(err)
481 }
482 if len(certs) != 2 {
483 t.Errorf("Wrong number of certs: got %d want 2", len(certs))
484 return
485 }
486
487 err = certs[0].CheckSignatureFrom(certs[1])
488 if err != nil {
489 t.Error(err)
490 }
491
492 if err := certs[0].VerifyHostname("mail.google.com"); err != nil {
493 t.Error(err)
494 }
495
496 const expectedExtensions = 10
497 if n := len(certs[0].Extensions); n != expectedExtensions {
498 t.Errorf("want %d extensions, got %d", expectedExtensions, n)
499 }
500 }
501
502 func TestCertificateEqualOnNil(t *testing.T) {
503 cNonNil := new(Certificate)
504 var cNil1, cNil2 *Certificate
505 if !cNil1.Equal(cNil2) {
506 t.Error("Nil certificates: cNil1 is not equal to cNil2")
507 }
508 if !cNil2.Equal(cNil1) {
509 t.Error("Nil certificates: cNil2 is not equal to cNil1")
510 }
511 if cNil1.Equal(cNonNil) {
512 t.Error("Unexpectedly cNil1 is equal to cNonNil")
513 }
514 if cNonNil.Equal(cNil1) {
515 t.Error("Unexpectedly cNonNil is equal to cNil1")
516 }
517 }
518
519 func TestMismatchedSignatureAlgorithm(t *testing.T) {
520 der, _ := pem.Decode([]byte(rsaPSSSelfSignedPEM))
521 if der == nil {
522 t.Fatal("Failed to find PEM block")
523 }
524
525 cert, err := ParseCertificate(der.Bytes)
526 if err != nil {
527 t.Fatal(err)
528 }
529
530 if err = cert.CheckSignature(ECDSAWithSHA256, nil, nil); err == nil {
531 t.Fatal("CheckSignature unexpectedly return no error")
532 }
533
534 const expectedSubstring = " but have public key of type "
535 if !strings.Contains(err.Error(), expectedSubstring) {
536 t.Errorf("Expected error containing %q, but got %q", expectedSubstring, err)
537 }
538 }
539
540 var certBytes = "MIIE0jCCA7qgAwIBAgIQWcvS+TTB3GwCAAAAAGEAWzANBgkqhkiG9w0BAQsFADBCMQswCQYD" +
541 "VQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZpY2VzMRMwEQYDVQQDEwpHVFMg" +
542 "Q0EgMU8xMB4XDTIwMDQwMTEyNTg1NloXDTIwMDYyNDEyNTg1NlowaTELMAkGA1UEBhMCVVMx" +
543 "EzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDU1vdW50YWluIFZpZXcxEzARBgNVBAoT" +
544 "Ckdvb2dsZSBMTEMxGDAWBgNVBAMTD21haWwuZ29vZ2xlLmNvbTBZMBMGByqGSM49AgEGCCqG" +
545 "SM49AwEHA0IABO+dYiPnkFl+cZVf6mrWeNp0RhQcJSBGH+sEJxjvc+cYlW3QJCnm57qlpFdd" +
546 "pz3MPyVejvXQdM6iI1mEWP4C2OujggJmMIICYjAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0lBAww" +
547 "CgYIKwYBBQUHAwEwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUI6pZhnQ/lQgmPD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nMCUGCCsGAQUFBzABhhlodHRwOi8vb2NzcC5wa2kuZ29vZy9n" +
576 "c3IyMDIGA1UdHwQrMCkwJ6AloCOGIWh0dHA6Ly9jcmwucGtpLmdvb2cvZ3NyMi9nc3IyLmNy" +
577 "bDA/BgNVHSAEODA2MDQGBmeBDAECAjAqMCgGCCsGAQUFBwIBFhxodHRwczovL3BraS5nb29n" +
578 "L3JlcG9zaXRvcnkvMA0GCSqGSIb3DQEBCwUAA4IBAQAagD42efvzLqlGN31eVBY1rsdOCJn+" +
579 "vdE0aSZSZgc9CrpJy2L08RqO/BFPaJZMdCvTZ96yo6oFjYRNTCBlD6WW2g0W+Gw7228EI4hr" +
580 "OmzBYL1on3GO7i1YNAfw1VTphln9e14NIZT1jMmo+NjyrcwPGvOap6kEJ/mjybD/AnhrYbrH" +
581 "NSvoVvpPwxwM7bY8tEvq7czhPOzcDYzWPpvKQliLzBYhF0C8otZm79rEFVvNiaqbCSbnMtIN" +
582 "bmcgAlsQsJAJnAwfnq3YO+qh/GzoEFwIUhlRKnG7rHq13RXtK8kIKiyKtKYhq2P/11JJUNCJ" +
583 "t63yr/tQri/hlQ3zRq2dnPXK"
584
585 func parseCIDR(s string) *net.IPNet {
586 _, net, err := net.ParseCIDR(s)
587 if err != nil {
588 panic(err)
589 }
590 return net
591 }
592
593 func parseURI(s string) *url.URL {
594 uri, err := url.Parse(s)
595 if err != nil {
596 panic(err)
597 }
598 return uri
599 }
600
601 func TestCreateSelfSignedCertificate(t *testing.T) {
602 random := rand.Reader
603
604 ecdsaPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
605 if err != nil {
606 t.Fatalf("Failed to generate ECDSA key: %s", err)
607 }
608
609 ed25519Pub, ed25519Priv, err := ed25519.GenerateKey(random)
610 if err != nil {
611 t.Fatalf("Failed to generate Ed25519 key: %s", err)
612 }
613
614 tests := []struct {
615 name string
616 pub, priv any
617 checkSig bool
618 sigAlgo SignatureAlgorithm
619 }{
620 {"RSA/RSA", &testPrivateKey.PublicKey, testPrivateKey, true, SHA384WithRSA},
621 {"RSA/ECDSA", &testPrivateKey.PublicKey, ecdsaPriv, false, ECDSAWithSHA384},
622 {"ECDSA/RSA", &ecdsaPriv.PublicKey, testPrivateKey, false, SHA256WithRSA},
623 {"ECDSA/ECDSA", &ecdsaPriv.PublicKey, ecdsaPriv, true, ECDSAWithSHA256},
624 {"RSAPSS/RSAPSS", &testPrivateKey.PublicKey, testPrivateKey, true, SHA256WithRSAPSS},
625 {"ECDSA/RSAPSS", &ecdsaPriv.PublicKey, testPrivateKey, false, SHA256WithRSAPSS},
626 {"RSAPSS/ECDSA", &testPrivateKey.PublicKey, ecdsaPriv, false, ECDSAWithSHA384},
627 {"Ed25519", ed25519Pub, ed25519Priv, true, PureEd25519},
628 }
629
630 testExtKeyUsage := []ExtKeyUsage{ExtKeyUsageClientAuth, ExtKeyUsageServerAuth}
631 testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
632 extraExtensionData := []byte("extra extension")
633
634 for _, test := range tests {
635 commonName := "test.example.com"
636 template := Certificate{
637 SerialNumber: big.NewInt(1),
638 Subject: pkix.Name{
639 CommonName: commonName,
640 Organization: []string{"Σ Acme Co"},
641 Country: []string{"US"},
642 ExtraNames: []pkix.AttributeTypeAndValue{
643 {
644 Type: []int{2, 5, 4, 42},
645 Value: "Gopher",
646 },
647
648 {
649 Type: []int{2, 5, 4, 6},
650 Value: "NL",
651 },
652 },
653 },
654 NotBefore: time.Unix(1000, 0),
655 NotAfter: time.Unix(100000, 0),
656
657 SignatureAlgorithm: test.sigAlgo,
658
659 SubjectKeyId: []byte{1, 2, 3, 4},
660 KeyUsage: KeyUsageCertSign,
661
662 ExtKeyUsage: testExtKeyUsage,
663 UnknownExtKeyUsage: testUnknownExtKeyUsage,
664
665 BasicConstraintsValid: true,
666 IsCA: true,
667
668 OCSPServer: []string{"http://ocsp.example.com"},
669 IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},
670
671 DNSNames: []string{"test.example.com"},
672 EmailAddresses: []string{"gopher@golang.org"},
673 IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
674 URIs: []*url.URL{parseURI("https://foo.com/wibble#foo")},
675
676 PolicyIdentifiers: []asn1.ObjectIdentifier{[]int{1, 2, 3}},
677 Policies: []OID{mustNewOIDFromInts(t, []uint64{1, 2, 3, math.MaxUint32, math.MaxUint64})},
678 PermittedDNSDomains: []string{".example.com", "example.com"},
679 ExcludedDNSDomains: []string{"bar.example.com"},
680 PermittedIPRanges: []*net.IPNet{parseCIDR("192.168.1.1/16"), parseCIDR("1.2.3.4/8")},
681 ExcludedIPRanges: []*net.IPNet{parseCIDR("2001:db8::/48")},
682 PermittedEmailAddresses: []string{"foo@example.com"},
683 ExcludedEmailAddresses: []string{".example.com", "example.com"},
684 PermittedURIDomains: []string{".bar.com", "bar.com"},
685 ExcludedURIDomains: []string{".bar2.com", "bar2.com"},
686
687 CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},
688
689 ExtraExtensions: []pkix.Extension{
690 {
691 Id: []int{1, 2, 3, 4},
692 Value: extraExtensionData,
693 },
694
695 {
696 Id: oidExtensionSubjectKeyId,
697 Critical: false,
698 Value: []byte{0x04, 0x04, 4, 3, 2, 1},
699 },
700 },
701 }
702
703 derBytes, err := CreateCertificate(random, &template, &template, test.pub, test.priv)
704 if err != nil {
705 t.Errorf("%s: failed to create certificate: %s", test.name, err)
706 continue
707 }
708
709 cert, err := ParseCertificate(derBytes)
710 if err != nil {
711 t.Errorf("%s: failed to parse certificate: %s", test.name, err)
712 continue
713 }
714
715 if len(cert.PolicyIdentifiers) != 1 || !cert.PolicyIdentifiers[0].Equal(template.PolicyIdentifiers[0]) {
716 t.Errorf("%s: failed to parse policy identifiers: got:%#v want:%#v", test.name, cert.PolicyIdentifiers, template.PolicyIdentifiers)
717 }
718
719 if len(cert.PermittedDNSDomains) != 2 || cert.PermittedDNSDomains[0] != ".example.com" || cert.PermittedDNSDomains[1] != "example.com" {
720 t.Errorf("%s: failed to parse name constraints: %#v", test.name, cert.PermittedDNSDomains)
721 }
722
723 if len(cert.ExcludedDNSDomains) != 1 || cert.ExcludedDNSDomains[0] != "bar.example.com" {
724 t.Errorf("%s: failed to parse name constraint exclusions: %#v", test.name, cert.ExcludedDNSDomains)
725 }
726
727 if len(cert.PermittedIPRanges) != 2 || cert.PermittedIPRanges[0].String() != "192.168.0.0/16" || cert.PermittedIPRanges[1].String() != "1.0.0.0/8" {
728 t.Errorf("%s: failed to parse IP constraints: %#v", test.name, cert.PermittedIPRanges)
729 }
730
731 if len(cert.ExcludedIPRanges) != 1 || cert.ExcludedIPRanges[0].String() != "2001:db8::/48" {
732 t.Errorf("%s: failed to parse IP constraint exclusions: %#v", test.name, cert.ExcludedIPRanges)
733 }
734
735 if len(cert.PermittedEmailAddresses) != 1 || cert.PermittedEmailAddresses[0] != "foo@example.com" {
736 t.Errorf("%s: failed to parse permitted email addresses: %#v", test.name, cert.PermittedEmailAddresses)
737 }
738
739 if len(cert.ExcludedEmailAddresses) != 2 || cert.ExcludedEmailAddresses[0] != ".example.com" || cert.ExcludedEmailAddresses[1] != "example.com" {
740 t.Errorf("%s: failed to parse excluded email addresses: %#v", test.name, cert.ExcludedEmailAddresses)
741 }
742
743 if len(cert.PermittedURIDomains) != 2 || cert.PermittedURIDomains[0] != ".bar.com" || cert.PermittedURIDomains[1] != "bar.com" {
744 t.Errorf("%s: failed to parse permitted URIs: %#v", test.name, cert.PermittedURIDomains)
745 }
746
747 if len(cert.ExcludedURIDomains) != 2 || cert.ExcludedURIDomains[0] != ".bar2.com" || cert.ExcludedURIDomains[1] != "bar2.com" {
748 t.Errorf("%s: failed to parse excluded URIs: %#v", test.name, cert.ExcludedURIDomains)
749 }
750
751 if cert.Subject.CommonName != commonName {
752 t.Errorf("%s: subject wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Subject.CommonName, commonName)
753 }
754
755 if len(cert.Subject.Country) != 1 || cert.Subject.Country[0] != "NL" {
756 t.Errorf("%s: ExtraNames didn't override Country", test.name)
757 }
758
759 for _, ext := range cert.Extensions {
760 if ext.Id.Equal(oidExtensionSubjectAltName) {
761 if ext.Critical {
762 t.Fatal("SAN extension is marked critical")
763 }
764 }
765 }
766
767 found := false
768 for _, atv := range cert.Subject.Names {
769 if atv.Type.Equal([]int{2, 5, 4, 42}) {
770 found = true
771 break
772 }
773 }
774 if !found {
775 t.Errorf("%s: Names didn't contain oid 2.5.4.42 from ExtraNames", test.name)
776 }
777
778 if cert.Issuer.CommonName != commonName {
779 t.Errorf("%s: issuer wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Issuer.CommonName, commonName)
780 }
781
782 if cert.SignatureAlgorithm != test.sigAlgo {
783 t.Errorf("%s: SignatureAlgorithm wasn't copied from template. Got %v, want %v", test.name, cert.SignatureAlgorithm, test.sigAlgo)
784 }
785
786 if !slices.Equal(cert.ExtKeyUsage, testExtKeyUsage) {
787 t.Errorf("%s: extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.ExtKeyUsage, testExtKeyUsage)
788 }
789
790 if !slices.EqualFunc(cert.UnknownExtKeyUsage, testUnknownExtKeyUsage, asn1.ObjectIdentifier.Equal) {
791 t.Errorf("%s: unknown extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.UnknownExtKeyUsage, testUnknownExtKeyUsage)
792 }
793
794 if !slices.Equal(cert.OCSPServer, template.OCSPServer) {
795 t.Errorf("%s: OCSP servers differ from template. Got %v, want %v", test.name, cert.OCSPServer, template.OCSPServer)
796 }
797
798 if !slices.Equal(cert.IssuingCertificateURL, template.IssuingCertificateURL) {
799 t.Errorf("%s: Issuing certificate URLs differ from template. Got %v, want %v", test.name, cert.IssuingCertificateURL, template.IssuingCertificateURL)
800 }
801
802 if !slices.Equal(cert.DNSNames, template.DNSNames) {
803 t.Errorf("%s: SAN DNS names differ from template. Got %v, want %v", test.name, cert.DNSNames, template.DNSNames)
804 }
805
806 if !slices.Equal(cert.EmailAddresses, template.EmailAddresses) {
807 t.Errorf("%s: SAN emails differ from template. Got %v, want %v", test.name, cert.EmailAddresses, template.EmailAddresses)
808 }
809
810 if len(cert.URIs) != 1 || cert.URIs[0].String() != "https://foo.com/wibble#foo" {
811 t.Errorf("%s: URIs differ from template. Got %v, want %v", test.name, cert.URIs, template.URIs)
812 }
813
814 if !slices.EqualFunc(cert.IPAddresses, template.IPAddresses, net.IP.Equal) {
815 t.Errorf("%s: SAN IPs differ from template. Got %v, want %v", test.name, cert.IPAddresses, template.IPAddresses)
816 }
817
818 if !slices.Equal(cert.CRLDistributionPoints, template.CRLDistributionPoints) {
819 t.Errorf("%s: CRL distribution points differ from template. Got %v, want %v", test.name, cert.CRLDistributionPoints, template.CRLDistributionPoints)
820 }
821
822 if !bytes.Equal(cert.SubjectKeyId, []byte{4, 3, 2, 1}) {
823 t.Errorf("%s: ExtraExtensions didn't override SubjectKeyId", test.name)
824 }
825
826 if !bytes.Contains(derBytes, extraExtensionData) {
827 t.Errorf("%s: didn't find extra extension in DER output", test.name)
828 }
829
830 if test.checkSig {
831 err = cert.CheckSignatureFrom(cert)
832 if err != nil {
833 t.Errorf("%s: signature verification failed: %s", test.name, err)
834 }
835 }
836 }
837 }
838
839
840 var ecdsaSHA1CertPem = `
841 -----BEGIN CERTIFICATE-----
842 MIICDjCCAbUCCQDF6SfN0nsnrjAJBgcqhkjOPQQBMIGPMQswCQYDVQQGEwJVUzET
843 MBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEVMBMG
844 A1UECgwMR29vZ2xlLCBJbmMuMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
845 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIwMjAyMDUw
846 WhcNMjIwNTE4MjAyMDUwWjCBjzELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
847 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTATBgNVBAoMDEdvb2dsZSwg
848 SW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAhBgkqhkiG9w0BCQEWFGdv
849 bGFuZy1kZXZAZ21haWwuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE/Wgn
850 WQDo5+bz71T0327ERgd5SDDXFbXLpzIZDXTkjpe8QTEbsF+ezsQfrekrpDPC4Cd3
851 P9LY0tG+aI8IyVKdUjAJBgcqhkjOPQQBA0gAMEUCIGlsqMcRqWVIWTD6wXwe6Jk2
852 DKxL46r/FLgJYnzBEH99AiEA3fBouObsvV1R3oVkb4BQYnD4/4LeId6lAT43YvyV
853 a/A=
854 -----END CERTIFICATE-----
855 `
856
857
858 var ecdsaSHA256p256CertPem = `
859 -----BEGIN CERTIFICATE-----
860 MIICDzCCAbYCCQDlsuMWvgQzhTAKBggqhkjOPQQDAjCBjzELMAkGA1UEBhMCVVMx
861 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTAT
862 BgNVBAoMDEdvb2dsZSwgSW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAh
863 BgkqhkiG9w0BCQEWFGdvbGFuZy1kZXZAZ21haWwuY29tMB4XDTEyMDUyMTAwMTkx
864 NloXDTIyMDUxOTAwMTkxNlowgY8xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxp
865 Zm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MRUwEwYDVQQKDAxHb29nbGUs
866 IEluYy4xFzAVBgNVBAMMDnd3dy5nb29nbGUuY29tMSMwIQYJKoZIhvcNAQkBFhRn
867 b2xhbmctZGV2QGdtYWlsLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPMt
868 2ErhxAty5EJRu9yM+MTy+hUXm3pdW1ensAv382KoGExSXAFWP7pjJnNtHO+XSwVm
869 YNtqjcAGFKpweoN//kQwCgYIKoZIzj0EAwIDRwAwRAIgIYSaUA/IB81gjbIw/hUV
870 70twxJr5EcgOo0hLp3Jm+EYCIFDO3NNcgmURbJ1kfoS3N/0O+irUtoPw38YoNkqJ
871 h5wi
872 -----END CERTIFICATE-----
873 `
874
875
876 var ecdsaSHA256p384CertPem = `
877 -----BEGIN CERTIFICATE-----
878 MIICSjCCAdECCQDje/no7mXkVzAKBggqhkjOPQQDAjCBjjELMAkGA1UEBhMCVVMx
879 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
880 BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
881 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMDYxMDM0
882 WhcNMjIwNTE5MDYxMDM0WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
883 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
884 SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
885 YW5nLWRldkBnbWFpbC5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARRuzRNIKRK
886 jIktEmXanNmrTR/q/FaHXLhWRZ6nHWe26Fw7Rsrbk+VjGy4vfWtNn7xSFKrOu5ze
887 qxKnmE0h5E480MNgrUiRkaGO2GMJJVmxx20aqkXOk59U8yGA4CghE6MwCgYIKoZI
888 zj0EAwIDZwAwZAIwBZEN8gvmRmfeP/9C1PRLzODIY4JqWub2PLRT4mv9GU+yw3Gr
889 PU9A3CHMdEcdw/MEAjBBO1lId8KOCh9UZunsSMfqXiVurpzmhWd6VYZ/32G+M+Mh
890 3yILeYQzllt/g0rKVRk=
891 -----END CERTIFICATE-----
892 `
893
894
895 var ecdsaSHA384p521CertPem = `
896 -----BEGIN CERTIFICATE-----
897 MIICljCCAfcCCQDhp1AFD/ahKjAKBggqhkjOPQQDAzCBjjELMAkGA1UEBhMCVVMx
898 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
899 BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
900 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMTUwNDI5
901 WhcNMjIwNTE5MTUwNDI5WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
902 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
903 SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
904 YW5nLWRldkBnbWFpbC5jb20wgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACqx9Rv
905 IssRs1LWYcNN+WffwlHw4Tv3y8/LIAA9MF1ZScIonU9nRMxt4a2uGJVCPDw6JHpz
906 PaYc0E9puLoE9AfKpwFr59Jkot7dBg55SKPEFkddoip/rvmN7NPAWjMBirOwjOkm
907 8FPthvPhGPqsu9AvgVuHu3PosWiHGNrhh379pva8MzAKBggqhkjOPQQDAwOBjAAw
908 gYgCQgEHNmswkUdPpHqrVxp9PvLVl+xxPuHBkT+75z9JizyxtqykHQo9Uh6SWCYH
909 BF9KLolo01wMt8DjoYP5Fb3j5MH7xwJCAbWZzTOp4l4DPkIvAh4LeC4VWbwPPyqh
910 kBg71w/iEcSY3wUKgHGcJJrObZw7wys91I5kENljqw/Samdr3ka+jBJa
911 -----END CERTIFICATE-----
912 `
913
914 var ecdsaTests = []struct {
915 sigAlgo SignatureAlgorithm
916 pemCert string
917 }{
918 {ECDSAWithSHA256, ecdsaSHA256p256CertPem},
919 {ECDSAWithSHA256, ecdsaSHA256p384CertPem},
920 {ECDSAWithSHA384, ecdsaSHA384p521CertPem},
921 }
922
923 func TestECDSA(t *testing.T) {
924 for i, test := range ecdsaTests {
925 pemBlock, _ := pem.Decode([]byte(test.pemCert))
926 cert, err := ParseCertificate(pemBlock.Bytes)
927 if err != nil {
928 t.Errorf("%d: failed to parse certificate: %s", i, err)
929 continue
930 }
931 if sa := cert.SignatureAlgorithm; sa != test.sigAlgo {
932 t.Errorf("%d: signature algorithm is %v, want %v", i, sa, test.sigAlgo)
933 }
934 if parsedKey, ok := cert.PublicKey.(*ecdsa.PublicKey); !ok {
935 t.Errorf("%d: wanted an ECDSA public key but found: %#v", i, parsedKey)
936 }
937 if pka := cert.PublicKeyAlgorithm; pka != ECDSA {
938 t.Errorf("%d: public key algorithm is %v, want ECDSA", i, pka)
939 }
940 if err = cert.CheckSignatureFrom(cert); err != nil {
941 t.Errorf("%d: certificate verification failed: %s", i, err)
942 }
943 }
944 }
945
946
947 var dsaCertPem = `-----BEGIN CERTIFICATE-----
948 MIIEDTCCA82gAwIBAgIJALHPghaoxeDhMAkGByqGSM44BAMweTELMAkGA1UEBhMC
949 VVMxCzAJBgNVBAgTAk5DMQ8wDQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2ds
950 ZSwgSW5jMRIwEAYDVQQDEwlKb24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFs
951 bGllQGdvb2dsZS5jb20wHhcNMTEwNTE0MDMwMTQ1WhcNMTEwNjEzMDMwMTQ1WjB5
952 MQswCQYDVQQGEwJVUzELMAkGA1UECBMCTkMxDzANBgNVBAcTBk5ld3RvbjEUMBIG
953 A1UEChMLR29vZ2xlLCBJbmMxEjAQBgNVBAMTCUpvbiBBbGxpZTEiMCAGCSqGSIb3
954 DQEJARYTam9uYWxsaWVAZ29vZ2xlLmNvbTCCAbcwggEsBgcqhkjOOAQBMIIBHwKB
955 gQC8hLUnQ7FpFYu4WXTj6DKvXvz8QrJkNJCVMTpKAT7uBpobk32S5RrPKXocd4gN
956 8lyGB9ggS03EVlEwXvSmO0DH2MQtke2jl9j1HLydClMf4sbx5V6TV9IFw505U1iW
957 jL7awRMgxge+FsudtJK254FjMFo03ZnOQ8ZJJ9E6AEDrlwIVAJpnBn9moyP11Ox5
958 Asc/5dnjb6dPAoGBAJFHd4KVv1iTVCvEG6gGiYop5DJh28hUQcN9kul+2A0yPUSC
959 X93oN00P8Vh3eYgSaCWZsha7zDG53MrVJ0Zf6v/X/CoZNhLldeNOepivTRAzn+Rz
960 kKUYy5l1sxYLHQKF0UGNCXfFKZT0PCmgU+PWhYNBBMn6/cIh44vp85ideo5CA4GE
961 AAKBgFmifCafzeRaohYKXJgMGSEaggCVCRq5xdyDCat+wbOkjC4mfG01/um3G8u5
962 LxasjlWRKTR/tcAL7t0QuokVyQaYdVypZXNaMtx1db7YBuHjj3aP+8JOQRI9xz8c
963 bp5NDJ5pISiFOv4p3GZfqZPcqckDt78AtkQrmnal2txhhjF6o4HeMIHbMB0GA1Ud
964 DgQWBBQVyyr7hO11ZFFpWX50298Sa3V+rzCBqwYDVR0jBIGjMIGggBQVyyr7hO11
965 ZFFpWX50298Sa3V+r6F9pHsweTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAk5DMQ8w
966 DQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2dsZSwgSW5jMRIwEAYDVQQDEwlK
967 b24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFsbGllQGdvb2dsZS5jb22CCQCx
968 z4IWqMXg4TAMBgNVHRMEBTADAQH/MAkGByqGSM44BAMDLwAwLAIUPtn/5j8Q1jJI
969 7ggOIsgrhgUdjGQCFCsmDq1H11q9+9Wp9IMeGrTSKHIM
970 -----END CERTIFICATE-----
971 `
972
973 func TestParseCertificateWithDsaPublicKey(t *testing.T) {
974 expectedKey := &dsa.PublicKey{
975 Parameters: dsa.Parameters{
976 P: bigFromHexString("00BC84B52743B169158BB85974E3E832AF5EFCFC42B264349095313A4A013EEE069A1B937D92E51ACF297A1C77880DF25C8607D8204B4DC45651305EF4A63B40C7D8C42D91EDA397D8F51CBC9D0A531FE2C6F1E55E9357D205C39D395358968CBEDAC11320C607BE16CB9DB492B6E78163305A34DD99CE43C64927D13A0040EB97"),
977 Q: bigFromHexString("009A67067F66A323F5D4EC7902C73FE5D9E36FA74F"),
978 G: bigFromHexString("009147778295BF5893542BC41BA806898A29E43261DBC85441C37D92E97ED80D323D44825FDDE8374D0FF15877798812682599B216BBCC31B9DCCAD527465FEAFFD7FC2A193612E575E34E7A98AF4D10339FE47390A518CB9975B3160B1D0285D1418D0977C52994F43C29A053E3D685834104C9FAFDC221E38BE9F3989D7A8E42"),
979 },
980 Y: bigFromHexString("59A27C269FCDE45AA2160A5C980C19211A820095091AB9C5DC8309AB7EC1B3A48C2E267C6D35FEE9B71BCBB92F16AC8E559129347FB5C00BEEDD10BA8915C90698755CA965735A32DC7575BED806E1E38F768FFBC24E41123DC73F1C6E9E4D0C9E692128853AFE29DC665FA993DCA9C903B7BF00B6442B9A76A5DADC6186317A"),
981 }
982 pemBlock, _ := pem.Decode([]byte(dsaCertPem))
983 cert, err := ParseCertificate(pemBlock.Bytes)
984 if err != nil {
985 t.Fatalf("Failed to parse certificate: %s", err)
986 }
987 if cert.PublicKeyAlgorithm != DSA {
988 t.Errorf("Parsed key algorithm was not DSA")
989 }
990 parsedKey, ok := cert.PublicKey.(*dsa.PublicKey)
991 if !ok {
992 t.Fatalf("Parsed key was not a DSA key: %s", err)
993 }
994 if expectedKey.Y.Cmp(parsedKey.Y) != 0 ||
995 expectedKey.P.Cmp(parsedKey.P) != 0 ||
996 expectedKey.Q.Cmp(parsedKey.Q) != 0 ||
997 expectedKey.G.Cmp(parsedKey.G) != 0 {
998 t.Fatal("Parsed key differs from expected key")
999 }
1000 }
1001
1002 func TestParseCertificateWithDSASignatureAlgorithm(t *testing.T) {
1003 pemBlock, _ := pem.Decode([]byte(dsaCertPem))
1004 cert, err := ParseCertificate(pemBlock.Bytes)
1005 if err != nil {
1006 t.Fatalf("Failed to parse certificate: %s", err)
1007 }
1008 if cert.SignatureAlgorithm != DSAWithSHA1 {
1009 t.Errorf("Parsed signature algorithm was not DSAWithSHA1")
1010 }
1011 }
1012
1013 func TestVerifyCertificateWithDSASignature(t *testing.T) {
1014 pemBlock, _ := pem.Decode([]byte(dsaCertPem))
1015 cert, err := ParseCertificate(pemBlock.Bytes)
1016 if err != nil {
1017 t.Fatalf("Failed to parse certificate: %s", err)
1018 }
1019
1020 if err = cert.CheckSignatureFrom(cert); err == nil {
1021 t.Fatalf("Expected error verifying DSA certificate")
1022 }
1023 }
1024
1025 var rsaPSSSelfSignedPEM = `-----BEGIN CERTIFICATE-----
1026 MIIGHjCCA9KgAwIBAgIBdjBBBgkqhkiG9w0BAQowNKAPMA0GCWCGSAFlAwQCAQUA
1027 oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAQUAogMCASAwbjELMAkGA1UEBhMC
1028 SlAxHDAaBgNVBAoME0phcGFuZXNlIEdvdmVybm1lbnQxKDAmBgNVBAsMH1RoZSBN
1029 aW5pc3RyeSBvZiBGb3JlaWduIEFmZmFpcnMxFzAVBgNVBAMMDmUtcGFzc3BvcnRD
1030 U0NBMB4XDTEzMDUxNDA1MDczMFoXDTI5MDUxNDA1MDczMFowbjELMAkGA1UEBhMC
1031 SlAxHDAaBgNVBAoME0phcGFuZXNlIEdvdmVybm1lbnQxKDAmBgNVBAsMH1RoZSBN
1032 aW5pc3RyeSBvZiBGb3JlaWduIEFmZmFpcnMxFzAVBgNVBAMMDmUtcGFzc3BvcnRD
1033 U0NBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAx/E3WRVxcCDXhoST
1034 8nVSLjW6hwM4Ni99AegWzcGtfGFo0zjFA1Cl5URqxauvYu3gQgQHBGA1CovW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rtUj3HRQWf3
1051 kNTu628SiMvap6aIdncburaK56MP7gkR1Wr/ichOfjIA3Jgw2PapI31i0GqeMd66
1052 U1+lC9FeyMAJpuSVp/SoiYzYo+79SFcVoM2yw3yAnIKg7q9GLYYqzncdykT6C06c
1053 15gWFI6igmReAsD9ITSvYh0jLrLHfEYcPTOD3ZXJ4EwwHtWSoO3gq1EAtOYKu/Lv
1054 C8zfBsZcFdsHvsSiYeBU8Oioe42mguky3Ax9O7D805Ek6R68ra07MW/G4YxvV7IN
1055 2BfSaYy8MX9IG0ZMIOcoc0FeF5xkFmJ7kdrlTaJzC0IE9PNxNaH5QnOAFB8vxHcO
1056 FioUxb6UKdHcPLR1VZtAdTdTMjSJxUqD/35Cdfqs7oDJXz8f6TXO2Tdy6G++YUs9
1057 qsGZWxzFvvkXUkQSl0dQQ5jO/FtUJcAVXVVp20LxPemfatAHpW31WdJYeWSQWky2
1058 +f9b5TXKXVyjlUL7uHxowWrT2AtTchDH22wTEtqLEF9Z3Q==
1059 -----END CERTIFICATE-----`
1060
1061
1062
1063
1064
1065 var rsaPSSSelfSignedOpenSSL110PEM = `-----BEGIN CERTIFICATE-----
1066 MIIDwDCCAnigAwIBAgIJAM9LAMHTE5xpMD0GCSqGSIb3DQEBCjAwoA0wCwYJYIZI
1067 AWUDBAIBoRowGAYJKoZIhvcNAQEIMAsGCWCGSAFlAwQCAaIDAgEgMEUxCzAJBgNV
1068 BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDTALBgNVBAoMBFRlc3Qx
1069 DTALBgNVBAMMBFRlc3QwHhcNMTgwMjIyMjIxMzE4WhcNMjgwMjIwMjIxMzE4WjBF
1070 MQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExCzAJBgNVBAcMAlNGMQ0wCwYDVQQK
1071 DARUZXN0MQ0wCwYDVQQDDARUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
1072 CgKCAQEA4Zrsydod+GoTAJLLutWNF87qhhVPBsK1zB1Gj+NAAe4+VbrZ1E41H1wp
1073 qITx7DA8DRtJEf+NqrTAnAdZWBG/tAOA5LfXVax0ZSQtLnYLSeylLoMtDyY3eFAj
1074 TmuTOoyVy6raktowCnHCh01NsstqqTfrx6SbmzOmDmKTkq/I+7K0MCVsn41xRDVM
1075 +ShD0WGFGioEGoiWnFSWupxJDA3Q6jIDEygVwNKHwnhv/2NgG2kqZzrZSQA67en0
1076 iKAXtoDNPpmyD5oS9YbEJ+2Nbm7oLeON30i6kZvXKIzJXx+UWViazHZqnsi5rQ8G
1077 RHF+iVFXsqd0MzDKmkKOT5FDhrsbKQIDAQABo1MwUTAdBgNVHQ4EFgQU9uFY/nlg
1078 gLH00NBnr/o7QvpN9ugwHwYDVR0jBBgwFoAU9uFY/nlggLH00NBnr/o7QvpN9ugw
1079 DwYDVR0TAQH/BAUwAwEB/zA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAaEa
1080 MBgGCSqGSIb3DQEBCDALBglghkgBZQMEAgGiAwIBIAOCAQEAhJzpwxBNGKvzKWDe
1081 WLqv6RMrl/q4GcH3b7M9wjxe0yOm4F+Tb2zJ7re4h+D39YkJf8cX1NV9UQVu6z4s
1082 Fvo2kmlR0qZOXAg5augmCQ1xS0WHFoF6B52anNzHkZQbAIYJ3kGoFsUHzs7Sz7F/
1083 656FsRpHA9UzJQ3avPPMrA4Y4aoJ7ANJ6XIwTrdWrhULOVuvYRLCl4CdTVztVFX6
1084 wxX8nS1ISYd8jXPUMgsBKVbWufvLoIymMJW8CZbpprVZel5zFn0bmPrON8IHS30w
1085 Gs+ITJjKEnZgXmAQ25SLKVzkZkBcGANs2GsdHNJ370Puisy0FIPD2NXR5uASAf7J
1086 +w9fjQ==
1087 -----END CERTIFICATE-----`
1088
1089 func TestRSAPSSSelfSigned(t *testing.T) {
1090 for i, pemBlock := range []string{rsaPSSSelfSignedPEM, rsaPSSSelfSignedOpenSSL110PEM} {
1091 der, _ := pem.Decode([]byte(pemBlock))
1092 if der == nil {
1093 t.Errorf("#%d: failed to find PEM block", i)
1094 continue
1095 }
1096
1097 cert, err := ParseCertificate(der.Bytes)
1098 if err != nil {
1099 t.Errorf("#%d: failed to parse: %s", i, err)
1100 continue
1101 }
1102
1103 if err = cert.CheckSignatureFrom(cert); err != nil {
1104 t.Errorf("#%d: signature check failed: %s", i, err)
1105 continue
1106 }
1107 }
1108 }
1109
1110 const ed25519Certificate = `
1111 Certificate:
1112 Data:
1113 Version: 3 (0x2)
1114 Serial Number:
1115 0c:83:d8:21:2b:82:cb:23:98:23:63:e2:f7:97:8a:43:5b:f3:bd:92
1116 Signature Algorithm: ED25519
1117 Issuer: CN = Ed25519 test certificate
1118 Validity
1119 Not Before: May 6 17:27:16 2019 GMT
1120 Not After : Jun 5 17:27:16 2019 GMT
1121 Subject: CN = Ed25519 test certificate
1122 Subject Public Key Info:
1123 Public Key Algorithm: ED25519
1124 ED25519 Public-Key:
1125 pub:
1126 36:29:c5:6c:0d:4f:14:6c:81:d0:ff:75:d3:6a:70:
1127 5f:69:cd:0f:4d:66:d5:da:98:7e:82:49:89:a3:8a:
1128 3c:fa
1129 X509v3 extensions:
1130 X509v3 Subject Key Identifier:
1131 09:3B:3A:9D:4A:29:D8:95:FF:68:BE:7B:43:54:72:E0:AD:A2:E3:AE
1132 X509v3 Authority Key Identifier:
1133 keyid:09:3B:3A:9D:4A:29:D8:95:FF:68:BE:7B:43:54:72:E0:AD:A2:E3:AE
1134
1135 X509v3 Basic Constraints: critical
1136 CA:TRUE
1137 Signature Algorithm: ED25519
1138 53:a5:58:1c:2c:3b:2a:9e:ac:9d:4e:a5:1d:5f:5d:6d:a6:b5:
1139 08:de:12:82:f3:97:20:ae:fa:d8:98:f4:1a:83:32:6b:91:f5:
1140 24:1d:c4:20:7f:2c:e2:4d:da:13:3b:6d:54:1a:d2:a8:28:dc:
1141 60:b9:d4:f4:78:4b:3c:1c:91:00
1142 -----BEGIN CERTIFICATE-----
1143 MIIBWzCCAQ2gAwIBAgIUDIPYISuCyyOYI2Pi95eKQ1vzvZIwBQYDK2VwMCMxITAf
1144 BgNVBAMMGEVkMjU1MTkgdGVzdCBjZXJ0aWZpY2F0ZTAeFw0xOTA1MDYxNzI3MTZa
1145 Fw0xOTA2MDUxNzI3MTZaMCMxITAfBgNVBAMMGEVkMjU1MTkgdGVzdCBjZXJ0aWZp
1146 Y2F0ZTAqMAUGAytlcAMhADYpxWwNTxRsgdD/ddNqcF9pzQ9NZtXamH6CSYmjijz6
1147 o1MwUTAdBgNVHQ4EFgQUCTs6nUop2JX/aL57Q1Ry4K2i464wHwYDVR0jBBgwFoAU
1148 CTs6nUop2JX/aL57Q1Ry4K2i464wDwYDVR0TAQH/BAUwAwEB/zAFBgMrZXADQQBT
1149 pVgcLDsqnqydTqUdX11tprUI3hKC85cgrvrYmPQagzJrkfUkHcQgfyziTdoTO21U
1150 GtKoKNxgudT0eEs8HJEA
1151 -----END CERTIFICATE-----`
1152
1153 func TestEd25519SelfSigned(t *testing.T) {
1154 der, _ := pem.Decode([]byte(ed25519Certificate))
1155 if der == nil {
1156 t.Fatalf("Failed to find PEM block")
1157 }
1158
1159 cert, err := ParseCertificate(der.Bytes)
1160 if err != nil {
1161 t.Fatalf("Failed to parse: %s", err)
1162 }
1163
1164 if cert.PublicKeyAlgorithm != Ed25519 {
1165 t.Fatalf("Parsed key algorithm was not Ed25519")
1166 }
1167 parsedKey, ok := cert.PublicKey.(ed25519.PublicKey)
1168 if !ok {
1169 t.Fatalf("Parsed key was not an Ed25519 key: %s", err)
1170 }
1171 if len(parsedKey) != ed25519.PublicKeySize {
1172 t.Fatalf("Invalid Ed25519 key")
1173 }
1174
1175 if err = cert.CheckSignatureFrom(cert); err != nil {
1176 t.Fatalf("Signature check failed: %s", err)
1177 }
1178 }
1179
1180 const pemCertificate = `-----BEGIN CERTIFICATE-----
1181 MIIDATCCAemgAwIBAgIRAKQkkrFx1T/dgB/Go/xBM5swDQYJKoZIhvcNAQELBQ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const ed25519CRLCertificate = `
1201 Certificate:
1202 Data:
1203 Version: 3 (0x2)
1204 Serial Number:
1205 7a:07:a0:9d:14:04:16:fc:1f:d8:e5:fe:d1:1d:1f:8d
1206 Signature Algorithm: ED25519
1207 Issuer: CN = Ed25519 CRL Test CA
1208 Validity
1209 Not Before: Oct 30 01:20:20 2019 GMT
1210 Not After : Dec 31 23:59:59 9999 GMT
1211 Subject: CN = Ed25519 CRL Test CA
1212 Subject Public Key Info:
1213 Public Key Algorithm: ED25519
1214 ED25519 Public-Key:
1215 pub:
1216 95:73:3b:b0:06:2a:31:5a:b6:a7:a6:6e:ef:71:df:
1217 ac:6f:6b:39:03:85:5e:63:4b:f8:a6:0f:68:c6:6f:
1218 75:21
1219 X509v3 extensions:
1220 X509v3 Key Usage: critical
1221 Digital Signature, Certificate Sign, CRL Sign
1222 X509v3 Extended Key Usage:
1223 TLS Web Client Authentication, TLS Web Server Authentication, OCSP Signing
1224 X509v3 Basic Constraints: critical
1225 CA:TRUE
1226 X509v3 Subject Key Identifier:
1227 B7:17:DA:16:EA:C5:ED:1F:18:49:44:D3:D2:E3:A0:35:0A:81:93:60
1228 X509v3 Authority Key Identifier:
1229 keyid:B7:17:DA:16:EA:C5:ED:1F:18:49:44:D3:D2:E3:A0:35:0A:81:93:60
1230
1231 Signature Algorithm: ED25519
1232 fc:3e:14:ea:bb:70:c2:6f:38:34:70:bc:c8:a7:f4:7c:0d:1e:
1233 28:d7:2a:9f:22:8a:45:e8:02:76:84:1e:2d:64:2d:1e:09:b5:
1234 29:71:1f:95:8a:4e:79:87:51:60:9a:e7:86:40:f6:60:c7:d1:
1235 ee:68:76:17:1d:90:cc:92:93:07
1236 -----BEGIN CERTIFICATE-----
1237 MIIBijCCATygAwIBAgIQegegnRQEFvwf2OX+0R0fjTAFBgMrZXAwHjEcMBoGA1UE
1238 AxMTRWQyNTUxOSBDUkwgVGVzdCBDQTAgFw0xOTEwMzAwMTIwMjBaGA85OTk5MTIz
1239 MTIzNTk1OVowHjEcMBoGA1UEAxMTRWQyNTUxOSBDUkwgVGVzdCBDQTAqMAUGAytl
1240 cAMhAJVzO7AGKjFatqembu9x36xvazkDhV5jS/imD2jGb3Uho4GNMIGKMA4GA1Ud
1241 DwEB/wQEAwIBhjAnBgNVHSUEIDAeBggrBgEFBQcDAgYIKwYBBQUHAwEGCCsGAQUF
1242 BwMJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFLcX2hbqxe0fGElE09LjoDUK
1243 gZNgMB8GA1UdIwQYMBaAFLcX2hbqxe0fGElE09LjoDUKgZNgMAUGAytlcANBAPw+
1244 FOq7cMJvODRwvMin9HwNHijXKp8iikXoAnaEHi1kLR4JtSlxH5WKTnmHUWCa54ZA
1245 9mDH0e5odhcdkMySkwc=
1246 -----END CERTIFICATE-----`
1247
1248 var ed25519CRLKey = testingKey(`-----BEGIN TEST KEY-----
1249 MC4CAQAwBQYDK2VwBCIEINdKh2096vUBYu4EIFpjShsUSh3vimKya1sQ1YTT4RZG
1250 -----END TEST KEY-----`)
1251
1252 func TestCRLCreation(t *testing.T) {
1253 block, _ := pem.Decode([]byte(pemPrivateKey))
1254 privRSA, _ := ParsePKCS1PrivateKey(block.Bytes)
1255 block, _ = pem.Decode([]byte(pemCertificate))
1256 certRSA, _ := ParseCertificate(block.Bytes)
1257
1258 block, _ = pem.Decode([]byte(ed25519CRLKey))
1259 privEd25519, _ := ParsePKCS8PrivateKey(block.Bytes)
1260 block, _ = pem.Decode([]byte(ed25519CRLCertificate))
1261 certEd25519, _ := ParseCertificate(block.Bytes)
1262
1263 tests := []struct {
1264 name string
1265 priv any
1266 cert *Certificate
1267 }{
1268 {"RSA CA", privRSA, certRSA},
1269 {"Ed25519 CA", privEd25519, certEd25519},
1270 }
1271
1272 loc := time.FixedZone("Oz/Atlantis", int((2 * time.Hour).Seconds()))
1273
1274 now := time.Unix(1000, 0).In(loc)
1275 nowUTC := now.UTC()
1276 expiry := time.Unix(10000, 0)
1277
1278 revokedCerts := []pkix.RevokedCertificate{
1279 {
1280 SerialNumber: big.NewInt(1),
1281 RevocationTime: nowUTC,
1282 },
1283 {
1284 SerialNumber: big.NewInt(42),
1285
1286 RevocationTime: now,
1287 },
1288 }
1289 expectedCerts := []pkix.RevokedCertificate{
1290 {
1291 SerialNumber: big.NewInt(1),
1292 RevocationTime: nowUTC,
1293 },
1294 {
1295 SerialNumber: big.NewInt(42),
1296 RevocationTime: nowUTC,
1297 },
1298 }
1299
1300 for _, test := range tests {
1301 crlBytes, err := test.cert.CreateCRL(rand.Reader, test.priv, revokedCerts, now, expiry)
1302 if err != nil {
1303 t.Errorf("%s: error creating CRL: %s", test.name, err)
1304 continue
1305 }
1306
1307 parsedCRL, err := ParseDERCRL(crlBytes)
1308 if err != nil {
1309 t.Errorf("%s: error reparsing CRL: %s", test.name, err)
1310 continue
1311 }
1312 if !reflect.DeepEqual(parsedCRL.TBSCertList.RevokedCertificates, expectedCerts) {
1313 t.Errorf("%s: RevokedCertificates mismatch: got %v; want %v.", test.name,
1314 parsedCRL.TBSCertList.RevokedCertificates, expectedCerts)
1315 }
1316 }
1317 }
1318
1319 func fromBase64(in string) []byte {
1320 out := make([]byte, base64.StdEncoding.DecodedLen(len(in)))
1321 n, err := base64.StdEncoding.Decode(out, []byte(in))
1322 if err != nil {
1323 panic("failed to base64 decode")
1324 }
1325 return out[:n]
1326 }
1327
1328 func TestParseDERCRL(t *testing.T) {
1329 derBytes := fromBase64(derCRLBase64)
1330 certList, err := ParseDERCRL(derBytes)
1331 if err != nil {
1332 t.Errorf("error parsing: %s", err)
1333 return
1334 }
1335 numCerts := len(certList.TBSCertList.RevokedCertificates)
1336 expected := 88
1337 if numCerts != expected {
1338 t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected)
1339 }
1340
1341 if certList.HasExpired(time.Unix(1302517272, 0)) {
1342 t.Errorf("CRL has expired (but shouldn't have)")
1343 }
1344
1345
1346 }
1347
1348 func TestCRLWithoutExpiry(t *testing.T) {
1349 derBytes := fromBase64("MIHYMIGZMAkGByqGSM44BAMwEjEQMA4GA1UEAxMHQ2FybERTUxcNOTkwODI3MDcwMDAwWjBpMBMCAgDIFw05OTA4MjIwNzAwMDBaMBMCAgDJFw05OTA4MjIwNzAwMDBaMBMCAgDTFw05OTA4MjIwNzAwMDBaMBMCAgDSFw05OTA4MjIwNzAwMDBaMBMCAgDUFw05OTA4MjQwNzAwMDBaMAkGByqGSM44BAMDLwAwLAIUfmVSdjP+NHMX0feW+aDU2G1cfT0CFAJ6W7fVWxjBz4fvftok8yqDnDWh")
1350 certList, err := ParseDERCRL(derBytes)
1351 if err != nil {
1352 t.Fatal(err)
1353 }
1354 if !certList.TBSCertList.NextUpdate.IsZero() {
1355 t.Errorf("NextUpdate is not the zero value")
1356 }
1357 }
1358
1359 func TestParsePEMCRL(t *testing.T) {
1360 pemBytes := fromBase64(pemCRLBase64)
1361 certList, err := ParseCRL(pemBytes)
1362 if err != nil {
1363 t.Errorf("error parsing: %s", err)
1364 return
1365 }
1366 numCerts := len(certList.TBSCertList.RevokedCertificates)
1367 expected := 2
1368 if numCerts != expected {
1369 t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected)
1370 }
1371
1372 if certList.HasExpired(time.Unix(1302517272, 0)) {
1373 t.Errorf("CRL has expired (but shouldn't have)")
1374 }
1375
1376
1377 }
1378
1379 func TestImports(t *testing.T) {
1380 if testing.Short() {
1381 t.Skip("skipping in -short mode")
1382 }
1383 testenv.MustHaveGoRun(t)
1384
1385 if out, err := exec.Command(testenv.GoToolPath(t), "run", "x509_test_import.go").CombinedOutput(); err != nil {
1386 t.Errorf("failed to run x509_test_import.go: %s\n%s", err, out)
1387 }
1388 }
1389
1390 const derCRLBase64 = "MIINqzCCDJMCAQEwDQYJKoZIhvcNAQEFBQAwVjEZMBcGA1UEAxMQUEtJIEZJTk1FQ0NBTklDQTEVMBMGA1UEChMMRklOTUVDQ0FOSUNBMRUwEwYDVQQLEwxGSU5NRUNDQU5JQ0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3BQWmVSV0NCamlQL01FSEJXSkNsQkhQDQpHUmNxNXlJZDNFakRrYUV5eFJhK2k2N0x6dmhJNmMyOUVlNks5cFNZd2ppLzdSVWhtbW5Qclh0VHhsTDBsckxyDQptUVFKNnhoRFJhNUczUUE0Q21VZHNITnZicnpnbUNZcHZWRT0NCi0tLS0tRU5EIFg1MDkgQ1JMLS0tLS0NCg0K"
1393
1394 func TestCreateCertificateRequest(t *testing.T) {
1395 random := rand.Reader
1396
1397 ecdsa256Priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
1398 if err != nil {
1399 t.Fatalf("Failed to generate ECDSA key: %s", err)
1400 }
1401
1402 ecdsa384Priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
1403 if err != nil {
1404 t.Fatalf("Failed to generate ECDSA key: %s", err)
1405 }
1406
1407 ecdsa521Priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
1408 if err != nil {
1409 t.Fatalf("Failed to generate ECDSA key: %s", err)
1410 }
1411
1412 _, ed25519Priv, err := ed25519.GenerateKey(random)
1413 if err != nil {
1414 t.Fatalf("Failed to generate Ed25519 key: %s", err)
1415 }
1416
1417 tests := []struct {
1418 name string
1419 priv any
1420 sigAlgo SignatureAlgorithm
1421 }{
1422 {"RSA", testPrivateKey, SHA256WithRSA},
1423 {"RSA-PSS-SHA256", testPrivateKey, SHA256WithRSAPSS},
1424 {"ECDSA-256", ecdsa256Priv, ECDSAWithSHA256},
1425 {"ECDSA-384", ecdsa384Priv, ECDSAWithSHA256},
1426 {"ECDSA-521", ecdsa521Priv, ECDSAWithSHA256},
1427 {"Ed25519", ed25519Priv, PureEd25519},
1428 }
1429
1430 for _, test := range tests {
1431 template := CertificateRequest{
1432 Subject: pkix.Name{
1433 CommonName: "test.example.com",
1434 Organization: []string{"Σ Acme Co"},
1435 },
1436 SignatureAlgorithm: test.sigAlgo,
1437 DNSNames: []string{"test.example.com"},
1438 EmailAddresses: []string{"gopher@golang.org"},
1439 IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
1440 }
1441
1442 derBytes, err := CreateCertificateRequest(random, &template, test.priv)
1443 if err != nil {
1444 t.Errorf("%s: failed to create certificate request: %s", test.name, err)
1445 continue
1446 }
1447
1448 out, err := ParseCertificateRequest(derBytes)
1449 if err != nil {
1450 t.Errorf("%s: failed to create certificate request: %s", test.name, err)
1451 continue
1452 }
1453
1454 err = out.CheckSignature()
1455 if err != nil {
1456 t.Errorf("%s: failed to check certificate request signature: %s", test.name, err)
1457 continue
1458 }
1459
1460 if out.Subject.CommonName != template.Subject.CommonName {
1461 t.Errorf("%s: output subject common name and template subject common name don't match", test.name)
1462 } else if len(out.Subject.Organization) != len(template.Subject.Organization) {
1463 t.Errorf("%s: output subject organisation and template subject organisation don't match", test.name)
1464 } else if len(out.DNSNames) != len(template.DNSNames) {
1465 t.Errorf("%s: output DNS names and template DNS names don't match", test.name)
1466 } else if len(out.EmailAddresses) != len(template.EmailAddresses) {
1467 t.Errorf("%s: output email addresses and template email addresses don't match", test.name)
1468 } else if len(out.IPAddresses) != len(template.IPAddresses) {
1469 t.Errorf("%s: output IP addresses and template IP addresses names don't match", test.name)
1470 }
1471 }
1472 }
1473
1474 func marshalAndParseCSR(t *testing.T, template *CertificateRequest) *CertificateRequest {
1475 t.Helper()
1476 derBytes, err := CreateCertificateRequest(rand.Reader, template, testPrivateKey)
1477 if err != nil {
1478 t.Fatal(err)
1479 }
1480
1481 csr, err := ParseCertificateRequest(derBytes)
1482 if err != nil {
1483 t.Fatal(err)
1484 }
1485
1486 return csr
1487 }
1488
1489 func TestCertificateRequestOverrides(t *testing.T) {
1490 sanContents, err := marshalSANs([]string{"foo.example.com"}, nil, nil, nil)
1491 if err != nil {
1492 t.Fatal(err)
1493 }
1494
1495 template := CertificateRequest{
1496 Subject: pkix.Name{
1497 CommonName: "test.example.com",
1498 Organization: []string{"Σ Acme Co"},
1499 },
1500 DNSNames: []string{"test.example.com"},
1501
1502
1503
1504 ExtraExtensions: []pkix.Extension{
1505 {
1506 Id: oidExtensionSubjectAltName,
1507 Value: sanContents,
1508 Critical: true,
1509 },
1510 },
1511 }
1512
1513 csr := marshalAndParseCSR(t, &template)
1514
1515 if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo.example.com" {
1516 t.Errorf("Extension did not override template. Got %v\n", csr.DNSNames)
1517 }
1518
1519 if len(csr.Extensions) != 1 || !csr.Extensions[0].Id.Equal(oidExtensionSubjectAltName) || !csr.Extensions[0].Critical {
1520 t.Errorf("SAN extension was not faithfully copied, got %#v", csr.Extensions)
1521 }
1522
1523
1524
1525
1526
1527 template.Attributes = []pkix.AttributeTypeAndValueSET{
1528 {
1529 Type: oidExtensionRequest,
1530 Value: [][]pkix.AttributeTypeAndValue{
1531 {
1532 {
1533 Type: oidExtensionAuthorityInfoAccess,
1534 Value: []byte("foo"),
1535 },
1536 },
1537 },
1538 },
1539 }
1540
1541 csr = marshalAndParseCSR(t, &template)
1542 if l := len(csr.Attributes); l != 1 {
1543 t.Errorf("incorrect number of attributes: %d\n", l)
1544 }
1545
1546 if !csr.Attributes[0].Type.Equal(oidExtensionRequest) ||
1547 len(csr.Attributes[0].Value) != 1 ||
1548 len(csr.Attributes[0].Value[0]) != 2 {
1549 t.Errorf("bad attributes: %#v\n", csr.Attributes)
1550 }
1551
1552 sanContents2, err := marshalSANs([]string{"foo2.example.com"}, nil, nil, nil)
1553 if err != nil {
1554 t.Fatal(err)
1555 }
1556
1557
1558 template.Attributes[0].Value[0] = append(template.Attributes[0].Value[0], pkix.AttributeTypeAndValue{
1559 Type: oidExtensionSubjectAltName,
1560 Value: sanContents2,
1561 })
1562
1563 csr = marshalAndParseCSR(t, &template)
1564
1565 if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo2.example.com" {
1566 t.Errorf("Attributes did not override ExtraExtensions. Got %v\n", csr.DNSNames)
1567 }
1568 }
1569
1570 func TestParseCertificateRequest(t *testing.T) {
1571 for _, csrBase64 := range csrBase64Array {
1572 csrBytes := fromBase64(csrBase64)
1573 csr, err := ParseCertificateRequest(csrBytes)
1574 if err != nil {
1575 t.Fatalf("failed to parse CSR: %s", err)
1576 }
1577
1578 if len(csr.EmailAddresses) != 1 || csr.EmailAddresses[0] != "gopher@golang.org" {
1579 t.Errorf("incorrect email addresses found: %v", csr.EmailAddresses)
1580 }
1581
1582 if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "test.example.com" {
1583 t.Errorf("incorrect DNS names found: %v", csr.DNSNames)
1584 }
1585
1586 if len(csr.Subject.Country) != 1 || csr.Subject.Country[0] != "AU" {
1587 t.Errorf("incorrect Subject name: %v", csr.Subject)
1588 }
1589
1590 found := false
1591 for _, e := range csr.Extensions {
1592 if e.Id.Equal(oidExtensionBasicConstraints) {
1593 found = true
1594 break
1595 }
1596 }
1597 if !found {
1598 t.Errorf("basic constraints extension not found in CSR")
1599 }
1600 }
1601 }
1602
1603 func TestCriticalFlagInCSRRequestedExtensions(t *testing.T) {
1604
1605
1606 const csrBase64 = "MIICrTCCAZUCAQIwMzEgMB4GA1UEAwwXU0NFUCBDQSBmb3IgRGV2ZWxlciBTcmwxDzANBgNVBAsMBjQzNTk3MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALFMAJ7Zy9YyfgbNlbUWAW0LalNRMPs7aXmLANsCpjhnw3lLlfDPaLeWyKh1nK5I5ojaJOW6KIOSAcJkDUe3rrE0wR0RVt3UxArqs0R/ND3u5Q+bDQY2X1HAFUHzUzcdm5JRAIA355v90teMckaWAIlkRQjDE22Lzc6NAl64KOd1rqOUNj8+PfX6fSo20jm94Pp1+a6mfk3G/RUWVuSm7owO5DZI/Fsi2ijdmb4NUar6K/bDKYTrDFkzcqAyMfP3TitUtBp19Mp3B1yAlHjlbp/r5fSSXfOGHZdgIvp0WkLuK2u5eQrX5l7HMB/5epgUs3HQxKY6ljhh5wAjDwz//LsCAwEAAaA1MDMGCSqGSIb3DQEJDjEmMCQwEgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAoQwDQYJKoZIhvcNAQEFBQADggEBAAMq3bxJSPQEgzLYR/yaVvgjCDrc3zUbIwdOis6Go06Q4RnjH5yRaSZAqZQTDsPurQcnz2I39VMGEiSkFJFavf4QHIZ7QFLkyXadMtALc87tm17Ej719SbHcBSSZayR9VYJUNXRLayI6HvyUrmqcMKh+iX3WY3ICr59/wlM0tYa8DYN4yzmOa2Onb29gy3YlaF5A2AKAMmk003cRT9gY26mjpv7d21czOSSeNyVIoZ04IR9ee71vWTMdv0hu/af5kSjQ+ZG5/Qgc0+mnECLz/1gtxt1srLYbtYQ/qAY8oX1DCSGFS61tN/vl+4cxGMD/VGcGzADRLRHSlVqy2Qgss6Q="
1607
1608 csrBytes := fromBase64(csrBase64)
1609 csr, err := ParseCertificateRequest(csrBytes)
1610 if err != nil {
1611 t.Fatalf("failed to parse CSR: %s", err)
1612 }
1613
1614 expected := []struct {
1615 Id asn1.ObjectIdentifier
1616 Value []byte
1617 }{
1618 {oidExtensionBasicConstraints, fromBase64("MAYBAf8CAQA=")},
1619 {oidExtensionKeyUsage, fromBase64("AwIChA==")},
1620 }
1621
1622 if n := len(csr.Extensions); n != len(expected) {
1623 t.Fatalf("expected to find %d extensions but found %d", len(expected), n)
1624 }
1625
1626 for i, extension := range csr.Extensions {
1627 if !extension.Id.Equal(expected[i].Id) {
1628 t.Fatalf("extension #%d has unexpected type %v (expected %v)", i, extension.Id, expected[i].Id)
1629 }
1630
1631 if !bytes.Equal(extension.Value, expected[i].Value) {
1632 t.Fatalf("extension #%d has unexpected contents %x (expected %x)", i, extension.Value, expected[i].Value)
1633 }
1634 }
1635 }
1636
1637
1638
1639 func serialiseAndParse(t *testing.T, template *Certificate) *Certificate {
1640 t.Helper()
1641 derBytes, err := CreateCertificate(rand.Reader, template, template, &testPrivateKey.PublicKey, testPrivateKey)
1642 if err != nil {
1643 t.Fatalf("failed to create certificate: %s", err)
1644 return nil
1645 }
1646
1647 cert, err := ParseCertificate(derBytes)
1648 if err != nil {
1649 t.Fatalf("failed to parse certificate: %s", err)
1650 return nil
1651 }
1652
1653 return cert
1654 }
1655
1656 func TestMaxPathLenNotCA(t *testing.T) {
1657 template := &Certificate{
1658 SerialNumber: big.NewInt(1),
1659 Subject: pkix.Name{
1660 CommonName: "Σ Acme Co",
1661 },
1662 NotBefore: time.Unix(1000, 0),
1663 NotAfter: time.Unix(100000, 0),
1664
1665 BasicConstraintsValid: true,
1666 IsCA: false,
1667 }
1668 if m := serialiseAndParse(t, template).MaxPathLen; m != -1 {
1669 t.Errorf("MaxPathLen should be -1 when IsCa is false, got %d", m)
1670 }
1671
1672 template.MaxPathLen = -1
1673 if m := serialiseAndParse(t, template).MaxPathLen; m != -1 {
1674 t.Errorf("MaxPathLen should be -1 when IsCa is false and MaxPathLen set to -1, got %d", m)
1675 }
1676
1677 template.MaxPathLen = 5
1678 if _, err := CreateCertificate(rand.Reader, template, template, &testPrivateKey.PublicKey, testPrivateKey); err == nil {
1679 t.Error("specifying a MaxPathLen when IsCA is false should fail")
1680 }
1681
1682 template.MaxPathLen = 0
1683 template.MaxPathLenZero = true
1684 if _, err := CreateCertificate(rand.Reader, template, template, &testPrivateKey.PublicKey, testPrivateKey); err == nil {
1685 t.Error("setting MaxPathLenZero when IsCA is false should fail")
1686 }
1687
1688 template.BasicConstraintsValid = false
1689 if m := serialiseAndParse(t, template).MaxPathLen; m != 0 {
1690 t.Errorf("Bad MaxPathLen should be ignored if BasicConstraintsValid is false, got %d", m)
1691 }
1692 }
1693
1694 func TestMaxPathLen(t *testing.T) {
1695 template := &Certificate{
1696 SerialNumber: big.NewInt(1),
1697 Subject: pkix.Name{
1698 CommonName: "Σ Acme Co",
1699 },
1700 NotBefore: time.Unix(1000, 0),
1701 NotAfter: time.Unix(100000, 0),
1702
1703 BasicConstraintsValid: true,
1704 IsCA: true,
1705 }
1706
1707 cert1 := serialiseAndParse(t, template)
1708 if m := cert1.MaxPathLen; m != -1 {
1709 t.Errorf("Omitting MaxPathLen didn't turn into -1, got %d", m)
1710 }
1711 if cert1.MaxPathLenZero {
1712 t.Errorf("Omitting MaxPathLen resulted in MaxPathLenZero")
1713 }
1714
1715 template.MaxPathLen = 1
1716 cert2 := serialiseAndParse(t, template)
1717 if m := cert2.MaxPathLen; m != 1 {
1718 t.Errorf("Setting MaxPathLen didn't work. Got %d but set 1", m)
1719 }
1720 if cert2.MaxPathLenZero {
1721 t.Errorf("Setting MaxPathLen resulted in MaxPathLenZero")
1722 }
1723
1724 template.MaxPathLen = 0
1725 template.MaxPathLenZero = true
1726 cert3 := serialiseAndParse(t, template)
1727 if m := cert3.MaxPathLen; m != 0 {
1728 t.Errorf("Setting MaxPathLenZero didn't work, got %d", m)
1729 }
1730 if !cert3.MaxPathLenZero {
1731 t.Errorf("Setting MaxPathLen to zero didn't result in MaxPathLenZero")
1732 }
1733 }
1734
1735 func TestNoAuthorityKeyIdInSelfSignedCert(t *testing.T) {
1736 template := &Certificate{
1737 SerialNumber: big.NewInt(1),
1738 Subject: pkix.Name{
1739 CommonName: "Σ Acme Co",
1740 },
1741 NotBefore: time.Unix(1000, 0),
1742 NotAfter: time.Unix(100000, 0),
1743
1744 BasicConstraintsValid: true,
1745 IsCA: true,
1746 SubjectKeyId: []byte{1, 2, 3, 4},
1747 }
1748
1749 if cert := serialiseAndParse(t, template); len(cert.AuthorityKeyId) != 0 {
1750 t.Fatalf("self-signed certificate contained default authority key id")
1751 }
1752
1753 template.AuthorityKeyId = []byte{1, 2, 3, 4}
1754 if cert := serialiseAndParse(t, template); len(cert.AuthorityKeyId) == 0 {
1755 t.Fatalf("self-signed certificate erased explicit authority key id")
1756 }
1757 }
1758
1759 func TestNoSubjectKeyIdInCert(t *testing.T) {
1760 template := &Certificate{
1761 SerialNumber: big.NewInt(1),
1762 Subject: pkix.Name{
1763 CommonName: "Σ Acme Co",
1764 },
1765 NotBefore: time.Unix(1000, 0),
1766 NotAfter: time.Unix(100000, 0),
1767
1768 BasicConstraintsValid: true,
1769 IsCA: true,
1770 }
1771 if cert := serialiseAndParse(t, template); len(cert.SubjectKeyId) == 0 {
1772 t.Fatalf("self-signed certificate did not generate subject key id using the public key")
1773 }
1774
1775 template.IsCA = false
1776 if cert := serialiseAndParse(t, template); len(cert.SubjectKeyId) != 0 {
1777 t.Fatalf("self-signed certificate generated subject key id when it isn't a CA")
1778 }
1779
1780 template.SubjectKeyId = []byte{1, 2, 3, 4}
1781 if cert := serialiseAndParse(t, template); len(cert.SubjectKeyId) == 0 {
1782 t.Fatalf("self-signed certificate erased explicit subject key id")
1783 }
1784 }
1785
1786 func TestASN1BitLength(t *testing.T) {
1787 tests := []struct {
1788 bytes []byte
1789 bitLen int
1790 }{
1791 {nil, 0},
1792 {[]byte{0x00}, 0},
1793 {[]byte{0x00, 0x00}, 0},
1794 {[]byte{0xf0}, 4},
1795 {[]byte{0x88}, 5},
1796 {[]byte{0xff}, 8},
1797 {[]byte{0xff, 0x80}, 9},
1798 {[]byte{0xff, 0x81}, 16},
1799 }
1800
1801 for i, test := range tests {
1802 if got := asn1BitLength(test.bytes); got != test.bitLen {
1803 t.Errorf("#%d: calculated bit-length of %d for %x, wanted %d", i, got, test.bytes, test.bitLen)
1804 }
1805 }
1806 }
1807
1808 func TestVerifyEmptyCertificate(t *testing.T) {
1809 if _, err := new(Certificate).Verify(VerifyOptions{}); err != errNotParsed {
1810 t.Errorf("Verifying empty certificate resulted in unexpected error: %q (wanted %q)", err, errNotParsed)
1811 }
1812 }
1813
1814 func TestInsecureAlgorithmErrorString(t *testing.T) {
1815 tests := []struct {
1816 sa SignatureAlgorithm
1817 want string
1818 }{
1819 {MD5WithRSA, "x509: cannot verify signature: insecure algorithm MD5-RSA"},
1820 {SHA1WithRSA, "x509: cannot verify signature: insecure algorithm SHA1-RSA (temporarily override with GODEBUG=x509sha1=1)"},
1821 {ECDSAWithSHA1, "x509: cannot verify signature: insecure algorithm ECDSA-SHA1 (temporarily override with GODEBUG=x509sha1=1)"},
1822 {MD2WithRSA, "x509: cannot verify signature: insecure algorithm 1"},
1823 {-1, "x509: cannot verify signature: insecure algorithm -1"},
1824 {0, "x509: cannot verify signature: insecure algorithm 0"},
1825 {9999, "x509: cannot verify signature: insecure algorithm 9999"},
1826 }
1827 for i, tt := range tests {
1828 if got := fmt.Sprint(InsecureAlgorithmError(tt.sa)); got != tt.want {
1829 t.Errorf("%d. mismatch.\n got: %s\nwant: %s\n", i, got, tt.want)
1830 }
1831 }
1832 }
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847 var csrBase64Array = [...]string{
1848
1849 "MIIDHDCCAgQCAQAwfjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEUMBIGA1UEAwwLQ29tbW9uIE5hbWUxITAfBgkqhkiG9w0BCQEWEnRlc3RAZW1haWwuYWRkcmVzczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK1GY4YFx2ujlZEOJxQVYmsjUnLsd5nFVnNpLE4cV+77sgv9NPNlB8uhn3MXt5leD34rm/2BisCHOifPucYlSrszo2beuKhvwn4+2FxDmWtBEMu/QA16L5IvoOfYZm/gJTsPwKDqvaR0tTU67a9OtxwNTBMI56YKtmwd/o8d3hYv9cg+9ZGAZ/gKONcg/OWYx/XRh6bd0g8DMbCikpWgXKDsvvK1Nk+VtkDO1JxuBaj4Lz/p/MifTfnHoqHxWOWl4EaTs4Ychxsv34/rSj1KD1tJqorIv5Xv2aqv4sjxfbrYzX4kvS5SC1goIovLnhj5UjmQ3Qy8u65eow/LLWw+YFcCAwEAAaBZMFcGCSqGSIb3DQEJDjFKMEgwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwLgYDVR0RBCcwJYERZ29waGVyQGdvbGFuZy5vcmeCEHRlc3QuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQELBQADggEB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cDDLJWVi7bhfa4EAD86di05azOh9kWSn4b3o9QYRGCSw
1865 GNnI3Zk0cwNKA49hZntKKiy22DhRk7JAHF01d6Bu3KkHkmENrtJ+zj/+159WAnUa
1866 qViorq4=
1867 -----END CERTIFICATE-----
1868 `
1869
1870 func TestMD5(t *testing.T) {
1871 pemBlock, _ := pem.Decode([]byte(md5cert))
1872 cert, err := ParseCertificate(pemBlock.Bytes)
1873 if err != nil {
1874 t.Fatalf("failed to parse certificate: %s", err)
1875 }
1876 if sa := cert.SignatureAlgorithm; sa != MD5WithRSA {
1877 t.Errorf("signature algorithm is %v, want %v", sa, MD5WithRSA)
1878 }
1879 if err = cert.CheckSignatureFrom(cert); err == nil {
1880 t.Fatalf("certificate verification succeeded incorrectly")
1881 }
1882 if _, ok := err.(InsecureAlgorithmError); !ok {
1883 t.Fatalf("certificate verification returned %v (%T), wanted InsecureAlgorithmError", err, err)
1884 }
1885 }
1886
1887 func TestSHA1(t *testing.T) {
1888 pemBlock, _ := pem.Decode([]byte(ecdsaSHA1CertPem))
1889 cert, err := ParseCertificate(pemBlock.Bytes)
1890 if err != nil {
1891 t.Fatalf("failed to parse certificate: %s", err)
1892 }
1893 if sa := cert.SignatureAlgorithm; sa != ECDSAWithSHA1 {
1894 t.Errorf("signature algorithm is %v, want %v", sa, ECDSAWithSHA1)
1895 }
1896 if err = cert.CheckSignatureFrom(cert); err == nil {
1897 t.Fatalf("certificate verification succeeded incorrectly")
1898 }
1899 if _, ok := err.(InsecureAlgorithmError); !ok {
1900 t.Fatalf("certificate verification returned %v (%T), wanted InsecureAlgorithmError", err, err)
1901 }
1902
1903 t.Setenv("GODEBUG", "x509sha1=1")
1904 if err = cert.CheckSignatureFrom(cert); err != nil {
1905 t.Fatalf("SHA-1 certificate did not verify with GODEBUG=x509sha1=1: %v", err)
1906 }
1907 }
1908
1909
1910
1911 const certMissingRSANULL = `
1912 -----BEGIN CERTIFICATE-----
1913 MIIB7TCCAVigAwIBAgIBADALBgkqhkiG9w0BAQUwJjEQMA4GA1UEChMHQWNtZSBD
1914 bzESMBAGA1UEAxMJMTI3LjAuMC4xMB4XDTExMTIwODA3NTUxMloXDTEyMTIwNzA4
1915 MDAxMlowJjEQMA4GA1UEChMHQWNtZSBDbzESMBAGA1UEAxMJMTI3LjAuMC4xMIGc
1916 MAsGCSqGSIb3DQEBAQOBjAAwgYgCgYBO0Hsx44Jk2VnAwoekXh6LczPHY1PfZpIG
1917 hPZk1Y/kNqcdK+izIDZFI7Xjla7t4PUgnI2V339aEu+H5Fto5OkOdOwEin/ekyfE
1918 ARl6vfLcPRSr0FTKIQzQTW6HLlzF0rtNS0/Otiz3fojsfNcCkXSmHgwa2uNKWi7e
1919 E5xMQIhZkwIDAQABozIwMDAOBgNVHQ8BAf8EBAMCAKAwDQYDVR0OBAYEBAECAwQw
1920 DwYDVR0jBAgwBoAEAQIDBDALBgkqhkiG9w0BAQUDgYEANh+zegx1yW43RmEr1b3A
1921 p0vMRpqBWHyFeSnIyMZn3TJWRSt1tukkqVCavh9a+hoV2cxVlXIWg7nCto/9iIw4
1922 hB2rXZIxE0/9gzvGnfERYraL7KtnvshksBFQRlgXa5kc0x38BvEO5ZaoDPl4ILdE
1923 GFGNEH5PlGffo05wc46QkYU=
1924 -----END CERTIFICATE-----`
1925
1926 func TestRSAMissingNULLParameters(t *testing.T) {
1927 block, _ := pem.Decode([]byte(certMissingRSANULL))
1928 if _, err := ParseCertificate(block.Bytes); err == nil {
1929 t.Error("unexpected success when parsing certificate with missing RSA NULL parameter")
1930 } else if !strings.Contains(err.Error(), "missing NULL") {
1931 t.Errorf("unrecognised error when parsing certificate with missing RSA NULL parameter: %s", err)
1932 }
1933 }
1934
1935 const certISOOID = `-----BEGIN CERTIFICATE-----
1936 MIIB5TCCAVKgAwIBAgIQNwyL3RPWV7dJQp34HwZG9DAJBgUrDgMCHQUAMBExDzAN
1937 BgNVBAMTBm15dGVzdDAeFw0xNjA4MDkyMjExMDVaFw0zOTEyMzEyMzU5NTlaMBEx
1938 DzANBgNVBAMTBm15dGVzdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArzIH
1939 GsyDB3ohIGkkvijF2PTRUX1bvOtY1eUUpjwHyu0twpAKSuaQv2Ha+/63+aHe8O86
1940 BT+98wjXFX6RFSagtAujo80rIF2dSm33BGt18pDN8v6zp93dnAm0jRaSQrHJ75xw
1941 5O+S1oEYR1LtUoFJy6qB104j6aINBAgOiLIKiMkCAwEAAaNGMEQwQgYDVR0BBDsw
1942 OYAQVuYVQ/WDjdGSkZRlTtJDNKETMBExDzANBgNVBAMTBm15dGVzdIIQtwyL3RPW
1943 V7dJQp34HwZG9DAJBgUrDgMCHQUAA4GBABngrSkH7vG5lY4sa4AZF59lAAXqBVJE
1944 J4TBiKC62hCdZv18rBleP6ETfhbPg7pTs8p4ebQbpmtNxRS9Lw3MzQ8Ya5Ybwzj2
1945 NwBSyCtCQl7mrEg4nJqJl4A2EUhnET/oVxU0oTV/SZ3ziGXcY1oG1s6vidV7TZTu
1946 MCRtdSdaM7g3
1947 -----END CERTIFICATE-----`
1948
1949 func TestISOOIDInCertificate(t *testing.T) {
1950 block, _ := pem.Decode([]byte(certISOOID))
1951 if cert, err := ParseCertificate(block.Bytes); err != nil {
1952 t.Errorf("certificate with ISO OID failed to parse: %s", err)
1953 } else if cert.SignatureAlgorithm == UnknownSignatureAlgorithm {
1954 t.Errorf("ISO OID not recognised in certificate")
1955 }
1956 }
1957
1958
1959
1960
1961 const certMultipleRDN = `
1962 -----BEGIN CERTIFICATE-----
1963 MIIFRzCCBC+gAwIBAgIEOl59NTANBgkqhkiG9w0BAQUFADA9MQswCQYDVQQGEwJz
1964 aTEbMBkGA1UEChMSc3RhdGUtaW5zdGl0dXRpb25zMREwDwYDVQQLEwhzaWdvdi1j
1965 YTAeFw0xMjExMTYxMDUyNTdaFw0xNzExMTYxMjQ5MDVaMIGLMQswCQYDVQQGEwJz
1966 aTEbMBkGA1UEChMSc3RhdGUtaW5zdGl0d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EuZ292
1982 LnNpL2NybC9zaWdvdi1jYS5jcmwwKwYDVR0QBCQwIoAPMjAxMjExMTYxMDUyNTda
1983 gQ8yMDE3MTExNjEyNDkwNVowHwYDVR0jBBgwFoAUHvjUU2uzgwbpBAZXAvmlv8ZY
1984 PHIwHQYDVR0OBBYEFGI1Duuu+wTGDZka/xHNbwcbM69ZMAkGA1UdEwQCMAAwGQYJ
1985 KoZIhvZ9B0EABAwwChsEVjcuMQMCA6gwDQYJKoZIhvcNAQEFBQADggEBAHny0K1y
1986 BQznrzDu3DDpBcGYguKU0dvU9rqsV1ua4nxkriSMWjgsX6XJFDdDW60I3P4VWab5
1987 ag5fZzbGqi8kva/CzGgZh+CES0aWCPy+4Gb8lwOTt+854/laaJvd6kgKTER7z7U9
1988 9C86Ch2y4sXNwwwPJ1A9dmrZJZOcJjS/WYZgwaafY2Hdxub5jqPE5nehwYUPVu9R
1989 uH6/skk4OEKcfOtN0hCnISOVuKYyS4ANARWRG5VGHIH06z3lGUVARFRJ61gtAprd
1990 La+fgSS+LVZ+kU2TkeoWAKvGq8MAgDq4D4Xqwekg7WKFeuyusi/NI5rm40XgjBMF
1991 DF72IUofoVt7wo0=
1992 -----END CERTIFICATE-----`
1993
1994 func TestMultipleRDN(t *testing.T) {
1995 block, _ := pem.Decode([]byte(certMultipleRDN))
1996 cert, err := ParseCertificate(block.Bytes)
1997 if err != nil {
1998 t.Fatalf("certificate with two elements in an RDN failed to parse: %v", err)
1999 }
2000
2001 if want := "eportal.mss.edus.si"; cert.Subject.CommonName != want {
2002 t.Errorf("got common name of %q, but want %q", cert.Subject.CommonName, want)
2003 }
2004
2005 if want := "1236484010010"; cert.Subject.SerialNumber != want {
2006 t.Errorf("got serial number of %q, but want %q", cert.Subject.SerialNumber, want)
2007 }
2008 }
2009
2010 func TestSystemCertPool(t *testing.T) {
2011 if runtime.GOOS == "windows" || runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
2012 t.Skip("not implemented on Windows (Issue 16736, 18609) or darwin (Issue 46287)")
2013 }
2014 a, err := SystemCertPool()
2015 if err != nil {
2016 t.Fatal(err)
2017 }
2018 b, err := SystemCertPool()
2019 if err != nil {
2020 t.Fatal(err)
2021 }
2022 if !certPoolEqual(a, b) {
2023 t.Fatal("two calls to SystemCertPool had different results")
2024 }
2025 if ok := b.AppendCertsFromPEM([]byte(`
2026 -----BEGIN CERTIFICATE-----
2027 MIIDBjCCAe6gAwIBAgIRANXM5I3gjuqDfTp/PYrs+u8wDQYJKoZIhvcNAQELBQAw
2028 EjEQMA4GA1UEChMHQWNtZSBDbzAeFw0xODAzMjcxOTU2MjFaFw0xOTAzMjcxOTU2
2029 MjFaMBIxEDAOBgNVBAoTB0FjbWUgQ28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
2030 ggEKAoIBAQDK+9m3rjsO2Djes6bIYQZ3eV29JF09ZrjOrEHLtaKrD6/acsoSoTsf
2031 cQr+rzzztdB5ijWXCS64zo/0OiqBeZUNZ67jVdToa9qW5UYe2H0Y+ZNdfA5GYMFD
2032 yk/l3/uBu3suTZPfXiW2TjEi27Q8ruNUIZ54DpTcs6y2rBRFzadPWwn/VQMlvRXM
2033 jrzl8Y08dgnYmaAHprxVzwMXcQ/Brol+v9GvjaH1DooHqkn8O178wsPQNhdtvN01
2034 IXL46cYdcUwWrE/GX5u+9DaSi+0KWxAPQ+NVD5qUI0CKl4714yGGh7feXMjJdHgl
2035 VG4QJZlJvC4FsURgCHJT6uHGIelnSwhbAgMBAAGjVzBVMA4GA1UdDwEB/wQEAwIF
2036 oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMCAGA1UdEQQZMBeC
2037 FVRlc3RTeXN0ZW1DZXJ0UG9vbC5nbzANBgkqhkiG9w0BAQsFAAOCAQEAwuSRx/VR
2038 BKh2ICxZjL6jBwk/7UlU1XKbhQD96RqkidDNGEc6eLZ90Z5XXTurEsXqdm5jQYPs
2039 1cdcSW+fOSMl7MfW9e5tM66FaIPZl9rKZ1r7GkOfgn93xdLAWe8XHd19xRfDreub
2040 YC8DVqgLASOEYFupVSl76ktPfxkU5KCvmUf3P2PrRybk1qLGFytGxfyice2gHSNI
2041 gify3K/+H/7wCkyFW4xYvzl7WW4mXxoqPRPjQt1J423DhnnQ4G1P8V/vhUpXNXOq
2042 N9IEPnWuihC09cyx/WMQIUlWnaQLHdfpPS04Iez3yy2PdfXJzwfPrja7rNE+skK6
2043 pa/O1nF0AfWOpw==
2044 -----END CERTIFICATE-----
2045 `)); !ok {
2046 t.Fatal("AppendCertsFromPEM failed")
2047 }
2048 if reflect.DeepEqual(a, b) {
2049 t.Fatal("changing one pool modified the other")
2050 }
2051 }
2052
2053 const emptyNameConstraintsPEM = `
2054 -----BEGIN CERTIFICATE-----
2055 MIIC1jCCAb6gAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwKDEmMCQGA1UEAxMdRW1w
2056 dHkgbmFtZSBjb25zdHJhaW50cyBpc3N1ZXIwHhcNMTMwMjAxMDAwMDAwWhcNMjAw
2057 NTMwMTA0ODM4WjAhMR8wHQYDVQQDExZFbXB0eSBuYW1lIGNvbnN0cmFpbnRzMIIB
2058 IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwriElUIt3LCqmJObs+yDoWPD
2059 F5IqgWk6moIobYjPfextZiYU6I3EfvAwoNxPDkN2WowcocUZMJbEeEq5ebBksFnx
2060 f12gBxlIViIYwZAzu7aFvhDMyPKQI3C8CG0ZSC9ABZ1E3umdA3CEueNOmP/TChNq
2061 Cl23+BG1Qb/PJkpAO+GfpWSVhTcV53Mf/cKvFHcjGNrxzdSoq9fyW7a6gfcGEQY0
2062 LVkmwFWUfJ0wT8kaeLr0E0tozkIfo01KNWNzv6NcYP80QOBRDlApWu9ODmEVJHPD
2063 blx4jzTQ3JLa+4DvBNOjVUOp+mgRmjiW0rLdrxwOxIqIOwNjweMCp/hgxX/hTQID
2064 AQABoxEwDzANBgNVHR4EBjAEoAChADANBgkqhkiG9w0BAQsFAAOCAQEAWG+/zUMH
2065 QhP8uNCtgSHyim/vh7wminwAvWgMKxlkLBFns6nZeQqsOV1lABY7U0Zuoqa1Z5nb
2066 6L+iJa4ElREJOi/erLc9uLwBdDCAR0hUTKD7a6i4ooS39DTle87cUnj0MW1CUa6H
2067 v5SsvpYW+1XleYJk/axQOOTcy4Es53dvnZsjXH0EA/QHnn7UV+JmlE3rtVxcYp6M
2068 LYPmRhTioROA/drghicRkiu9hxdPyxkYS16M5g3Zj30jdm+k/6C6PeNtN9YmOOga
2069 nCOSyFYfGhqOANYzpmuV+oIedAsPpIbfIzN8njYUs1zio+1IoI4o8ddM9sCbtPU8
2070 o+WoY6IsCKXV/g==
2071 -----END CERTIFICATE-----`
2072
2073 func TestEmptyNameConstraints(t *testing.T) {
2074 block, _ := pem.Decode([]byte(emptyNameConstraintsPEM))
2075 _, err := ParseCertificate(block.Bytes)
2076 if err == nil {
2077 t.Fatal("unexpected success")
2078 }
2079
2080 const expected = "empty name constraints"
2081 if str := err.Error(); !strings.Contains(str, expected) {
2082 t.Errorf("expected %q in error but got %q", expected, str)
2083 }
2084 }
2085
2086 func TestPKIXNameString(t *testing.T) {
2087 der, err := base64.StdEncoding.DecodeString(certBytes)
2088 if err != nil {
2089 t.Fatal(err)
2090 }
2091 certs, err := ParseCertificates(der)
2092 if err != nil {
2093 t.Fatal(err)
2094 }
2095
2096
2097 rdns := pkix.Name{
2098 Locality: []string{"Gophertown"},
2099 ExtraNames: []pkix.AttributeTypeAndValue{
2100 {Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
2101 }.ToRDNSequence()
2102 nn := pkix.Name{}
2103 nn.FillFromRDNSequence(&rdns)
2104
2105
2106 extra := []pkix.AttributeTypeAndValue{
2107 {Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "backing array"}}
2108 extraNotNil := pkix.Name{
2109 Locality: []string{"Gophertown"},
2110 ExtraNames: extra[:0],
2111 Names: []pkix.AttributeTypeAndValue{
2112 {Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
2113 }
2114
2115 tests := []struct {
2116 dn pkix.Name
2117 want string
2118 }{
2119 {nn, "L=Gophertown,1.2.3.4.5=#130a676f6c616e672e6f7267"},
2120 {extraNotNil, "L=Gophertown"},
2121 {pkix.Name{
2122 CommonName: "Steve Kille",
2123 Organization: []string{"Isode Limited"},
2124 OrganizationalUnit: []string{"RFCs"},
2125 Locality: []string{"Richmond"},
2126 Province: []string{"Surrey"},
2127 StreetAddress: []string{"The Square"},
2128 PostalCode: []string{"TW9 1DT"},
2129 SerialNumber: "RFC 2253",
2130 Country: []string{"GB"},
2131 }, "SERIALNUMBER=RFC 2253,CN=Steve Kille,OU=RFCs,O=Isode Limited,POSTALCODE=TW9 1DT,STREET=The Square,L=Richmond,ST=Surrey,C=GB"},
2132 {certs[0].Subject,
2133 "CN=mail.google.com,O=Google LLC,L=Mountain View,ST=California,C=US"},
2134 {pkix.Name{
2135 Organization: []string{"#Google, Inc. \n-> 'Alphabet\" "},
2136 Country: []string{"US"},
2137 }, "O=\\#Google\\, Inc. \n-\\> 'Alphabet\\\"\\ ,C=US"},
2138 {pkix.Name{
2139 CommonName: "foo.com",
2140 Organization: []string{"Gopher Industries"},
2141 ExtraNames: []pkix.AttributeTypeAndValue{
2142 {Type: asn1.ObjectIdentifier([]int{2, 5, 4, 3}), Value: "bar.com"}},
2143 }, "CN=bar.com,O=Gopher Industries"},
2144 {pkix.Name{
2145 Locality: []string{"Gophertown"},
2146 ExtraNames: []pkix.AttributeTypeAndValue{
2147 {Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
2148 }, "1.2.3.4.5=#130a676f6c616e672e6f7267,L=Gophertown"},
2149
2150 {pkix.Name{
2151 Locality: []string{"Gophertown"},
2152 Names: []pkix.AttributeTypeAndValue{
2153 {Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
2154 }, "L=Gophertown,1.2.3.4.5=#130a676f6c616e672e6f7267"},
2155
2156 {pkix.Name{
2157 Locality: []string{"Gophertown"},
2158 ExtraNames: []pkix.AttributeTypeAndValue{
2159 {Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
2160 Names: []pkix.AttributeTypeAndValue{
2161 {Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 6}), Value: "example.com"}},
2162 }, "1.2.3.4.5=#130a676f6c616e672e6f7267,L=Gophertown"},
2163 }
2164
2165 for i, test := range tests {
2166 if got := test.dn.String(); got != test.want {
2167 t.Errorf("#%d: String() = \n%s\n, want \n%s", i, got, test.want)
2168 }
2169 }
2170
2171 if extra[0].Value != "backing array" {
2172 t.Errorf("the backing array of an empty ExtraNames got modified by String")
2173 }
2174 }
2175
2176 func TestRDNSequenceString(t *testing.T) {
2177
2178
2179
2180 var (
2181 oidCountry = []int{2, 5, 4, 6}
2182 oidOrganization = []int{2, 5, 4, 10}
2183 oidOrganizationalUnit = []int{2, 5, 4, 11}
2184 oidCommonName = []int{2, 5, 4, 3}
2185 )
2186
2187 tests := []struct {
2188 seq pkix.RDNSequence
2189 want string
2190 }{
2191 {
2192 seq: pkix.RDNSequence{
2193 pkix.RelativeDistinguishedNameSET{
2194 pkix.AttributeTypeAndValue{Type: oidCountry, Value: "US"},
2195 },
2196 pkix.RelativeDistinguishedNameSET{
2197 pkix.AttributeTypeAndValue{Type: oidOrganization, Value: "Widget Inc."},
2198 },
2199 pkix.RelativeDistinguishedNameSET{
2200 pkix.AttributeTypeAndValue{Type: oidOrganizationalUnit, Value: "Sales"},
2201 pkix.AttributeTypeAndValue{Type: oidCommonName, Value: "J. Smith"},
2202 },
2203 },
2204 want: "OU=Sales+CN=J. Smith,O=Widget Inc.,C=US",
2205 },
2206 }
2207
2208 for i, test := range tests {
2209 if got := test.seq.String(); got != test.want {
2210 t.Errorf("#%d: String() = \n%s\n, want \n%s", i, got, test.want)
2211 }
2212 }
2213 }
2214
2215 const criticalNameConstraintWithUnknownTypePEM = `
2216 -----BEGIN CERTIFICATE-----
2217 MIIC/TCCAeWgAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwKDEmMCQGA1UEAxMdRW1w
2218 dHkgbmFtZSBjb25zdHJhaW50cyBpc3N1ZXIwHhcNMTMwMjAxMDAwMDAwWhcNMjAw
2219 NTMwMTA0ODM4WjAhMR8wHQYDVQQDExZFbXB0eSBuYW1lIGNvbnN0cmFpbnRzMIIB
2220 IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwriElUIt3LCqmJObs+yDoWPD
2221 F5IqgWk6moIobYjPfextZiYU6I3EfvAwoNxPDkN2WowcocUZMJbEeEq5ebBksFnx
2222 f12gBxlIViIYwZAzu7aFvhDMyPKQI3C8CG0ZSC9ABZ1E3umdA3CEueNOmP/TChNq
2223 Cl23+BG1Qb/PJkpAO+GfpWSVhTcV53Mf/cKvFHcjGNrxzdSoq9fyW7a6gfcGEQY0
2224 LVkmwFWUfJ0wT8kaeLr0E0tozkIfo01KNWNzv6NcYP80QOBRDlApWu9ODmEVJHPD
2225 blx4jzTQ3JLa+4DvBNOjVUOp+mgRmjiW0rLdrxwOxIqIOwNjweMCp/hgxX/hTQID
2226 AQABozgwNjA0BgNVHR4BAf8EKjAooCQwIokgIACrzQAAAAAAAAAAAAAAAP////8A
2227 AAAAAAAAAAAAAAChADANBgkqhkiG9w0BAQsFAAOCAQEAWG+/zUMHQhP8uNCtgSHy
2228 im/vh7wminwAvWgMKxlkLBFns6nZeQqsOV1lABY7U0Zuoqa1Z5nb6L+iJa4ElREJ
2229 Oi/erLc9uLwBdDCAR0hUTKD7a6i4ooS39DTle87cUnj0MW1CUa6Hv5SsvpYW+1Xl
2230 eYJk/axQOOTcy4Es53dvnZsjXH0EA/QHnn7UV+JmlE3rtVxcYp6MLYPmRhTioROA
2231 /drghicRkiu9hxdPyxkYS16M5g3Zj30jdm+k/6C6PeNtN9YmOOganCOSyFYfGhqO
2232 ANYzpmuV+oIedAsPpIbfIzN8njYUs1zio+1IoI4o8ddM9sCbtPU8o+WoY6IsCKXV
2233 /g==
2234 -----END CERTIFICATE-----`
2235
2236 func TestCriticalNameConstraintWithUnknownType(t *testing.T) {
2237 block, _ := pem.Decode([]byte(criticalNameConstraintWithUnknownTypePEM))
2238 cert, err := ParseCertificate(block.Bytes)
2239 if err != nil {
2240 t.Fatalf("unexpected parsing failure: %s", err)
2241 }
2242
2243 if l := len(cert.UnhandledCriticalExtensions); l != 1 {
2244 t.Fatalf("expected one unhandled critical extension, but found %d", l)
2245 }
2246 }
2247
2248 const badIPMaskPEM = `
2249 -----BEGIN CERTIFICATE-----
2250 MIICzzCCAbegAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwHTEbMBkGA1UEAxMSQmFk
2251 IElQIG1hc2sgaXNzdWVyMB4XDTEzMDIwMTAwMDAwMFoXDTIwMDUzMDEwNDgzOFow
2252 FjEUMBIGA1UEAxMLQmFkIElQIG1hc2swggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
2253 ggEKAoIBAQDCuISVQi3csKqYk5uz7IOhY8MXkiqBaTqagihtiM997G1mJhTojcR+
2254 8DCg3E8OQ3ZajByhxRkwlsR4Srl5sGSwWfF/XaAHGUhWIhjBkDO7toW+EMzI8pAj
2255 cLwIbRlIL0AFnUTe6Z0DcIS5406Y/9MKE2oKXbf4EbVBv88mSkA74Z+lZJWFNxXn
2256 cx/9wq8UdyMY2vHN1Kir1/JbtrqB9wYRBjQtWSbAVZR8nTBPyRp4uvQTS2jOQh+j
2257 TUo1Y3O/o1xg/zRA4FEOUCla704OYRUkc8NuXHiPNNDcktr7gO8E06NVQ6n6aBGa
2258 OJbSst2vHA7Eiog7A2PB4wKn+GDFf+FNAgMBAAGjIDAeMBwGA1UdHgEB/wQSMBCg
2259 DDAKhwgBAgME//8BAKEAMA0GCSqGSIb3DQEBCwUAA4IBAQBYb7/NQwdCE/y40K2B
2260 IfKKb++HvCaKfAC9aAwrGWQsEWezqdl5Cqw5XWUAFjtTRm6iprVnmdvov6IlrgSV
2261 EQk6L96stz24vAF0MIBHSFRMoPtrqLiihLf0NOV7ztxSePQxbUJRroe/lKy+lhb7
2262 VeV5gmT9rFA45NzLgSznd2+dmyNcfQQD9AeeftRX4maUTeu1XFxinowtg+ZGFOKh
2263 E4D92uCGJxGSK72HF0/LGRhLXozmDdmPfSN2b6T/oLo942031iY46BqcI5LIVh8a
2264 Go4A1jOma5X6gh50Cw+kht8jM3yeNhSzXOKj7Uigjijx10z2wJu09Tyj5ahjoiwI
2265 pdX+
2266 -----END CERTIFICATE-----`
2267
2268 func TestBadIPMask(t *testing.T) {
2269 block, _ := pem.Decode([]byte(badIPMaskPEM))
2270 _, err := ParseCertificate(block.Bytes)
2271 if err == nil {
2272 t.Fatalf("unexpected success")
2273 }
2274
2275 const expected = "contained invalid mask"
2276 if !strings.Contains(err.Error(), expected) {
2277 t.Fatalf("expected %q in error but got: %s", expected, err)
2278 }
2279 }
2280
2281 const additionalGeneralSubtreePEM = `
2282 -----BEGIN CERTIFICATE-----
2283 MIIG4TCCBMmgAwIBAgIRALss+4rLw2Ia7tFFhxE8g5cwDQYJKoZIhvcNAQELBQAw
2284 bjELMAkGA1UEBhMCTkwxIDAeBgNVBAoMF01pbmlzdGVyaWUgdmFuIERlZmVuc2ll
2285 MT0wOwYDVQQDDDRNaW5pc3RlcmllIHZhbiBEZWZlbnNpZSBDZXJ0aWZpY2F0aWUg
2286 QXV0b3JpdGVpdCAtIEcyMB4XDTEzMDMwNjEyMDM0OVoXDTEzMTEzMDEyMDM1MFow
2287 bDELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUNlcnRpUGF0aCBMTEMxIjAgBgNVBAsT
2288 GUNlcnRpZmljYXRpb24gQXV0aG9yaXRpZXMxITAfBgNVBAMTGENlcnRpUGF0aCBC
2289 cmlkZ2UgQ0EgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADgg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AeBgNVBAoTF01pbmlzdGVyaWUgdmFuIERlZmVuc2ll
2306 gQFjMF0GA1UdIQRWMFQwGgYKYIQQAYdrAQIFAQYMKwYBBAGBu1MBAQECMBoGCmCE
2307 EAGHawECBQIGDCsGAQQBgbtTAQEBAjAaBgpghBABh2sBAgUDBgwrBgEEAYG7UwEB
2308 AQIwHQYDVR0OBBYEFNDCjBM3M3ZKkag84ei3/aKc0d0UMA0GCSqGSIb3DQEBCwUA
2309 A4ICAQAQXFn9jF90/DNFf15JhoGtta/0dNInb14PMu3PAjcdrXYCDPpQZOArTUng
2310 5YT1WuzfmjnXiTsziT3my0r9Mxvz/btKK/lnVOMW4c2q/8sIsIPnnW5ZaRGrsANB
2311 dNDZkzMYmeG2Pfgvd0AQSOrpE/TVgWfu/+MMRWwX9y6VbooBR7BLv7zMuVH0WqLn
2312 6OMFth7fqsThlfMSzkE/RDSaU6n3wXAWT1SIqBITtccRjSUQUFm/q3xrb2cwcZA6
2313 8vdS4hzNd+ttS905ay31Ks4/1Wrm1bH5RhEfRSH0VSXnc0b+z+RyBbmiwtVZqzxE
2314 u3UQg/rAmtLDclLFEzjp8YDTIRYSLwstDbEXO/0ArdGrQm79HQ8i/3ZbP2357myW
2315 i15qd6gMJIgGHS4b8Hc7R1K8LQ9Gm1aLKBEWVNGZlPK/cpXThpVmoEyslN2DHCrc
2316 fbMbjNZpXlTMa+/b9z7Fa4X8dY8u/ELzZuJXJv5Rmqtg29eopFFYDCl0Nkh1XAjo
2317 QejEoHHUvYV8TThHZr6Z6Ib8CECgTehU4QvepkgDXNoNrKRZBG0JhLjkwxh2whZq
2318 nvWBfALC2VuNOM6C0rDY+HmhMlVt0XeqnybD9MuQALMit7Z00Cw2CIjNsBI9xBqD
2319 xKK9CjUb7gzRUWSpB9jGHsvpEMHOzIFhufvH2Bz1XJw+Cl7khw==
2320 -----END CERTIFICATE-----`
2321
2322 func TestAdditionFieldsInGeneralSubtree(t *testing.T) {
2323
2324
2325
2326 block, _ := pem.Decode([]byte(additionalGeneralSubtreePEM))
2327 if _, err := ParseCertificate(block.Bytes); err != nil {
2328 t.Fatalf("failed to parse certificate: %s", err)
2329 }
2330 }
2331
2332 func TestEmptySubject(t *testing.T) {
2333 template := Certificate{
2334 SerialNumber: big.NewInt(1),
2335 DNSNames: []string{"example.com"},
2336 }
2337
2338 derBytes, err := CreateCertificate(rand.Reader, &template, &template, &testPrivateKey.PublicKey, testPrivateKey)
2339 if err != nil {
2340 t.Fatalf("failed to create certificate: %s", err)
2341 }
2342
2343 cert, err := ParseCertificate(derBytes)
2344 if err != nil {
2345 t.Fatalf("failed to parse certificate: %s", err)
2346 }
2347
2348 for _, ext := range cert.Extensions {
2349 if ext.Id.Equal(oidExtensionSubjectAltName) {
2350 if !ext.Critical {
2351 t.Fatal("SAN extension is not critical")
2352 }
2353 return
2354 }
2355 }
2356
2357 t.Fatal("SAN extension is missing")
2358 }
2359
2360
2361
2362 const multipleURLsInCRLDPPEM = `
2363 -----BEGIN CERTIFICATE-----
2364 MIIF4TCCBMmgAwIBAgIQc+6uFePfrahUGpXs8lhiTzANBgkqhkiG9w0BAQsFADCB
2365 8zELMAkGA1UEBhMCRVMxOzA5BgNVBAoTMkFnZW5jaWEgQ2F0YWxhbmEgZGUgQ2Vy
2366 dGlmaWNhY2lvIChOSUYgUS0wODAxMTc2LUkpMSgwJgYDVQQLEx9TZXJ2ZWlzIFB1
2367 YmxpY3MgZGUgQ2VydGlmaWNhY2lvMTUwMwYDVQQLEyxWZWdldSBodHRwczovL3d3
2368 dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbCAoYykwMzE1MDMGA1UECxMsSmVyYXJxdWlh
2369 IEVudGl0YXRzIGRlIENlcnRpZmljYWNpbyBDYXRhbGFuZXMxDzANBgNVBAMTBkVD
2370 LUFDQzAeFw0xNDA5MTgwODIxMDBaFw0zMDA5MTgwODIxMDBaMIGGMQswCQYDVQQG
2371 EwJFUzEzMDEGA1UECgwqQ09OU09SQ0kgQURNSU5JU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cDovL29jc3AuY2F0Y2VydC5jYXQwYgYDVR0fBFswWTBXoFWgU4Yn
2388 aHR0cDovL2Vwc2NkLmNhdGNlcnQubmV0L2NybC9lYy1hY2MuY3JshihodHRwOi8v
2389 ZXBzY2QyLmNhdGNlcnQubmV0L2NybC9lYy1hY2MuY3JsMA0GCSqGSIb3DQEBCwUA
2390 A4IBAQChqFTjlAH5PyIhLjLgEs68CyNNC1+vDuZXRhy22TI83JcvGmQrZosPvVIL
2391 PsUXx+C06Pfqmh48Q9S89X9K8w1SdJxP/rZeGEoRiKpwvQzM4ArD9QxyC8jirxex
2392 3Umg9Ai/sXQ+1lBf6xw4HfUUr1WIp7pNHj0ZWLo106urqktcdeAFWme+/klis5fu
2393 labCSVPuT/QpwakPrtqOhRms8vgpKiXa/eLtL9ZiA28X/Mker0zlAeTA7Z7uAnp6
2394 oPJTlZu1Gg1ZDJueTWWsLlO+P+Wzm3MRRIbcgdRzm4mdO7ubu26SzX/aQXDhuih+
2395 eVxXDTCfs7GUlxnjOp5j559X/N0A
2396 -----END CERTIFICATE-----
2397 `
2398
2399 func TestMultipleURLsInCRLDP(t *testing.T) {
2400 block, _ := pem.Decode([]byte(multipleURLsInCRLDPPEM))
2401 cert, err := ParseCertificate(block.Bytes)
2402 if err != nil {
2403 t.Fatalf("failed to parse certificate: %s", err)
2404 }
2405
2406 want := []string{
2407 "http://epscd.catcert.net/crl/ec-acc.crl",
2408 "http://epscd2.catcert.net/crl/ec-acc.crl",
2409 }
2410 if got := cert.CRLDistributionPoints; !slices.Equal(got, want) {
2411 t.Errorf("CRL distribution points = %#v, want #%v", got, want)
2412 }
2413 }
2414
2415 const hexPKCS1TestPKCS8Key = "30820278020100300d06092a864886f70d0101010500048202623082025e02010002818100cfb1b5bf9685ffa97b4f99df4ff122b70e59ac9b992f3bc2b3dde17d53c1a34928719b02e8fd17839499bfbd515bd6ef99c7a1c47a239718fe36bfd824c0d96060084b5f67f0273443007a24dfaf5634f7772c9346e10eb294c2306671a5a5e719ae24b4de467291bc571014b0e02dec04534d66a9bb171d644b66b091780e8d020301000102818100b595778383c4afdbab95d2bfed12b3f93bb0a73a7ad952f44d7185fd9ec6c34de8f03a48770f2009c8580bcd275e9632714e9a5e3f32f29dc55474b2329ff0ebc08b3ffcb35bc96e6516b483df80a4a59cceb71918cbabf91564e64a39d7e35dce21cb3031824fdbc845dba6458852ec16af5dddf51a8397a8797ae0337b1439024100ea0eb1b914158c70db39031dd8904d6f18f408c85fbbc592d7d20dee7986969efbda081fdf8bc40e1b1336d6b638110c836bfdc3f314560d2e49cd4fbde1e20b024100e32a4e793b574c9c4a94c8803db5152141e72d03de64e54ef2c8ed104988ca780cd11397bc359630d01b97ebd87067c5451ba777cf045ca23f5912f1031308c702406dfcdbbd5a57c9f85abc4edf9e9e29153507b07ce0a7ef6f52e60dcfebe1b8341babd8b789a837485da6c8d55b29bbb142ace3c24a1f5b54b454d01b51e2ad03024100bd6a2b60dee01e1b3bfcef6a2f09ed027c273cdbbaf6ba55a80f6dcc64e4509ee560f84b4f3e076bd03b11e42fe71a3fdd2dffe7e0902c8584f8cad877cdc945024100aa512fa4ada69881f1d8bb8ad6614f192b83200aef5edf4811313d5ef30a86cbd0a90f7b025c71ea06ec6b34db6306c86b1040670fd8654ad7291d066d06d031"
2416 const hexPKCS1TestECKey = "3081a40201010430bdb9839c08ee793d1157886a7a758a3c8b2a17a4df48f17ace57c72c56b4723cf21dcda21d4e1ad57ff034f19fcfd98ea00706052b81040022a16403620004feea808b5ee2429cfcce13c32160e1c960990bd050bb0fdf7222f3decd0a55008e32a6aa3c9062051c4cba92a7a3b178b24567412d43cdd2f882fa5addddd726fe3e208d2c26d733a773a597abb749714df7256ead5105fa6e7b3650de236b50"
2417
2418 var pkcs1MismatchKeyTests = []struct {
2419 hexKey string
2420 errorContains string
2421 }{
2422 {hexKey: hexPKCS1TestPKCS8Key, errorContains: "use ParsePKCS8PrivateKey instead"},
2423 {hexKey: hexPKCS1TestECKey, errorContains: "use ParseECPrivateKey instead"},
2424 }
2425
2426 func TestPKCS1MismatchKeyFormat(t *testing.T) {
2427 for i, test := range pkcs1MismatchKeyTests {
2428 derBytes, _ := hex.DecodeString(test.hexKey)
2429 _, err := ParsePKCS1PrivateKey(derBytes)
2430 if !strings.Contains(err.Error(), test.errorContains) {
2431 t.Errorf("#%d: expected error containing %q, got %s", i, test.errorContains, err)
2432 }
2433 }
2434 }
2435
2436 func TestCreateRevocationList(t *testing.T) {
2437 ec256Priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
2438 if err != nil {
2439 t.Fatalf("Failed to generate ECDSA P256 key: %s", err)
2440 }
2441 _, ed25519Priv, err := ed25519.GenerateKey(rand.Reader)
2442 if err != nil {
2443 t.Fatalf("Failed to generate Ed25519 key: %s", err)
2444 }
2445
2446
2447
2448 utf8CAStr := "MIIEITCCAwmgAwIBAgIUXHXy7NdtDv+ClaHvIvlwCYiI4a4wDQYJKoZIhvcNAQELBQAwgZoxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMR8wHQYDVQQKDBZJbnRlcm5ldCBXaWRnZXRzLCBJbmMuMQwwCgYDVQQLDANXV1cxDTALBgNVBAMMBFJvb3QxIDAeBgkqhkiG9w0BCQEWEWFkbWluQGV4YW1wbGUuY29tMB4XDTIyMDcwODE1MzgyMFoXDTIzMDcwODE1MzgyMFowgZoxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMR8wHQYDVQQKDBZJbnRlcm5ldCBXaWRnZXRzLCBJbmMuMQwwCgYDVQQLDANXV1cxDTALBgNVBAMMBFJvb3QxIDAeBgkqhkiG9w0BCQEWEWFkbWluQGV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmXvp0WNjsZzySWT7Ce5zewQNKq8ujeZGphJ44Vdrwut/b6TcC4iYENds5+7/3PYwBllp3K5TRpCcafSxdhJsvA7/zWlHHNRcJhJLNt9qsKWP6ukI2Iw6OmFMg6kJQ8f67RXkT8HR3v0UqE+lWrA0g+oRuj4erLtfOtSpnl4nsE/Rs2qxbELFWAf7F5qMqH4dUyveWKrNT8eI6YQN+wBg0MAjoKRvDJnBhuo+IvvXX8Aq1QWUcBGPK3or/Ehxy5f/gEmSUXyEU1Ht/vATt2op+eRaEEpBdGRvO+DrKjlcQV2XMN18A9LAX6hCzH43sGye87dj7RZ9yj+waOYNaM7kFQIDAQABo10wWzAdBgNVHQ4EFgQUtbSlrW4hGL2kNjviM6wcCRwvOEEwHwYDVR0jBBgwFoAUtbSlrW4hGL2kNjviM6wcCRwvOEEwDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAbYwDQYJKoZIhvcNAQELBQADggEBAAko82YNNI2n/45L3ya21vufP6nZihIOIxgcRPUMX+IDJZk16qsFdcLgH3KAP8uiVLn8sULuCj35HpViR4IcAk2d+DqfG11l8kY+e5P7nYsViRfy0AatF59/sYlWf+3RdmPXfL70x4mE9OqlMdDm0kR2obps8rng83VLDNvj3R5sBnQwdw6LKLGzaE+RiCTmkH0+P6vnbOJ33su9+9al1+HvJUg3UM1Xq5Bw7TE8DQTetMV3c2Q35RQaJB9pQ4blJOnW9hfnt8yQzU6TU1bU4mRctTm1o1f8btPqUpi+/blhi5MUJK0/myj1XD00pmyfp8QAFl1EfqmTMIBMLg633A0="
2449 utf8CABytes, _ := base64.StdEncoding.DecodeString(utf8CAStr)
2450 utf8CA, _ := ParseCertificate(utf8CABytes)
2451
2452 utf8KeyStr := "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCZe+nRY2OxnPJJZPsJ7nN7BA0qry6N5kamEnjhV2vC639vpNwLiJgQ12zn7v/c9jAGWWncrlNGkJxp9LF2Emy8Dv/NaUcc1FwmEks232qwpY/q6QjYjDo6YUyDqQlDx/rtFeRPwdH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gCAHeaDzzWsudCO4ngwvZ3PGwnwgoaElqrmzRJLYG3SVtGvKOJTpINnNLDGwZ6dEaw1gLyEJ38QY4oJxEULDMiXzVasXQuPkmMAqhUP7D7A1JPw8C4TQ+mOa3XUppHx/CpMl/S4SA5OnmsnvyE5Fv0IveCGVXUkFtAN5rihuXEfhAoGANUkuGU3A0Upk2mzv0JTGP4H95JFG93cqnyPNrYs30M6RkZNgTW27yyr+Nhs4/cMdrg1AYTB0+6ItQWSDmYLs7JEbBE/8L8fdD1irIcygjIHE9nJh96TgZCt61kVGLE8758lOdmoB2rZOpGwi16QIhdQb+IyozYqfX+lQUojL/W0="
2453 utf8KeyBytes, _ := base64.StdEncoding.DecodeString(utf8KeyStr)
2454 utf8KeyRaw, _ := ParsePKCS8PrivateKey(utf8KeyBytes)
2455 utf8Key := utf8KeyRaw.(crypto.Signer)
2456
2457 tests := []struct {
2458 name string
2459 key crypto.Signer
2460 issuer *Certificate
2461 template *RevocationList
2462 expectedError string
2463 }{
2464 {
2465 name: "nil template",
2466 key: ec256Priv,
2467 issuer: nil,
2468 template: nil,
2469 expectedError: "x509: template can not be nil",
2470 },
2471 {
2472 name: "nil issuer",
2473 key: ec256Priv,
2474 issuer: nil,
2475 template: &RevocationList{},
2476 expectedError: "x509: issuer can not be nil",
2477 },
2478 {
2479 name: "issuer doesn't have crlSign key usage bit set",
2480 key: ec256Priv,
2481 issuer: &Certificate{
2482 KeyUsage: KeyUsageCertSign,
2483 },
2484 template: &RevocationList{},
2485 expectedError: "x509: issuer must have the crlSign key usage bit set",
2486 },
2487 {
2488 name: "issuer missing SubjectKeyId",
2489 key: ec256Priv,
2490 issuer: &Certificate{
2491 KeyUsage: KeyUsageCRLSign,
2492 },
2493 template: &RevocationList{},
2494 expectedError: "x509: issuer certificate doesn't contain a subject key identifier",
2495 },
2496 {
2497 name: "nextUpdate before thisUpdate",
2498 key: ec256Priv,
2499 issuer: &Certificate{
2500 KeyUsage: KeyUsageCRLSign,
2501 Subject: pkix.Name{
2502 CommonName: "testing",
2503 },
2504 SubjectKeyId: []byte{1, 2, 3},
2505 },
2506 template: &RevocationList{
2507 ThisUpdate: time.Time{}.Add(time.Hour),
2508 NextUpdate: time.Time{},
2509 },
2510 expectedError: "x509: template.ThisUpdate is after template.NextUpdate",
2511 },
2512 {
2513 name: "nil Number",
2514 key: ec256Priv,
2515 issuer: &Certificate{
2516 KeyUsage: KeyUsageCRLSign,
2517 Subject: pkix.Name{
2518 CommonName: "testing",
2519 },
2520 SubjectKeyId: []byte{1, 2, 3},
2521 },
2522 template: &RevocationList{
2523 ThisUpdate: time.Time{}.Add(time.Hour * 24),
2524 NextUpdate: time.Time{}.Add(time.Hour * 48),
2525 },
2526 expectedError: "x509: template contains nil Number field",
2527 },
2528 {
2529 name: "long Number",
2530 key: ec256Priv,
2531 issuer: &Certificate{
2532 KeyUsage: KeyUsageCRLSign,
2533 Subject: pkix.Name{
2534 CommonName: "testing",
2535 },
2536 SubjectKeyId: []byte{1, 2, 3},
2537 },
2538 template: &RevocationList{
2539 ThisUpdate: time.Time{}.Add(time.Hour * 24),
2540 NextUpdate: time.Time{}.Add(time.Hour * 48),
2541 Number: big.NewInt(0).SetBytes(append([]byte{1}, make([]byte, 20)...)),
2542 },
2543 expectedError: "x509: CRL number exceeds 20 octets",
2544 },
2545 {
2546 name: "long Number (20 bytes, MSB set)",
2547 key: ec256Priv,
2548 issuer: &Certificate{
2549 KeyUsage: KeyUsageCRLSign,
2550 Subject: pkix.Name{
2551 CommonName: "testing",
2552 },
2553 SubjectKeyId: []byte{1, 2, 3},
2554 },
2555 template: &RevocationList{
2556 ThisUpdate: time.Time{}.Add(time.Hour * 24),
2557 NextUpdate: time.Time{}.Add(time.Hour * 48),
2558 Number: big.NewInt(0).SetBytes(append([]byte{255}, make([]byte, 19)...)),
2559 },
2560 expectedError: "x509: CRL number exceeds 20 octets",
2561 },
2562 {
2563 name: "invalid signature algorithm",
2564 key: ec256Priv,
2565 issuer: &Certificate{
2566 KeyUsage: KeyUsageCRLSign,
2567 Subject: pkix.Name{
2568 CommonName: "testing",
2569 },
2570 SubjectKeyId: []byte{1, 2, 3},
2571 },
2572 template: &RevocationList{
2573 SignatureAlgorithm: SHA256WithRSA,
2574 RevokedCertificates: []pkix.RevokedCertificate{
2575 {
2576 SerialNumber: big.NewInt(2),
2577 RevocationTime: time.Time{}.Add(time.Hour),
2578 },
2579 },
2580 Number: big.NewInt(5),
2581 ThisUpdate: time.Time{}.Add(time.Hour * 24),
2582 NextUpdate: time.Time{}.Add(time.Hour * 48),
2583 },
2584 expectedError: "x509: requested SignatureAlgorithm does not match private key type",
2585 },
2586 {
2587 name: "valid",
2588 key: ec256Priv,
2589 issuer: &Certificate{
2590 KeyUsage: KeyUsageCRLSign,
2591 Subject: pkix.Name{
2592 CommonName: "testing",
2593 },
2594 SubjectKeyId: []byte{1, 2, 3},
2595 },
2596 template: &RevocationList{
2597 RevokedCertificateEntries: []RevocationListEntry{
2598 {
2599 SerialNumber: big.NewInt(2),
2600 RevocationTime: time.Time{}.Add(time.Hour),
2601 },
2602 },
2603 Number: big.NewInt(5),
2604 ThisUpdate: time.Time{}.Add(time.Hour * 24),
2605 NextUpdate: time.Time{}.Add(time.Hour * 48),
2606 },
2607 },
2608 {
2609 name: "valid, reason code",
2610 key: ec256Priv,
2611 issuer: &Certificate{
2612 KeyUsage: KeyUsageCRLSign,
2613 Subject: pkix.Name{
2614 CommonName: "testing",
2615 },
2616 SubjectKeyId: []byte{1, 2, 3},
2617 },
2618 template: &RevocationList{
2619 RevokedCertificateEntries: []RevocationListEntry{
2620 {
2621 SerialNumber: big.NewInt(2),
2622 RevocationTime: time.Time{}.Add(time.Hour),
2623 ReasonCode: 1,
2624 },
2625 },
2626 Number: big.NewInt(5),
2627 ThisUpdate: time.Time{}.Add(time.Hour * 24),
2628 NextUpdate: time.Time{}.Add(time.Hour * 48),
2629 },
2630 },
2631 {
2632 name: "valid, extra entry extension",
2633 key: ec256Priv,
2634 issuer: &Certificate{
2635 KeyUsage: KeyUsageCRLSign,
2636 Subject: pkix.Name{
2637 CommonName: "testing",
2638 },
2639 SubjectKeyId: []byte{1, 2, 3},
2640 },
2641 template: &RevocationList{
2642 RevokedCertificateEntries: []RevocationListEntry{
2643 {
2644 SerialNumber: big.NewInt(2),
2645 RevocationTime: time.Time{}.Add(time.Hour),
2646 ExtraExtensions: []pkix.Extension{
2647 {
2648 Id: []int{2, 5, 29, 99},
2649 Value: []byte{5, 0},
2650 },
2651 },
2652 },
2653 },
2654 Number: big.NewInt(5),
2655 ThisUpdate: time.Time{}.Add(time.Hour * 24),
2656 NextUpdate: time.Time{}.Add(time.Hour * 48),
2657 },
2658 },
2659 {
2660 name: "valid, Ed25519 key",
2661 key: ed25519Priv,
2662 issuer: &Certificate{
2663 KeyUsage: KeyUsageCRLSign,
2664 Subject: pkix.Name{
2665 CommonName: "testing",
2666 },
2667 SubjectKeyId: []byte{1, 2, 3},
2668 },
2669 template: &RevocationList{
2670 RevokedCertificateEntries: []RevocationListEntry{
2671 {
2672 SerialNumber: big.NewInt(2),
2673 RevocationTime: time.Time{}.Add(time.Hour),
2674 },
2675 },
2676 Number: big.NewInt(5),
2677 ThisUpdate: time.Time{}.Add(time.Hour * 24),
2678 NextUpdate: time.Time{}.Add(time.Hour * 48),
2679 },
2680 },
2681 {
2682 name: "valid, non-default signature algorithm",
2683 key: ec256Priv,
2684 issuer: &Certificate{
2685 KeyUsage: KeyUsageCRLSign,
2686 Subject: pkix.Name{
2687 CommonName: "testing",
2688 },
2689 SubjectKeyId: []byte{1, 2, 3},
2690 },
2691 template: &RevocationList{
2692 SignatureAlgorithm: ECDSAWithSHA512,
2693 RevokedCertificateEntries: []RevocationListEntry{
2694 {
2695 SerialNumber: big.NewInt(2),
2696 RevocationTime: time.Time{}.Add(time.Hour),
2697 },
2698 },
2699 Number: big.NewInt(5),
2700 ThisUpdate: time.Time{}.Add(time.Hour * 24),
2701 NextUpdate: time.Time{}.Add(time.Hour * 48),
2702 },
2703 },
2704 {
2705 name: "valid, extra extension",
2706 key: ec256Priv,
2707 issuer: &Certificate{
2708 KeyUsage: KeyUsageCRLSign,
2709 Subject: pkix.Name{
2710 CommonName: "testing",
2711 },
2712 SubjectKeyId: []byte{1, 2, 3},
2713 },
2714 template: &RevocationList{
2715 RevokedCertificateEntries: []RevocationListEntry{
2716 {
2717 SerialNumber: big.NewInt(2),
2718 RevocationTime: time.Time{}.Add(time.Hour),
2719 },
2720 },
2721 Number: big.NewInt(5),
2722 ThisUpdate: time.Time{}.Add(time.Hour * 24),
2723 NextUpdate: time.Time{}.Add(time.Hour * 48),
2724 ExtraExtensions: []pkix.Extension{
2725 {
2726 Id: []int{2, 5, 29, 99},
2727 Value: []byte{5, 0},
2728 },
2729 },
2730 },
2731 },
2732 {
2733 name: "valid, deprecated entries with extension",
2734 key: ec256Priv,
2735 issuer: &Certificate{
2736 KeyUsage: KeyUsageCRLSign,
2737 Subject: pkix.Name{
2738 CommonName: "testing",
2739 },
2740 SubjectKeyId: []byte{1, 2, 3},
2741 },
2742 template: &RevocationList{
2743 RevokedCertificates: []pkix.RevokedCertificate{
2744 {
2745 SerialNumber: big.NewInt(2),
2746 RevocationTime: time.Time{}.Add(time.Hour),
2747 Extensions: []pkix.Extension{
2748 {
2749 Id: []int{2, 5, 29, 99},
2750 Value: []byte{5, 0},
2751 },
2752 },
2753 },
2754 },
2755 Number: big.NewInt(5),
2756 ThisUpdate: time.Time{}.Add(time.Hour * 24),
2757 NextUpdate: time.Time{}.Add(time.Hour * 48),
2758 },
2759 },
2760 {
2761 name: "valid, empty list",
2762 key: ec256Priv,
2763 issuer: &Certificate{
2764 KeyUsage: KeyUsageCRLSign,
2765 Subject: pkix.Name{
2766 CommonName: "testing",
2767 },
2768 SubjectKeyId: []byte{1, 2, 3},
2769 },
2770 template: &RevocationList{
2771 Number: big.NewInt(5),
2772 ThisUpdate: time.Time{}.Add(time.Hour * 24),
2773 NextUpdate: time.Time{}.Add(time.Hour * 48),
2774 },
2775 },
2776 {
2777 name: "valid CA with utf8 Subject fields including Email, empty list",
2778 key: utf8Key,
2779 issuer: utf8CA,
2780 template: &RevocationList{
2781 Number: big.NewInt(5),
2782 ThisUpdate: time.Time{}.Add(time.Hour * 24),
2783 NextUpdate: time.Time{}.Add(time.Hour * 48),
2784 },
2785 },
2786 }
2787
2788 for _, tc := range tests {
2789 t.Run(tc.name, func(t *testing.T) {
2790 crl, err := CreateRevocationList(rand.Reader, tc.template, tc.issuer, tc.key)
2791 if err != nil && tc.expectedError == "" {
2792 t.Fatalf("CreateRevocationList failed unexpectedly: %s", err)
2793 } else if err != nil && tc.expectedError != err.Error() {
2794 t.Fatalf("CreateRevocationList failed unexpectedly, wanted: %s, got: %s", tc.expectedError, err)
2795 } else if err == nil && tc.expectedError != "" {
2796 t.Fatalf("CreateRevocationList didn't fail, expected: %s", tc.expectedError)
2797 }
2798 if tc.expectedError != "" {
2799 return
2800 }
2801
2802 parsedCRL, err := ParseRevocationList(crl)
2803 if err != nil {
2804 t.Fatalf("Failed to parse generated CRL: %s", err)
2805 }
2806
2807 if tc.template.SignatureAlgorithm != UnknownSignatureAlgorithm &&
2808 parsedCRL.SignatureAlgorithm != tc.template.SignatureAlgorithm {
2809 t.Fatalf("SignatureAlgorithm mismatch: got %v; want %v.", parsedCRL.SignatureAlgorithm,
2810 tc.template.SignatureAlgorithm)
2811 }
2812
2813 if len(tc.template.RevokedCertificates) > 0 {
2814 if !reflect.DeepEqual(parsedCRL.RevokedCertificates, tc.template.RevokedCertificates) {
2815 t.Fatalf("RevokedCertificates mismatch: got %v; want %v.",
2816 parsedCRL.RevokedCertificates, tc.template.RevokedCertificates)
2817 }
2818 } else {
2819 if len(parsedCRL.RevokedCertificateEntries) != len(tc.template.RevokedCertificateEntries) {
2820 t.Fatalf("RevokedCertificateEntries length mismatch: got %d; want %d.",
2821 len(parsedCRL.RevokedCertificateEntries),
2822 len(tc.template.RevokedCertificateEntries))
2823 }
2824 for i, rce := range parsedCRL.RevokedCertificateEntries {
2825 expected := tc.template.RevokedCertificateEntries[i]
2826 if rce.SerialNumber.Cmp(expected.SerialNumber) != 0 {
2827 t.Fatalf("RevocationListEntry serial mismatch: got %d; want %d.",
2828 rce.SerialNumber, expected.SerialNumber)
2829 }
2830 if !rce.RevocationTime.Equal(expected.RevocationTime) {
2831 t.Fatalf("RevocationListEntry revocation time mismatch: got %v; want %v.",
2832 rce.RevocationTime, expected.RevocationTime)
2833 }
2834 if rce.ReasonCode != expected.ReasonCode {
2835 t.Fatalf("RevocationListEntry reason code mismatch: got %d; want %d.",
2836 rce.ReasonCode, expected.ReasonCode)
2837 }
2838 }
2839 }
2840
2841 if len(parsedCRL.Extensions) != 2+len(tc.template.ExtraExtensions) {
2842 t.Fatalf("Generated CRL has wrong number of extensions, wanted: %d, got: %d", 2+len(tc.template.ExtraExtensions), len(parsedCRL.Extensions))
2843 }
2844 expectedAKI, err := asn1.Marshal(authKeyId{Id: tc.issuer.SubjectKeyId})
2845 if err != nil {
2846 t.Fatalf("asn1.Marshal failed: %s", err)
2847 }
2848 akiExt := pkix.Extension{
2849 Id: oidExtensionAuthorityKeyId,
2850 Value: expectedAKI,
2851 }
2852 if !reflect.DeepEqual(parsedCRL.Extensions[0], akiExt) {
2853 t.Fatalf("Unexpected first extension: got %v, want %v",
2854 parsedCRL.Extensions[0], akiExt)
2855 }
2856 expectedNum, err := asn1.Marshal(tc.template.Number)
2857 if err != nil {
2858 t.Fatalf("asn1.Marshal failed: %s", err)
2859 }
2860 crlExt := pkix.Extension{
2861 Id: oidExtensionCRLNumber,
2862 Value: expectedNum,
2863 }
2864 if !reflect.DeepEqual(parsedCRL.Extensions[1], crlExt) {
2865 t.Fatalf("Unexpected second extension: got %v, want %v",
2866 parsedCRL.Extensions[1], crlExt)
2867 }
2868
2869
2870
2871
2872
2873
2874 if len(tc.issuer.RawSubject) > 0 {
2875 issuerSubj, err := subjectBytes(tc.issuer)
2876 if err != nil {
2877 t.Fatalf("failed to get issuer subject: %s", err)
2878 }
2879 if !bytes.Equal(issuerSubj, parsedCRL.RawIssuer) {
2880 t.Fatalf("Unexpected issuer subject; wanted: %v, got: %v", hex.EncodeToString(issuerSubj), hex.EncodeToString(parsedCRL.RawIssuer))
2881 }
2882 } else {
2883
2884
2885
2886
2887 issuerRDN := tc.issuer.Subject.ToRDNSequence()
2888 var caIssuer pkix.Name
2889 caIssuer.FillFromRDNSequence(&issuerRDN)
2890 if !reflect.DeepEqual(caIssuer, parsedCRL.Issuer) {
2891 t.Fatalf("Expected issuer.Subject, parsedCRL.Issuer to be the same; wanted: %#v, got: %#v", caIssuer, parsedCRL.Issuer)
2892 }
2893 }
2894
2895 if len(parsedCRL.Extensions[2:]) == 0 && len(tc.template.ExtraExtensions) == 0 {
2896
2897
2898 return
2899 }
2900 if !reflect.DeepEqual(parsedCRL.Extensions[2:], tc.template.ExtraExtensions) {
2901 t.Fatalf("Extensions mismatch: got %v; want %v.",
2902 parsedCRL.Extensions[2:], tc.template.ExtraExtensions)
2903 }
2904
2905 if tc.template.Number != nil && parsedCRL.Number == nil {
2906 t.Fatalf("Generated CRL missing Number: got nil, want %s",
2907 tc.template.Number.String())
2908 }
2909 if tc.template.Number != nil && tc.template.Number.Cmp(parsedCRL.Number) != 0 {
2910 t.Fatalf("Generated CRL has wrong Number: got %s, want %s",
2911 parsedCRL.Number.String(), tc.template.Number.String())
2912 }
2913 if !bytes.Equal(parsedCRL.AuthorityKeyId, tc.issuer.SubjectKeyId) {
2914 t.Fatalf("Generated CRL has wrong AuthorityKeyId: got %x, want %x",
2915 parsedCRL.AuthorityKeyId, tc.issuer.SubjectKeyId)
2916 }
2917 })
2918 }
2919 }
2920
2921 func TestRSAPSAParameters(t *testing.T) {
2922 generateParams := func(hashFunc crypto.Hash) []byte {
2923 var hashOID asn1.ObjectIdentifier
2924
2925 switch hashFunc {
2926 case crypto.SHA256:
2927 hashOID = oidSHA256
2928 case crypto.SHA384:
2929 hashOID = oidSHA384
2930 case crypto.SHA512:
2931 hashOID = oidSHA512
2932 }
2933
2934 params := pssParameters{
2935 Hash: pkix.AlgorithmIdentifier{
2936 Algorithm: hashOID,
2937 Parameters: asn1.NullRawValue,
2938 },
2939 MGF: pkix.AlgorithmIdentifier{
2940 Algorithm: oidMGF1,
2941 },
2942 SaltLength: hashFunc.Size(),
2943 TrailerField: 1,
2944 }
2945
2946 mgf1Params := pkix.AlgorithmIdentifier{
2947 Algorithm: hashOID,
2948 Parameters: asn1.NullRawValue,
2949 }
2950
2951 var err error
2952 params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
2953 if err != nil {
2954 t.Fatalf("failed to marshal MGF parameters: %s", err)
2955 }
2956
2957 serialized, err := asn1.Marshal(params)
2958 if err != nil {
2959 t.Fatalf("failed to marshal parameters: %s", err)
2960 }
2961
2962 return serialized
2963 }
2964
2965 for _, detail := range signatureAlgorithmDetails {
2966 if !detail.isRSAPSS {
2967 continue
2968 }
2969 generated := generateParams(detail.hash)
2970 if !bytes.Equal(detail.params.FullBytes, generated) {
2971 t.Errorf("hardcoded parameters for %s didn't match generated parameters: got (generated) %x, wanted (hardcoded) %x", detail.hash, generated, detail.params.FullBytes)
2972 }
2973 }
2974 }
2975
2976 func TestUnknownExtKey(t *testing.T) {
2977 const errorContains = "unknown extended key usage"
2978
2979 template := &Certificate{
2980 SerialNumber: big.NewInt(10),
2981 DNSNames: []string{"foo"},
2982 ExtKeyUsage: []ExtKeyUsage{ExtKeyUsage(-1)},
2983 }
2984 signer, err := rsa.GenerateKey(rand.Reader, 1024)
2985 if err != nil {
2986 t.Errorf("failed to generate key for TestUnknownExtKey")
2987 }
2988
2989 _, err = CreateCertificate(rand.Reader, template, template, signer.Public(), signer)
2990 if !strings.Contains(err.Error(), errorContains) {
2991 t.Errorf("expected error containing %q, got %s", errorContains, err)
2992 }
2993 }
2994
2995 func TestIA5SANEnforcement(t *testing.T) {
2996 k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
2997 if err != nil {
2998 t.Fatalf("ecdsa.GenerateKey failed: %s", err)
2999 }
3000
3001 testURL, err := url.Parse("https://example.com/")
3002 if err != nil {
3003 t.Fatalf("url.Parse failed: %s", err)
3004 }
3005 testURL.RawQuery = "∞"
3006
3007 marshalTests := []struct {
3008 name string
3009 template *Certificate
3010 expectedError string
3011 }{
3012 {
3013 name: "marshal: unicode dNSName",
3014 template: &Certificate{
3015 SerialNumber: big.NewInt(0),
3016 DNSNames: []string{"∞"},
3017 },
3018 expectedError: "x509: \"∞\" cannot be encoded as an IA5String",
3019 },
3020 {
3021 name: "marshal: unicode rfc822Name",
3022 template: &Certificate{
3023 SerialNumber: big.NewInt(0),
3024 EmailAddresses: []string{"∞"},
3025 },
3026 expectedError: "x509: \"∞\" cannot be encoded as an IA5String",
3027 },
3028 {
3029 name: "marshal: unicode uniformResourceIdentifier",
3030 template: &Certificate{
3031 SerialNumber: big.NewInt(0),
3032 URIs: []*url.URL{testURL},
3033 },
3034 expectedError: "x509: \"https://example.com/?∞\" cannot be encoded as an IA5String",
3035 },
3036 }
3037
3038 for _, tc := range marshalTests {
3039 t.Run(tc.name, func(t *testing.T) {
3040 _, err := CreateCertificate(rand.Reader, tc.template, tc.template, k.Public(), k)
3041 if err == nil {
3042 t.Errorf("expected CreateCertificate to fail with template: %v", tc.template)
3043 } else if err.Error() != tc.expectedError {
3044 t.Errorf("unexpected error: got %q, want %q", err.Error(), tc.expectedError)
3045 }
3046 })
3047 }
3048
3049 unmarshalTests := []struct {
3050 name string
3051 cert string
3052 expectedError string
3053 }{
3054 {
3055 name: "unmarshal: unicode dNSName",
3056 cert: "308201083081aea003020102020100300a06082a8648ce3d04030230003022180f30303031303130313030303030305a180f30303031303130313030303030305a30003059301306072a8648ce3d020106082a8648ce3d0301070342000424bcc48180d8d9db794028f2575ebe3cac79f04d7b0d0151c5292e588aac3668c495f108c626168462e0668c9705e08a211dd103a659d2684e0adf8c2bfd47baa315301330110603551d110101ff040730058203e2889e300a06082a8648ce3d04030203490030460221008ac7827ac326a6ee0fa70b2afe99af575ec60b975f820f3c25f60fff43fbccd0022100bffeed93556722d43d13e461d5b3e33efc61f6349300327d3a0196cb6da501c2",
3057 expectedError: "x509: SAN dNSName is malformed",
3058 },
3059 {
3060 name: "unmarshal: unicode rfc822Name",
3061 cert: "308201083081aea003020102020100300a06082a8648ce3d04030230003022180f30303031303130313030303030305a180f30303031303130313030303030305a30003059301306072a8648ce3d020106082a8648ce3d0301070342000405cb4c4ba72aac980f7b11b0285191425e29e196ce7c5df1c83f56886566e517f196657cc1b73de89ab84ce503fd634e2f2af88fde24c63ca536dc3a5eed2665a315301330110603551d110101ff040730058103e2889e300a06082a8648ce3d0403020349003046022100ed1431cd4b9bb03d88d1511a0ec128a51204375764c716280dc36e2a60142c8902210088c96d25cfaf97eea851ff17d87bb6fe619d6546656e1739f35c3566051c3d0f",
3062 expectedError: "x509: SAN rfc822Name is malformed",
3063 },
3064 {
3065 name: "unmarshal: unicode uniformResourceIdentifier",
3066 cert: "3082011b3081c3a003020102020100300a06082a8648ce3d04030230003022180f30303031303130313030303030305a180f30303031303130313030303030305a30003059301306072a8648ce3d020106082a8648ce3d03010703420004ce0a79b511701d9188e1ea76bcc5907f1db51de6cc1a037b803f256e8588145ca409d120288bfeb4e38f3088104674d374b35bb91fc80d768d1d519dbe2b0b5aa32a302830260603551d110101ff041c301a861868747470733a2f2f6578616d706c652e636f6d2f3fe2889e300a06082a8648ce3d0403020347003044022044f4697779fd1dae1e382d2452413c5c5ca67851e267d6bc64a8d164977c172c0220505015e657637aa1945d46e7650b6f59b968fc1508ca8b152c99f782446dfc81",
3067 expectedError: "x509: SAN uniformResourceIdentifier is malformed",
3068 },
3069 }
3070
3071 for _, tc := range unmarshalTests {
3072 der, err := hex.DecodeString(tc.cert)
3073 if err != nil {
3074 t.Fatalf("failed to decode test cert: %s", err)
3075 }
3076 _, err = ParseCertificate(der)
3077 if err == nil {
3078 t.Error("expected CreateCertificate to fail")
3079 } else if err.Error() != tc.expectedError {
3080 t.Errorf("unexpected error: got %q, want %q", err.Error(), tc.expectedError)
3081 }
3082 }
3083 }
3084
3085 func BenchmarkCreateCertificate(b *testing.B) {
3086 template := &Certificate{
3087 SerialNumber: big.NewInt(10),
3088 DNSNames: []string{"example.com"},
3089 }
3090 tests := []struct {
3091 name string
3092 gen func() crypto.Signer
3093 }{
3094 {
3095 name: "RSA 2048",
3096 gen: func() crypto.Signer {
3097 k, err := rsa.GenerateKey(rand.Reader, 2048)
3098 if err != nil {
3099 b.Fatalf("failed to generate test key: %s", err)
3100 }
3101 return k
3102 },
3103 },
3104 {
3105 name: "ECDSA P256",
3106 gen: func() crypto.Signer {
3107 k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
3108 if err != nil {
3109 b.Fatalf("failed to generate test key: %s", err)
3110 }
3111 return k
3112 },
3113 },
3114 }
3115
3116 for _, tc := range tests {
3117 k := tc.gen()
3118 b.ResetTimer()
3119 b.Run(tc.name, func(b *testing.B) {
3120 for i := 0; i < b.N; i++ {
3121 _, err := CreateCertificate(rand.Reader, template, template, k.Public(), k)
3122 if err != nil {
3123 b.Fatalf("failed to create certificate: %s", err)
3124 }
3125 }
3126 })
3127 }
3128 }
3129
3130 type brokenSigner struct {
3131 pub crypto.PublicKey
3132 }
3133
3134 func (bs *brokenSigner) Public() crypto.PublicKey {
3135 return bs.pub
3136 }
3137
3138 func (bs *brokenSigner) Sign(_ io.Reader, _ []byte, _ crypto.SignerOpts) ([]byte, error) {
3139 return []byte{1, 2, 3}, nil
3140 }
3141
3142 func TestCreateCertificateBrokenSigner(t *testing.T) {
3143 template := &Certificate{
3144 SerialNumber: big.NewInt(10),
3145 DNSNames: []string{"example.com"},
3146 }
3147 expectedErr := "signature returned by signer is invalid"
3148 _, err := CreateCertificate(rand.Reader, template, template, testPrivateKey.Public(), &brokenSigner{testPrivateKey.Public()})
3149 if err == nil {
3150 t.Fatal("expected CreateCertificate to fail with a broken signer")
3151 } else if !strings.Contains(err.Error(), expectedErr) {
3152 t.Fatalf("CreateCertificate returned an unexpected error: got %q, want %q", err, expectedErr)
3153 }
3154 }
3155
3156 func TestCreateCertificateLegacy(t *testing.T) {
3157 sigAlg := MD5WithRSA
3158 template := &Certificate{
3159 SerialNumber: big.NewInt(10),
3160 DNSNames: []string{"example.com"},
3161 SignatureAlgorithm: sigAlg,
3162 }
3163 _, err := CreateCertificate(rand.Reader, template, template, testPrivateKey.Public(), &brokenSigner{testPrivateKey.Public()})
3164 if err == nil {
3165 t.Fatal("CreateCertificate didn't fail when SignatureAlgorithm = MD5WithRSA")
3166 }
3167 }
3168
3169 func (s *CertPool) mustCert(t *testing.T, n int) *Certificate {
3170 c, err := s.lazyCerts[n].getCert()
3171 if err != nil {
3172 t.Fatalf("failed to load cert %d: %v", n, err)
3173 }
3174 return c
3175 }
3176
3177 func allCerts(t *testing.T, p *CertPool) []*Certificate {
3178 all := make([]*Certificate, p.len())
3179 for i := range all {
3180 all[i] = p.mustCert(t, i)
3181 }
3182 return all
3183 }
3184
3185
3186
3187 func certPoolEqual(a, b *CertPool) bool {
3188 if (a != nil) != (b != nil) {
3189 return false
3190 }
3191 if a == nil {
3192 return true
3193 }
3194 if !reflect.DeepEqual(a.byName, b.byName) ||
3195 len(a.lazyCerts) != len(b.lazyCerts) {
3196 return false
3197 }
3198 for i := range a.lazyCerts {
3199 la, lb := a.lazyCerts[i], b.lazyCerts[i]
3200 if !bytes.Equal(la.rawSubject, lb.rawSubject) {
3201 return false
3202 }
3203 ca, err := la.getCert()
3204 if err != nil {
3205 panic(err)
3206 }
3207 cb, err := la.getCert()
3208 if err != nil {
3209 panic(err)
3210 }
3211 if !ca.Equal(cb) {
3212 return false
3213 }
3214 }
3215
3216 return true
3217 }
3218
3219 func TestCertificateRequestRoundtripFields(t *testing.T) {
3220 urlA, err := url.Parse("https://example.com/_")
3221 if err != nil {
3222 t.Fatal(err)
3223 }
3224 urlB, err := url.Parse("https://example.org/_")
3225 if err != nil {
3226 t.Fatal(err)
3227 }
3228 in := &CertificateRequest{
3229 DNSNames: []string{"example.com", "example.org"},
3230 EmailAddresses: []string{"a@example.com", "b@example.com"},
3231 IPAddresses: []net.IP{net.IPv4(192, 0, 2, 0), net.IPv6loopback},
3232 URIs: []*url.URL{urlA, urlB},
3233 }
3234 out := marshalAndParseCSR(t, in)
3235
3236 if !slices.Equal(in.DNSNames, out.DNSNames) {
3237 t.Fatalf("Unexpected DNSNames: got %v, want %v", out.DNSNames, in.DNSNames)
3238 }
3239 if !slices.Equal(in.EmailAddresses, out.EmailAddresses) {
3240 t.Fatalf("Unexpected EmailAddresses: got %v, want %v", out.EmailAddresses, in.EmailAddresses)
3241 }
3242 if len(in.IPAddresses) != len(out.IPAddresses) ||
3243 !in.IPAddresses[0].Equal(out.IPAddresses[0]) ||
3244 !in.IPAddresses[1].Equal(out.IPAddresses[1]) {
3245 t.Fatalf("Unexpected IPAddresses: got %v, want %v", out.IPAddresses, in.IPAddresses)
3246 }
3247 if !reflect.DeepEqual(in.URIs, out.URIs) {
3248 t.Fatalf("Unexpected URIs: got %v, want %v", out.URIs, in.URIs)
3249 }
3250 }
3251
3252 func BenchmarkParseCertificate(b *testing.B) {
3253 cases := []struct {
3254 name string
3255 pem string
3256 }{
3257 {
3258 name: "ecdsa leaf",
3259 pem: `-----BEGIN CERTIFICATE-----
3260 MIIINjCCBx6gAwIBAgIQHdQ6oBMoe/MJAAAAAEHzmTANBgkqhkiG9w0BAQsFADBG
3261 MQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExM
3262 QzETMBEGA1UEAxMKR1RTIENBIDFDMzAeFw0yMDEyMDgwOTExMzZaFw0yMTAzMDIw
3263 OTExMzVaMBcxFTATBgNVBAMMDCouZ29vZ2xlLmNvbTBZMBMGByqGSM49AgEGCCqG
3264 SM49AwEHA0IABEFYegyHh1AHRS1nar5+zYJgMACcsIQMtg0YMyK/59ml8ERIt/JF
3265 kXM3XIvQuCJhghUawZrrAcAs8djZF1U9M4mjgg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vZ2xlLnBsggsqLmdvb2dsZS5wdIISKi5nb29nbGVhZGFw
3282 aXMuY29tgg8qLmdvb2dsZWFwaXMuY26CESouZ29vZ2xlY25hcHBzLmNughQqLmdv
3283 b2dsZWNvbW1lcmNlLmNvbYIRKi5nb29nbGV2aWRlby5jb22CDCouZ3N0YXRpYy5j
3284 boINKi5nc3RhdGljLmNvbYISKi5nc3RhdGljY25hcHBzLmNuggoqLmd2dDEuY29t
3285 ggoqLmd2dDIuY29tghQqLm1ldHJpYy5nc3RhdGljLmNvbYIMKi51cmNoaW4uY29t
3286 ghAqLnVybC5nb29nbGUuY29tghMqLndlYXIuZ2tlY25hcHBzLmNughYqLnlvdXR1
3287 YmUtbm9jb29raWUuY29tgg0qLnlvdXR1YmUuY29tghYqLnlvdXR1YmVlZHVjYXRp
3288 b24uY29tghEqLnlvdXR1YmVraWRzLmNvbYIHKi55dC5iZYILKi55dGltZy5jb22C
3289 GmFuZHJvaWQuY2xpZW50cy5nb29nbGUuY29tggthbmRyb2lkLmNvbYIbZGV2ZWxv
3290 cGVyLmFuZHJvaWQuZ29vZ2xlLmNughxkZXZlbG9wZXJzLmFuZHJvaWQuZ29vZ2xl
3291 LmNuggRnLmNvgghnZ3BodC5jboIMZ2tlY25hcHBzLmNuggZnb28uZ2yCFGdvb2ds
3292 ZS1hbmFseXRpY3MuY29tggpnb29nbGUuY29tgg9nb29nbGVjbmFwcHMuY26CEmdv
3293 b2dsZWNvbW1lcmNlLmNvbYIYc291cmNlLmFuZHJvaWQuZ29vZ2xlLmNuggp1cmNo
3294 aW4uY29tggp3d3cuZ29vLmdsggh5b3V0dS5iZYILeW91dHViZS5jb22CFHlvdXR1
3295 YmVlZHVjYXRpb24uY29tgg95b3V0dWJla2lkcy5jb22CBXl0LmJlMCEGA1UdIAQa
3296 MBgwCAYGZ4EMAQIBMAwGCisGAQQB1nkCBQMwNQYDVR0fBC4wLDAqoCigJoYkaHR0
3297 cDovL2NybC5wa2kuZ29vZy9ndHNyMS9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5hbmRyb2lkLmdvb2ds
3349 ZS5jboIKdXJjaGluLmNvbYIKd3d3Lmdvby5nbIIIeW91dHUuYmWCC3lvdXR1YmUu
3350 Y29tghR5b3V0dWJlZWR1Y2F0aW9uLmNvbYIPeW91dHViZWtpZHMuY29tggV5dC5i
3351 ZTAhBgNVHSAEGjAYMAgGBmeBDAECAjAMBgorBgEEAdZ5AgUDMDMGA1UdHwQsMCow
3352 KKAmoCSGImh0dHA6Ly9jcmwucGtpLmdvb2cvR1RTMU8xY29yZS5jcmwwEwYKKwYB
3353 BAHWeQIEAwEB/wQCBQAwDQYJKoZIhvcNAQELBQADggEBAHh9/ozYUGRd+W5akWlM
3354 4WvX808TK2oUISnagbxCCFZ2trpg2oi03CJf4o4o3Je5Qzzz10s22oQY6gPHAR0B
3355 QHzrpqAveQw9D5vd8xjgtQ/SAujPzPKNQee5511rS7/EKW9I83ccd5XhhoEyx8A1
3356 /65RTS+2hKpJKTMkr0yHBPJV7kUW+n/KIef5YaSOA9VYK7hyH0niDpvm9EmoqvWS
3357 U5xAFAe/Xrrq3sxTuDJPQA8alk6h/ql5Klkw6dL53csiPka/MevDqdifWkzuT/6n
3358 YK/ePeJzPD17FA9V+N1rcuF3Wk29AZvCOSasdIkIuE82vGr3dfNrsrn9E9lWIbCr
3359 Qc4=
3360 -----END CERTIFICATE-----`,
3361 },
3362 }
3363 for _, c := range cases {
3364 b.Run(c.name, func(b *testing.B) {
3365 pemBlock, _ := pem.Decode([]byte(c.pem))
3366 b.ReportAllocs()
3367 b.ResetTimer()
3368 for i := 0; i < b.N; i++ {
3369 _, err := ParseCertificate(pemBlock.Bytes)
3370 if err != nil {
3371 b.Fatal(err)
3372 }
3373 }
3374 })
3375 }
3376 }
3377
3378 func TestParseCertificateRawEquals(t *testing.T) {
3379 p, _ := pem.Decode([]byte(pemCertificate))
3380 cert, err := ParseCertificate(p.Bytes)
3381 if err != nil {
3382 t.Fatalf("failed to parse certificate: %s", err)
3383 }
3384 if !bytes.Equal(p.Bytes, cert.Raw) {
3385 t.Fatalf("unexpected Certificate.Raw\ngot: %x\nwant: %x\n", cert.Raw, p.Bytes)
3386 }
3387 }
3388
3389
3390
3391
3392 const mismatchingSigAlgIDPEM = `-----BEGIN CERTIFICATE-----
3393 MIIBBzCBrqADAgECAgEAMAoGCCqGSM49BAMCMAAwIhgPMDAwMTAxMDEwMDAwMDBa
3394 GA8wMDAxMDEwMTAwMDAwMFowADBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABOqV
3395 EDuVXxwZgIU3+dOwv1SsMu0xuV48hf7xmK8n7sAMYgllB+96DnPqBeboJj4snYnx
3396 0AcE0PDVQ1l4Z3YXsQWjFTATMBEGA1UdEQEB/wQHMAWCA2FzZDAKBggqhkjOPQQD
3397 AwNIADBFAiBi1jz/T2HT5nAfrD7zsgR+68qh7Erc6Q4qlxYBOgKG4QIhAOtjIn+Q
3398 tA+bq+55P3ntxTOVRq0nv1mwnkjwt9cQR9Fn
3399 -----END CERTIFICATE-----`
3400
3401
3402
3403
3404 const mismatchingSigAlgParamPEM = `-----BEGIN CERTIFICATE-----
3405 MIIBCTCBrqADAgECAgEAMAoGCCqGSM49BAMCMAAwIhgPMDAwMTAxMDEwMDAwMDBa
3406 GA8wMDAxMDEwMTAwMDAwMFowADBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABOqV
3407 EDuVXxwZgIU3+dOwv1SsMu0xuV48hf7xmK8n7sAMYgllB+96DnPqBeboJj4snYnx
3408 0AcE0PDVQ1l4Z3YXsQWjFTATMBEGA1UdEQEB/wQHMAWCA2FzZDAMBggqhkjOPQQD
3409 AgUAA0gAMEUCIGLWPP9PYdPmcB+sPvOyBH7ryqHsStzpDiqXFgE6AobhAiEA62Mi
3410 f5C0D5ur7nk/ee3FM5VGrSe/WbCeSPC31xBH0Wc=
3411 -----END CERTIFICATE-----`
3412
3413 func TestSigAlgMismatch(t *testing.T) {
3414 for _, certPEM := range []string{mismatchingSigAlgIDPEM, mismatchingSigAlgParamPEM} {
3415 b, _ := pem.Decode([]byte(certPEM))
3416 if b == nil {
3417 t.Fatalf("couldn't decode test certificate")
3418 }
3419 _, err := ParseCertificate(b.Bytes)
3420 if err == nil {
3421 t.Fatalf("expected ParseCertificate to fail")
3422 }
3423 expected := "x509: inner and outer signature algorithm identifiers don't match"
3424 if err.Error() != expected {
3425 t.Errorf("unexpected error from ParseCertificate: got %q, want %q", err.Error(), expected)
3426 }
3427 }
3428 }
3429
3430 const optionalAuthKeyIDPEM = `-----BEGIN CERTIFICATE-----
3431 MIIFEjCCBHugAwIBAgICAQwwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1Zh
3432 bGlDZXJ0IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIElu
3433 Yy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDIgUG9saWN5IFZhbGlkYXRpb24g
3434 QXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAe
3435 BgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTA0MDYyOTE3MzkxNloX
3436 DTI0MDYyOTE3MzkxNlowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0YXJmaWVs
3437 ZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBDbGFzcyAy
3438 IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIDANBgkqhkiG9w0BAQEFAAOCAQ0A
3439 MIIBCAKCAQEAtzLI/ulxpgSFrQwRZN/OTe/IAxiHP6Gr+zymn/DDodrU2G4rU5D7
3440 JKQ+hPCe6F/s5SdE9SimP3ve4CrwyK9TL57KBQGTHo9mHDmnTfpatnMEJWbrd3/n
3441 WcZKmSUUVOsmx/N/GdUwcI+vsEYq/63rKe3Xn6oEh6PU+YmlNF/bQ5GCNtlmPLG4
3442 uYL9nDo+EMg77wZlZnq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USV
3458 FxdzPcwl
3459 -----END CERTIFICATE-----`
3460
3461 func TestAuthKeyIdOptional(t *testing.T) {
3462 b, _ := pem.Decode([]byte(optionalAuthKeyIDPEM))
3463 if b == nil {
3464 t.Fatalf("couldn't decode test certificate")
3465 }
3466 _, err := ParseCertificate(b.Bytes)
3467 if err != nil {
3468 t.Fatalf("ParseCertificate to failed to parse certificate with optional authority key identifier fields: %s", err)
3469 }
3470 }
3471
3472 const largeOIDPEM = `
3473 Certificate:
3474 Data:
3475 Version: 3 (0x2)
3476 Serial Number:
3477 da:ba:53:19:1b:09:4b:82:b2:89:26:7d:c7:6f:a0:02
3478 Signature Algorithm: sha256WithRSAEncryption
3479 Issuer: O = Acme Co
3480 Validity
3481 Not Before: Dec 21 16:59:27 2021 GMT
3482 Not After : Dec 21 16:59:27 2022 GMT
3483 Subject: O = Acme Co
3484 Subject Public Key Info:
3485 Public Key Algorithm: rsaEncryption
3486 RSA Public-Key: (2048 bit)
3487 Modulus:
3488 00:bf:17:16:d8:bc:29:9c:16:e5:76:b4:93:15:78:
3489 ad:6e:45:c5:4a:63:46:a1:b2:76:71:65:51:9c:14:
3490 c4:ea:74:13:e4:34:df:2f:2c:65:11:e8:56:52:69:
3491 11:f9:0e:fc:77:bb:63:a8:7c:1a:c6:a1:7b:6e:6c:
3492 e7:18:25:25:c9:e8:fb:06:7f:a2:a9:98:fe:2a:bc:
3493 8a:b3:75:b6:b8:7d:b6:c9:6b:29:08:32:22:10:cb:
3494 8d:d6:60:c8:83:ad:f5:58:91:d6:11:e8:55:56:fb:
3495 8f:a3:a2:9f:48:cb:79:e4:65:4a:8c:a6:52:64:9f:
3496 99:38:35:d4:d5:ac:6f:cf:a0:cb:42:8c:07:eb:21:
3497 17:31:3a:eb:91:7b:62:43:a4:75:5f:ef:a7:2f:94:
3498 f8:69:0b:d4:ec:09:e6:00:c0:8c:dd:07:63:0b:e4:
3499 77:aa:60:18:3c:a0:e0:ae:0a:ea:0e:52:3b:b4:fa:
3500 6a:30:1b:50:62:21:73:53:33:01:60:a1:6b:99:58:
3501 00:f3:77:c6:0f:46:19:ca:c2:5d:cd:f5:e2:52:4d:
3502 84:94:23:d3:32:2f:ae:5f:da:43:a1:19:95:d2:17:
3503 dd:49:14:b4:d9:48:1c:08:13:93:8e:d5:09:43:21:
3504 b6:ce:52:e8:87:bb:d2:60:0d:c6:4e:bf:c5:93:6a:
3505 c6:bf
3506 Exponent: 65537 (0x10001)
3507 X509v3 extensions:
3508 X509v3 Key Usage: critical
3509 Digital Signature, Key Encipherment
3510 X509v3 Extended Key Usage:
3511 TLS Web Server Authentication
3512 X509v3 Basic Constraints: critical
3513 CA:FALSE
3514 X509v3 Subject Alternative Name:
3515 DNS:longOID.example
3516 X509v3 Certificate Policies:
3517 Policy: 1.3.6.1.4.1.311.21.8.1492336001
3518
3519 Signature Algorithm: sha256WithRSAEncryption
3520 72:77:8b:de:48:fb:6d:9a:94:b1:be:d4:90:7d:4c:e6:d3:79:
3521 fa:fb:fc:3e:d5:3d:e9:a0:ce:28:2b:2f:94:77:3f:87:f8:9c:
3522 9f:91:1c:f3:f6:58:91:15:6b:24:b9:ca:ae:9f:ee:ca:c8:31:
3523 db:1a:3d:bb:6b:83:6d:bc:81:8b:a1:79:d5:3e:bb:dd:93:fe:
3524 35:3e:b7:99:e0:d6:eb:58:0c:fd:42:73:dc:49:da:e2:b7:ae:
3525 15:ee:e6:cc:aa:ef:91:41:9a:18:46:8d:4a:39:65:a2:85:3c:
3526 7f:0c:41:f8:0b:9c:e8:1f:35:36:60:8d:8c:e0:8e:18:b1:06:
3527 57:d0:4e:c4:c3:cd:8f:6f:e7:76:02:52:da:03:43:61:2b:b3:
3528 bf:19:fd:73:0d:6a:0b:b4:b6:cb:a9:6f:70:4e:53:2a:54:07:
3529 b3:74:fd:85:49:57:5b:23:8d:8c:6b:53:2b:09:e8:41:a5:80:
3530 3f:69:1b:11:d1:6b:13:35:2e:f9:d6:50:15:d9:91:38:42:43:
3531 e9:17:af:67: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3549 WAz9QnPcSdrit64V7ubMqu+RQZoYRo1KOWWihTx/DEH4C5zoHzU2YI2M4I4YsQZX
3550 0E7Ew82Pb+d2AlLaA0NhK7O/Gf1zDWoLtLbLqW9wTlMqVAezdP2FSVdbI42Ma1Mr
3551 CehBpYA/aRsR0WsTNS751lAV2ZE4QkPpF69n2Zak0WpPzLSnjkgfAHJp3k3xc6RH
3552 Emfp+Qc+eXWQQrjUtf3RfjUE9wAEz/E2vg8ngR+muohs
3553 -----END CERTIFICATE-----`
3554
3555 func TestLargeOID(t *testing.T) {
3556
3557 b, _ := pem.Decode([]byte(largeOIDPEM))
3558 if b == nil {
3559 t.Fatalf("couldn't decode test certificate")
3560 }
3561 _, err := ParseCertificate(b.Bytes)
3562 if err != nil {
3563 t.Fatalf("ParseCertificate to failed to parse certificate with large OID: %s", err)
3564 }
3565 }
3566
3567 const uniqueIDPEM = `-----BEGIN CERTIFICATE-----
3568 MIIFsDCCBJigAwIBAgIILOyC1ydafZMwDQYJKoZIhvcNAQEFBQAwgY4xgYswgYgG
3569 A1UEAx6BgABNAGkAYwByAG8AcwBvAGYAdAAgAEYAbwByAGUAZgByAG8AbgB0ACAA
3570 VABNAEcAIABIAFQAVABQAFMAIABJAG4AcwBwAGUAYwB0AGkAbwBuACAAQwBlAHIA
3571 dABpAGYAaQBjAGEAdABpAG8AbgAgAEEAdQB0AGgAbwByAGkAdAB5MB4XDTE0MDEx
3572 ODAwNDEwMFoXDTE1MTExNTA5Mzc1NlowgZYxCzAJBgNVBAYTAklEMRAwDgYDVQQI
3573 EwdqYWthcnRhMRIwEAYDVQQHEwlJbmRvbmVzaWExHDAaBgNVBAoTE3N0aG9ub3Jl
3574 aG90ZWxyZXNvcnQxHDAaBgNVBAsTE3N0aG9ub3JlaG90ZWxyZXNvcnQxJTAjBgNV
3575 BAMTHG1haWwuc3Rob25vcmVob3RlbHJlc29ydC5jb20wggEiMA0GCSqGSIb3DQEB
3576 AQUAA4IBDwAwggEKAoIBAQCvuu0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cgBpAHQAeYIIcKhXEmBXr0IwDQYJKoZIhvcNAQEFBQAD
3593 ggEBABlSxyCMr3+ANr+WmPSjyN5YCJBgnS0IFCwJAzIYP87bcTye/U8eQ2+E6PqG
3594 Q7Huj7nfHEw9qnGo+HNyPp1ad3KORzXDb54c6xEoi+DeuPzYHPbn4c3hlH49I0aQ
3595 eWW2w4RslSWpLvO6Y7Lboyz2/Thk/s2kd4RHxkkWpH2ltPqJuYYg3X6oM5+gIFHJ
3596 WGnh+ojZ5clKvS5yXh3Wkj78M6sb32KfcBk0Hx6NkCYPt60ODYmWtvqwtw6r73u5
3597 TnTYWRNvo2svX69TriL+CkHY9O1Hkwf2It5zHl3gNiKTJVaak8AuEz/CKWZneovt
3598 yYLwhUhg3PX5Co1VKYE+9TxloiE=
3599 -----END CERTIFICATE-----`
3600
3601 func TestParseUniqueID(t *testing.T) {
3602 b, _ := pem.Decode([]byte(uniqueIDPEM))
3603 if b == nil {
3604 t.Fatalf("couldn't decode test certificate")
3605 }
3606 cert, err := ParseCertificate(b.Bytes)
3607 if err != nil {
3608 t.Fatalf("ParseCertificate to failed to parse certificate with unique identifier id: %s", err)
3609 }
3610 if len(cert.Extensions) != 7 {
3611 t.Fatalf("unexpected number of extensions (probably because the extension section was not parsed): got %d, want 7", len(cert.Extensions))
3612 }
3613 }
3614
3615 func TestDisableSHA1ForCertOnly(t *testing.T) {
3616 t.Setenv("GODEBUG", "")
3617
3618 tmpl := &Certificate{
3619 SerialNumber: big.NewInt(1),
3620 NotBefore: time.Now().Add(-time.Hour),
3621 NotAfter: time.Now().Add(time.Hour),
3622 SignatureAlgorithm: SHA1WithRSA,
3623 BasicConstraintsValid: true,
3624 IsCA: true,
3625 KeyUsage: KeyUsageCertSign | KeyUsageCRLSign,
3626 }
3627 certDER, err := CreateCertificate(rand.Reader, tmpl, tmpl, rsaPrivateKey.Public(), rsaPrivateKey)
3628 if err != nil {
3629 t.Fatalf("failed to generate test cert: %s", err)
3630 }
3631 cert, err := ParseCertificate(certDER)
3632 if err != nil {
3633 t.Fatalf("failed to parse test cert: %s", err)
3634 }
3635
3636 err = cert.CheckSignatureFrom(cert)
3637 if err == nil {
3638 t.Error("expected CheckSignatureFrom to fail")
3639 } else if _, ok := err.(InsecureAlgorithmError); !ok {
3640 t.Errorf("expected InsecureAlgorithmError error, got %T", err)
3641 }
3642
3643 crlDER, err := CreateRevocationList(rand.Reader, &RevocationList{
3644 SignatureAlgorithm: SHA1WithRSA,
3645 Number: big.NewInt(1),
3646 ThisUpdate: time.Now().Add(-time.Hour),
3647 NextUpdate: time.Now().Add(time.Hour),
3648 }, cert, rsaPrivateKey)
3649 if err != nil {
3650 t.Fatalf("failed to generate test CRL: %s", err)
3651 }
3652 crl, err := ParseRevocationList(crlDER)
3653 if err != nil {
3654 t.Fatalf("failed to parse test CRL: %s", err)
3655 }
3656
3657 if err = crl.CheckSignatureFrom(cert); err != nil {
3658 t.Errorf("unexpected error: %s", err)
3659 }
3660
3661
3662
3663
3664 ocspTBSHex := "30819fa2160414884451ff502a695e2d88f421bad90cf2cecbea7c180f32303133303631383037323434335a30743072304a300906052b0e03021a0500041448b60d38238df8456e4ee5843ea394111802979f0414884451ff502a695e2d88f421bad90cf2cecbea7c021100f78b13b946fc9635d8ab49de9d2148218000180f32303133303631383037323434335aa011180f32303133303632323037323434335a"
3665 ocspTBS, err := hex.DecodeString(ocspTBSHex)
3666 if err != nil {
3667 t.Fatalf("failed to decode OCSP response TBS hex: %s", err)
3668 }
3669
3670 err = cert.CheckSignature(SHA1WithRSA, ocspTBS, nil)
3671 if err != rsa.ErrVerification {
3672 t.Errorf("unexpected error: %s", err)
3673 }
3674 }
3675
3676 func TestParseRevocationList(t *testing.T) {
3677 derBytes := fromBase64(derCRLBase64)
3678 certList, err := ParseRevocationList(derBytes)
3679 if err != nil {
3680 t.Errorf("error parsing: %s", err)
3681 return
3682 }
3683 numCerts := len(certList.RevokedCertificateEntries)
3684 numCertsDeprecated := len(certList.RevokedCertificateEntries)
3685 expected := 88
3686 if numCerts != expected || numCertsDeprecated != expected {
3687 t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected)
3688 }
3689 }
3690
3691 func TestRevocationListCheckSignatureFrom(t *testing.T) {
3692 goodKey, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
3693 if err != nil {
3694 t.Fatalf("failed to generate test key: %s", err)
3695 }
3696 badKey, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
3697 if err != nil {
3698 t.Fatalf("failed to generate test key: %s", err)
3699 }
3700 tests := []struct {
3701 name string
3702 issuer *Certificate
3703 err string
3704 }{
3705 {
3706 name: "valid",
3707 issuer: &Certificate{
3708 Version: 3,
3709 BasicConstraintsValid: true,
3710 IsCA: true,
3711 PublicKeyAlgorithm: ECDSA,
3712 PublicKey: goodKey.Public(),
3713 },
3714 },
3715 {
3716 name: "valid, key usage set",
3717 issuer: &Certificate{
3718 Version: 3,
3719 BasicConstraintsValid: true,
3720 IsCA: true,
3721 PublicKeyAlgorithm: ECDSA,
3722 PublicKey: goodKey.Public(),
3723 KeyUsage: KeyUsageCRLSign,
3724 },
3725 },
3726 {
3727 name: "invalid issuer, wrong key usage",
3728 issuer: &Certificate{
3729 Version: 3,
3730 BasicConstraintsValid: true,
3731 IsCA: true,
3732 PublicKeyAlgorithm: ECDSA,
3733 PublicKey: goodKey.Public(),
3734 KeyUsage: KeyUsageCertSign,
3735 },
3736 err: "x509: invalid signature: parent certificate cannot sign this kind of certificate",
3737 },
3738 {
3739 name: "invalid issuer, no basic constraints/ca",
3740 issuer: &Certificate{
3741 Version: 3,
3742 PublicKeyAlgorithm: ECDSA,
3743 PublicKey: goodKey.Public(),
3744 },
3745 err: "x509: invalid signature: parent certificate cannot sign this kind of certificate",
3746 },
3747 {
3748 name: "invalid issuer, unsupported public key type",
3749 issuer: &Certificate{
3750 Version: 3,
3751 BasicConstraintsValid: true,
3752 IsCA: true,
3753 PublicKeyAlgorithm: UnknownPublicKeyAlgorithm,
3754 PublicKey: goodKey.Public(),
3755 },
3756 err: "x509: cannot verify signature: algorithm unimplemented",
3757 },
3758 {
3759 name: "wrong key",
3760 issuer: &Certificate{
3761 Version: 3,
3762 BasicConstraintsValid: true,
3763 IsCA: true,
3764 PublicKeyAlgorithm: ECDSA,
3765 PublicKey: badKey.Public(),
3766 },
3767 err: "x509: ECDSA verification failure",
3768 },
3769 }
3770
3771 crlIssuer := &Certificate{
3772 BasicConstraintsValid: true,
3773 IsCA: true,
3774 PublicKeyAlgorithm: ECDSA,
3775 PublicKey: goodKey.Public(),
3776 KeyUsage: KeyUsageCRLSign,
3777 SubjectKeyId: []byte{1, 2, 3},
3778 }
3779 for _, tc := range tests {
3780 t.Run(tc.name, func(t *testing.T) {
3781 crlDER, err := CreateRevocationList(rand.Reader, &RevocationList{Number: big.NewInt(1)}, crlIssuer, goodKey)
3782 if err != nil {
3783 t.Fatalf("failed to generate CRL: %s", err)
3784 }
3785 crl, err := ParseRevocationList(crlDER)
3786 if err != nil {
3787 t.Fatalf("failed to parse test CRL: %s", err)
3788 }
3789 err = crl.CheckSignatureFrom(tc.issuer)
3790 if err != nil && err.Error() != tc.err {
3791 t.Errorf("unexpected error: got %s, want %s", err, tc.err)
3792 } else if err == nil && tc.err != "" {
3793 t.Errorf("CheckSignatureFrom did not fail: want %s", tc.err)
3794 }
3795 })
3796 }
3797 }
3798
3799 func TestOmitEmptyExtensions(t *testing.T) {
3800 k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
3801 if err != nil {
3802 t.Fatal(err)
3803 }
3804 tmpl := &Certificate{
3805 SerialNumber: big.NewInt(1),
3806 Subject: pkix.Name{
3807 CommonName: ":)",
3808 },
3809 NotAfter: time.Now().Add(time.Hour),
3810 NotBefore: time.Now().Add(-time.Hour),
3811 }
3812 der, err := CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
3813 if err != nil {
3814 t.Fatal(err)
3815 }
3816
3817 emptyExtSeq := []byte{0xA3, 0x02, 0x30, 0x00}
3818 if bytes.Contains(der, emptyExtSeq) {
3819 t.Error("DER encoding contains the an empty extensions SEQUENCE")
3820 }
3821 }
3822
3823 var negativeSerialCert = `-----BEGIN CERTIFICATE-----
3824 MIIBBTCBraADAgECAgH/MAoGCCqGSM49BAMCMA0xCzAJBgNVBAMTAjopMB4XDTIy
3825 MDQxNDIzNTYwNFoXDTIyMDQxNTAxNTYwNFowDTELMAkGA1UEAxMCOikwWTATBgcq
3826 hkjOPQIBBggqhkjOPQMBBwNCAAQ9ezsIsj+q17K87z/PXE/rfGRN72P/Wyn5d6oo
3827 5M0ZbSatuntMvfKdX79CQxXAxN4oXk3Aov4jVSG12AcDI8ShMAoGCCqGSM49BAMC
3828 A0cAMEQCIBzfBU5eMPT6m5lsR6cXaJILpAaiD9YxOl4v6dT3rzEjAiBHmjnHmAss
3829 RqUAyJKFzqZxOlK2q4j2IYnuj5+LrLGbQA==
3830 -----END CERTIFICATE-----`
3831
3832 func TestParseNegativeSerial(t *testing.T) {
3833 pemBlock, _ := pem.Decode([]byte(negativeSerialCert))
3834 _, err := ParseCertificate(pemBlock.Bytes)
3835 if err == nil {
3836 t.Fatal("parsed certificate with negative serial")
3837 }
3838 }
3839
3840 func TestCreateNegativeSerial(t *testing.T) {
3841 k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
3842 if err != nil {
3843 t.Fatal(err)
3844 }
3845 tmpl := &Certificate{
3846 SerialNumber: big.NewInt(-1),
3847 Subject: pkix.Name{
3848 CommonName: ":)",
3849 },
3850 NotAfter: time.Now().Add(time.Hour),
3851 NotBefore: time.Now().Add(-time.Hour),
3852 }
3853 expectedErr := "x509: serial number must be positive"
3854 _, err = CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
3855 if err == nil || err.Error() != expectedErr {
3856 t.Errorf("CreateCertificate returned unexpected error: want %q, got %q", expectedErr, err)
3857 }
3858 }
3859
3860 const dupExtCert = `-----BEGIN CERTIFICATE-----
3861 MIIBrjCCARegAwIBAgIBATANBgkqhkiG9w0BAQsFADAPMQ0wCwYDVQQDEwR0ZXN0
3862 MCIYDzAwMDEwMTAxMDAwMDAwWhgPMDAwMTAxMDEwMDAwMDBaMA8xDTALBgNVBAMT
3863 BHRlc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMiFchnHms9l9NninAIz
3864 SkY9acwl9Bk2AtmJrNCenFpiA17AcOO5q8DJYwdXi6WPKlVgcyH+ysW8XMWkq+CP
3865 yhtF/+LMzl9odaUF2iUy3vgTC5gxGLWH5URVssx21Und2Pm2f4xyou5IVxbS9dxy
3866 jLvV9PEY9BIb0H+zFthjhihDAgMBAAGjFjAUMAgGAioDBAIFADAIBgIqAwQCBQAw
3867 DQYJKoZIhvcNAQELBQADgYEAlhQ4TQQKIQ8GUyzGiN/75TCtQtjhMGemxc0cNgre
3868 d9rmm4DjydH0t7/sMCB56lQrfhJNplguzsbjFW4l245KbNKHfLiqwEGUgZjBNKur
3869 ot6qX/skahLtt0CNOaFIge75HVKe/69OrWQGdp18dkay/KS4Glu8YMKIjOhfrUi1
3870 NZA=
3871 -----END CERTIFICATE-----`
3872
3873 func TestDuplicateExtensionsCert(t *testing.T) {
3874 b, _ := pem.Decode([]byte(dupExtCert))
3875 if b == nil {
3876 t.Fatalf("couldn't decode test certificate")
3877 }
3878 _, err := ParseCertificate(b.Bytes)
3879 if err == nil {
3880 t.Fatal("ParseCertificate should fail when parsing certificate with duplicate extensions")
3881 }
3882 }
3883
3884 const dupExtCSR = `-----BEGIN CERTIFICATE REQUEST-----
3885 MIIBczCB3QIBADAPMQ0wCwYDVQQDEwR0ZXN0MIGfMA0GCSqGSIb3DQEBAQUAA4GN
3886 ADCBiQKBgQC5PbxMGVJ8aLF9lq/EvGObXTRMB7ieiZL9N+DJZg1n/ECCnZLIvYrr
3887 ZmmDV7YZsClgxKGfjJB0RQFFyZElFM9EfHEs8NJdidDKCRdIhDXQWRyhXKevHvdm
3888 CQNKzUeoxvdHpU/uscSkw6BgUzPyLyTx9A6ye2ix94z8Y9hGOBO2DQIDAQABoCUw
3889 IwYJKoZIhvcNAQkOMRYwFDAIBgIqAwQCBQAwCAYCKgMEAgUAMA0GCSqGSIb3DQEB
3890 CwUAA4GBAHROEsE7URk1knXmBnQtIHwoq663vlMcX3Hes58pUy020rWP8QkocA+X
3891 VF18/phg3p5ILlS4fcbbP2bEeV0pePo2k00FDPsJEKCBAX2LKxbU7Vp2OuV2HM2+
3892 VLOVx0i+/Q7fikp3hbN1JwuMTU0v2KL/IKoUcZc02+5xiYrnOIt5
3893 -----END CERTIFICATE REQUEST-----`
3894
3895 func TestDuplicateExtensionsCSR(t *testing.T) {
3896 b, _ := pem.Decode([]byte(dupExtCSR))
3897 if b == nil {
3898 t.Fatalf("couldn't decode test CSR")
3899 }
3900 _, err := ParseCertificateRequest(b.Bytes)
3901 if err == nil {
3902 t.Fatal("ParseCertificateRequest should fail when parsing CSR with duplicate extensions")
3903 }
3904 }
3905
3906 const dupAttCSR = `-----BEGIN CERTIFICATE REQUEST-----
3907 MIIBbDCB1gIBADAPMQ0wCwYDVQQDEwR0ZXN0MIGfMA0GCSqGSIb3DQEBAQUAA4GN
3908 ADCBiQKBgQCj5Po3PKO/JNuxr+B+WNfMIzqqYztdlv+mTQhT0jOR5rTkUvxeeHH8
3909 YclryES2dOISjaUOTmOAr5GQIIdQl4Ql33Cp7ZR/VWcRn+qvTak0Yow+xVsDo0n4
3910 7IcvvP6CJ7FRoYBUakVczeXLxCjLwdyK16VGJM06eRzDLykPxpPwLQIDAQABoB4w
3911 DQYCKgMxBwwFdGVzdDEwDQYCKgMxBwwFdGVzdDIwDQYJKoZIhvcNAQELBQADgYEA
3912 UJ8hsHxtnIeqb2ufHnQFJO+wEJhx2Uxm/BTuzHOeffuQkwATez4skZ7SlX9exgb7
3913 6jRMRilqb4F7f8w+uDoqxRrA9zc8mwY16zPsyBhRet+ZGbj/ilgvGmtZ21qZZ/FU
3914 0pJFJIVLM3l49Onr5uIt5+hCWKwHlgE0nGpjKLR3cMg=
3915 -----END CERTIFICATE REQUEST-----`
3916
3917 func TestDuplicateAttributesCSR(t *testing.T) {
3918 b, _ := pem.Decode([]byte(dupAttCSR))
3919 if b == nil {
3920 t.Fatalf("couldn't decode test CSR")
3921 }
3922 _, err := ParseCertificateRequest(b.Bytes)
3923 if err != nil {
3924 t.Fatal("ParseCertificateRequest should succeed when parsing CSR with duplicate attributes")
3925 }
3926 }
3927
3928 func TestCertificateOIDPolicies(t *testing.T) {
3929 template := Certificate{
3930 SerialNumber: big.NewInt(1),
3931 Subject: pkix.Name{CommonName: "Cert"},
3932 NotBefore: time.Unix(1000, 0),
3933 NotAfter: time.Unix(100000, 0),
3934 PolicyIdentifiers: []asn1.ObjectIdentifier{[]int{1, 2, 3}},
3935 }
3936
3937 var expectPolicyIdentifiers = []asn1.ObjectIdentifier{
3938 []int{1, 2, 3},
3939 }
3940
3941 var expectPolicies = []OID{
3942 mustNewOIDFromInts(t, []uint64{1, 2, 3}),
3943 }
3944
3945 certDER, err := CreateCertificate(rand.Reader, &template, &template, rsaPrivateKey.Public(), rsaPrivateKey)
3946 if err != nil {
3947 t.Fatalf("CreateCertificate() unexpected error: %v", err)
3948 }
3949
3950 cert, err := ParseCertificate(certDER)
3951 if err != nil {
3952 t.Fatalf("ParseCertificate() unexpected error: %v", err)
3953 }
3954
3955 if !slices.EqualFunc(cert.PolicyIdentifiers, expectPolicyIdentifiers, slices.Equal) {
3956 t.Errorf("cert.PolicyIdentifiers = %v, want: %v", cert.PolicyIdentifiers, expectPolicyIdentifiers)
3957 }
3958
3959 if !slices.EqualFunc(cert.Policies, expectPolicies, OID.Equal) {
3960 t.Errorf("cert.Policies = %v, want: %v", cert.Policies, expectPolicies)
3961 }
3962 }
3963
3964 func TestCertificatePoliciesGODEBUG(t *testing.T) {
3965 template := Certificate{
3966 SerialNumber: big.NewInt(1),
3967 Subject: pkix.Name{CommonName: "Cert"},
3968 NotBefore: time.Unix(1000, 0),
3969 NotAfter: time.Unix(100000, 0),
3970 PolicyIdentifiers: []asn1.ObjectIdentifier{[]int{1, 2, 3}},
3971 Policies: []OID{mustNewOIDFromInts(t, []uint64{1, 2, math.MaxUint32 + 1})},
3972 }
3973
3974 expectPolicies := []OID{mustNewOIDFromInts(t, []uint64{1, 2, 3})}
3975 certDER, err := CreateCertificate(rand.Reader, &template, &template, rsaPrivateKey.Public(), rsaPrivateKey)
3976 if err != nil {
3977 t.Fatalf("CreateCertificate() unexpected error: %v", err)
3978 }
3979
3980 cert, err := ParseCertificate(certDER)
3981 if err != nil {
3982 t.Fatalf("ParseCertificate() unexpected error: %v", err)
3983 }
3984
3985 if !slices.EqualFunc(cert.Policies, expectPolicies, OID.Equal) {
3986 t.Errorf("cert.Policies = %v, want: %v", cert.Policies, expectPolicies)
3987 }
3988
3989 t.Setenv("GODEBUG", "x509usepolicies=1")
3990 expectPolicies = []OID{mustNewOIDFromInts(t, []uint64{1, 2, math.MaxUint32 + 1})}
3991
3992 certDER, err = CreateCertificate(rand.Reader, &template, &template, rsaPrivateKey.Public(), rsaPrivateKey)
3993 if err != nil {
3994 t.Fatalf("CreateCertificate() unexpected error: %v", err)
3995 }
3996
3997 cert, err = ParseCertificate(certDER)
3998 if err != nil {
3999 t.Fatalf("ParseCertificate() unexpected error: %v", err)
4000 }
4001
4002 if !slices.EqualFunc(cert.Policies, expectPolicies, OID.Equal) {
4003 t.Errorf("cert.Policies = %v, want: %v", cert.Policies, expectPolicies)
4004 }
4005 }
4006
4007 func TestGob(t *testing.T) {
4008
4009
4010 cert := new(Certificate)
4011 err := gob.NewEncoder(io.Discard).Encode(cert)
4012 if err != nil {
4013 t.Fatal(err)
4014 }
4015 }
4016
4017 func TestRejectCriticalAKI(t *testing.T) {
4018 template := Certificate{
4019 SerialNumber: big.NewInt(1),
4020 Subject: pkix.Name{CommonName: "Cert"},
4021 NotBefore: time.Unix(1000, 0),
4022 NotAfter: time.Unix(100000, 0),
4023 ExtraExtensions: []pkix.Extension{
4024 {
4025 Id: asn1.ObjectIdentifier{2, 5, 29, 35},
4026 Critical: true,
4027 Value: []byte{1, 2, 3},
4028 },
4029 },
4030 }
4031 certDER, err := CreateCertificate(rand.Reader, &template, &template, rsaPrivateKey.Public(), rsaPrivateKey)
4032 if err != nil {
4033 t.Fatalf("CreateCertificate() unexpected error: %v", err)
4034 }
4035 expectedErr := "x509: authority key identifier incorrectly marked critical"
4036 _, err = ParseCertificate(certDER)
4037 if err == nil || err.Error() != expectedErr {
4038 t.Fatalf("ParseCertificate() unexpected error: %v, want: %s", err, expectedErr)
4039 }
4040 }
4041
4042 func TestRejectCriticalAIA(t *testing.T) {
4043 template := Certificate{
4044 SerialNumber: big.NewInt(1),
4045 Subject: pkix.Name{CommonName: "Cert"},
4046 NotBefore: time.Unix(1000, 0),
4047 NotAfter: time.Unix(100000, 0),
4048 ExtraExtensions: []pkix.Extension{
4049 {
4050 Id: asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 1},
4051 Critical: true,
4052 Value: []byte{1, 2, 3},
4053 },
4054 },
4055 }
4056 certDER, err := CreateCertificate(rand.Reader, &template, &template, rsaPrivateKey.Public(), rsaPrivateKey)
4057 if err != nil {
4058 t.Fatalf("CreateCertificate() unexpected error: %v", err)
4059 }
4060 expectedErr := "x509: authority info access incorrectly marked critical"
4061 _, err = ParseCertificate(certDER)
4062 if err == nil || err.Error() != expectedErr {
4063 t.Fatalf("ParseCertificate() unexpected error: %v, want: %s", err, expectedErr)
4064 }
4065 }
4066
4067 func TestRejectCriticalSKI(t *testing.T) {
4068 template := Certificate{
4069 SerialNumber: big.NewInt(1),
4070 Subject: pkix.Name{CommonName: "Cert"},
4071 NotBefore: time.Unix(1000, 0),
4072 NotAfter: time.Unix(100000, 0),
4073 ExtraExtensions: []pkix.Extension{
4074 {
4075 Id: asn1.ObjectIdentifier{2, 5, 29, 14},
4076 Critical: true,
4077 Value: []byte{1, 2, 3},
4078 },
4079 },
4080 }
4081 certDER, err := CreateCertificate(rand.Reader, &template, &template, rsaPrivateKey.Public(), rsaPrivateKey)
4082 if err != nil {
4083 t.Fatalf("CreateCertificate() unexpected error: %v", err)
4084 }
4085 expectedErr := "x509: subject key identifier incorrectly marked critical"
4086 _, err = ParseCertificate(certDER)
4087 if err == nil || err.Error() != expectedErr {
4088 t.Fatalf("ParseCertificate() unexpected error: %v, want: %s", err, expectedErr)
4089 }
4090 }
4091
View as plain text