github.com/zmap/zcrypto@v0.0.0-20240512203510-0fef58d9a9db/ct/asn1/asn1.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package asn1 implements parsing of DER-encoded ASN.1 data structures, 6 // as defined in ITU-T Rec X.690. 7 // 8 // See also “A Layman's Guide to a Subset of ASN.1, BER, and DER,” 9 // http://luca.ntop.org/Teaching/Appunti/asn1.html. 10 // 11 // START CT CHANGES 12 // This is a fork of the Go standard library ASN.1 implementation 13 // (encoding/asn1). The main difference is that this version tries to correct 14 // for errors (e.g. use of tagPrintableString when the string data is really 15 // ISO8859-1 - a common error present in many x509 certificates in the wild.) 16 // END CT CHANGES 17 package asn1 18 19 // ASN.1 is a syntax for specifying abstract objects and BER, DER, PER, XER etc 20 // are different encoding formats for those objects. Here, we'll be dealing 21 // with DER, the Distinguished Encoding Rules. DER is used in X.509 because 22 // it's fast to parse and, unlike BER, has a unique encoding for every object. 23 // When calculating hashes over objects, it's important that the resulting 24 // bytes be the same at both ends and DER removes this margin of error. 25 // 26 // ASN.1 is very complex and this package doesn't attempt to implement 27 // everything by any means. 28 29 import ( 30 // START CT CHANGES 31 "errors" 32 "fmt" 33 "strconv" 34 // END CT CHANGES 35 "math/big" 36 "reflect" 37 // START CT CHANGES 38 "strings" 39 // END CT CHANGES 40 "time" 41 ) 42 43 // A StructuralError suggests that the ASN.1 data is valid, but the Go type 44 // which is receiving it doesn't match. 45 type StructuralError struct { 46 Msg string 47 } 48 49 func (e StructuralError) Error() string { return "asn1: structure error: " + e.Msg } 50 51 // A SyntaxError suggests that the ASN.1 data is invalid. 52 type SyntaxError struct { 53 Msg string 54 } 55 56 func (e SyntaxError) Error() string { return "asn1: syntax error: " + e.Msg } 57 58 // We start by dealing with each of the primitive types in turn. 59 60 // BOOLEAN 61 62 func parseBool(bytes []byte) (ret bool, err error) { 63 if len(bytes) != 1 { 64 err = SyntaxError{"invalid boolean"} 65 return 66 } 67 68 // DER demands that "If the encoding represents the boolean value TRUE, 69 // its single contents octet shall have all eight bits set to one." 70 // Thus only 0 and 255 are valid encoded values. 71 switch bytes[0] { 72 case 0: 73 ret = false 74 case 0xff: 75 ret = true 76 default: 77 err = SyntaxError{"invalid boolean"} 78 } 79 80 return 81 } 82 83 // INTEGER 84 85 // parseInt64 treats the given bytes as a big-endian, signed integer and 86 // returns the result. 87 func parseInt64(bytes []byte) (ret int64, err error) { 88 if len(bytes) > 8 { 89 // We'll overflow an int64 in this case. 90 err = StructuralError{"integer too large"} 91 return 92 } 93 for bytesRead := 0; bytesRead < len(bytes); bytesRead++ { 94 ret <<= 8 95 ret |= int64(bytes[bytesRead]) 96 } 97 98 // Shift up and down in order to sign extend the result. 99 ret <<= 64 - uint8(len(bytes))*8 100 ret >>= 64 - uint8(len(bytes))*8 101 return 102 } 103 104 // parseInt treats the given bytes as a big-endian, signed integer and returns 105 // the result. 106 func parseInt32(bytes []byte) (int32, error) { 107 ret64, err := parseInt64(bytes) 108 if err != nil { 109 return 0, err 110 } 111 if ret64 != int64(int32(ret64)) { 112 return 0, StructuralError{"integer too large"} 113 } 114 return int32(ret64), nil 115 } 116 117 var bigOne = big.NewInt(1) 118 119 // parseBigInt treats the given bytes as a big-endian, signed integer and returns 120 // the result. 121 func parseBigInt(bytes []byte) *big.Int { 122 ret := new(big.Int) 123 if len(bytes) > 0 && bytes[0]&0x80 == 0x80 { 124 // This is a negative number. 125 notBytes := make([]byte, len(bytes)) 126 for i := range notBytes { 127 notBytes[i] = ^bytes[i] 128 } 129 ret.SetBytes(notBytes) 130 ret.Add(ret, bigOne) 131 ret.Neg(ret) 132 return ret 133 } 134 ret.SetBytes(bytes) 135 return ret 136 } 137 138 // BIT STRING 139 140 // BitString is the structure to use when you want an ASN.1 BIT STRING type. A 141 // bit string is padded up to the nearest byte in memory and the number of 142 // valid bits is recorded. Padding bits will be zero. 143 type BitString struct { 144 Bytes []byte // bits packed into bytes. 145 BitLength int // length in bits. 146 } 147 148 // At returns the bit at the given index. If the index is out of range it 149 // returns false. 150 func (b BitString) At(i int) int { 151 if i < 0 || i >= b.BitLength { 152 return 0 153 } 154 x := i / 8 155 y := 7 - uint(i%8) 156 return int(b.Bytes[x]>>y) & 1 157 } 158 159 // RightAlign returns a slice where the padding bits are at the beginning. The 160 // slice may share memory with the BitString. 161 func (b BitString) RightAlign() []byte { 162 shift := uint(8 - (b.BitLength % 8)) 163 if shift == 8 || len(b.Bytes) == 0 { 164 return b.Bytes 165 } 166 167 a := make([]byte, len(b.Bytes)) 168 a[0] = b.Bytes[0] >> shift 169 for i := 1; i < len(b.Bytes); i++ { 170 a[i] = b.Bytes[i-1] << (8 - shift) 171 a[i] |= b.Bytes[i] >> shift 172 } 173 174 return a 175 } 176 177 // parseBitString parses an ASN.1 bit string from the given byte slice and returns it. 178 func parseBitString(bytes []byte) (ret BitString, err error) { 179 if len(bytes) == 0 { 180 err = SyntaxError{"zero length BIT STRING"} 181 return 182 } 183 paddingBits := int(bytes[0]) 184 if paddingBits > 7 || 185 len(bytes) == 1 && paddingBits > 0 || 186 bytes[len(bytes)-1]&((1<<bytes[0])-1) != 0 { 187 err = SyntaxError{"invalid padding bits in BIT STRING"} 188 return 189 } 190 ret.BitLength = (len(bytes)-1)*8 - paddingBits 191 ret.Bytes = bytes[1:] 192 return 193 } 194 195 // OBJECT IDENTIFIER 196 197 // An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER. 198 type ObjectIdentifier []int 199 200 // Equal reports whether oi and other represent the same identifier. 201 func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool { 202 if len(oi) != len(other) { 203 return false 204 } 205 for i := 0; i < len(oi); i++ { 206 if oi[i] != other[i] { 207 return false 208 } 209 } 210 211 return true 212 } 213 func (oi ObjectIdentifier) String() string { 214 var s string 215 for i, v := range oi { 216 if i > 0 { 217 s += "." 218 } 219 s += strconv.Itoa(v) 220 } 221 return s 222 } 223 224 // parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and 225 // returns it. An object identifier is a sequence of variable length integers 226 // that are assigned in a hierarchy. 227 func parseObjectIdentifier(bytes []byte) (s []int, err error) { 228 if len(bytes) == 0 { 229 err = SyntaxError{"zero length OBJECT IDENTIFIER"} 230 return 231 } 232 233 // In the worst case, we get two elements from the first byte (which is 234 // encoded differently) and then every varint is a single byte long. 235 s = make([]int, len(bytes)+1) 236 237 // The first varint is 40*value1 + value2: 238 // According to this packing, value1 can take the values 0, 1 and 2 only. 239 // When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2, 240 // then there are no restrictions on value2. 241 v, offset, err := parseBase128Int(bytes, 0) 242 if err != nil { 243 return 244 } 245 if v < 80 { 246 s[0] = v / 40 247 s[1] = v % 40 248 } else { 249 s[0] = 2 250 s[1] = v - 80 251 } 252 253 i := 2 254 for ; offset < len(bytes); i++ { 255 v, offset, err = parseBase128Int(bytes, offset) 256 if err != nil { 257 return 258 } 259 s[i] = v 260 } 261 s = s[0:i] 262 return 263 } 264 265 // ENUMERATED 266 267 // An Enumerated is represented as a plain int. 268 type Enumerated int 269 270 // FLAG 271 272 // A Flag accepts any data and is set to true if present. 273 type Flag bool 274 275 // parseBase128Int parses a base-128 encoded int from the given offset in the 276 // given byte slice. It returns the value and the new offset. 277 func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err error) { 278 offset = initOffset 279 for shifted := 0; offset < len(bytes); shifted++ { 280 if shifted > 4 { 281 err = StructuralError{"base 128 integer too large"} 282 return 283 } 284 ret <<= 7 285 b := bytes[offset] 286 ret |= int(b & 0x7f) 287 offset++ 288 if b&0x80 == 0 { 289 return 290 } 291 } 292 err = SyntaxError{"truncated base 128 integer"} 293 return 294 } 295 296 // UTCTime 297 298 func parseUTCTime(bytes []byte) (ret time.Time, err error) { 299 s := string(bytes) 300 ret, err = time.Parse("0601021504Z0700", s) 301 if err != nil { 302 ret, err = time.Parse("060102150405Z0700", s) 303 } 304 if err == nil && ret.Year() >= 2050 { 305 // UTCTime only encodes times prior to 2050. See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1 306 ret = ret.AddDate(-100, 0, 0) 307 } 308 309 return 310 } 311 312 // parseGeneralizedTime parses the GeneralizedTime from the given byte slice 313 // and returns the resulting time. 314 func parseGeneralizedTime(bytes []byte) (ret time.Time, err error) { 315 return time.Parse("20060102150405Z0700", string(bytes)) 316 } 317 318 // PrintableString 319 320 // parsePrintableString parses a ASN.1 PrintableString from the given byte 321 // array and returns it. 322 func parsePrintableString(bytes []byte) (ret string, err error) { 323 for _, b := range bytes { 324 if !isPrintable(b) { 325 err = SyntaxError{"PrintableString contains invalid character"} 326 return 327 } 328 } 329 ret = string(bytes) 330 return 331 } 332 333 // isPrintable returns true iff the given b is in the ASN.1 PrintableString set. 334 func isPrintable(b byte) bool { 335 return 'a' <= b && b <= 'z' || 336 'A' <= b && b <= 'Z' || 337 '0' <= b && b <= '9' || 338 '\'' <= b && b <= ')' || 339 '+' <= b && b <= '/' || 340 b == ' ' || 341 b == ':' || 342 b == '=' || 343 b == '?' || 344 // This is technically not allowed in a PrintableString. 345 // However, x509 certificates with wildcard strings don't 346 // always use the correct string type so we permit it. 347 b == '*' 348 } 349 350 // IA5String 351 352 // parseIA5String parses a ASN.1 IA5String (ASCII string) from the given 353 // byte slice and returns it. 354 func parseIA5String(bytes []byte) (ret string, err error) { 355 for _, b := range bytes { 356 if b >= 0x80 { 357 err = SyntaxError{"IA5String contains invalid character"} 358 return 359 } 360 } 361 ret = string(bytes) 362 return 363 } 364 365 // T61String 366 367 // parseT61String parses a ASN.1 T61String (8-bit clean string) from the given 368 // byte slice and returns it. 369 func parseT61String(bytes []byte) (ret string, err error) { 370 return string(bytes), nil 371 } 372 373 // UTF8String 374 375 // parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte 376 // array and returns it. 377 func parseUTF8String(bytes []byte) (ret string, err error) { 378 return string(bytes), nil 379 } 380 381 // A RawValue represents an undecoded ASN.1 object. 382 type RawValue struct { 383 Class, Tag int 384 IsCompound bool 385 Bytes []byte 386 FullBytes []byte // includes the tag and length 387 } 388 389 // RawContent is used to signal that the undecoded, DER data needs to be 390 // preserved for a struct. To use it, the first field of the struct must have 391 // this type. It's an error for any of the other fields to have this type. 392 type RawContent []byte 393 394 // Tagging 395 396 // parseTagAndLength parses an ASN.1 tag and length pair from the given offset 397 // into a byte slice. It returns the parsed data and the new offset. SET and 398 // SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we 399 // don't distinguish between ordered and unordered objects in this code. 400 func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err error) { 401 offset = initOffset 402 b := bytes[offset] 403 offset++ 404 ret.class = int(b >> 6) 405 ret.isCompound = b&0x20 == 0x20 406 ret.tag = int(b & 0x1f) 407 408 // If the bottom five bits are set, then the tag number is actually base 128 409 // encoded afterwards 410 if ret.tag == 0x1f { 411 ret.tag, offset, err = parseBase128Int(bytes, offset) 412 if err != nil { 413 return 414 } 415 } 416 if offset >= len(bytes) { 417 err = SyntaxError{"truncated tag or length"} 418 return 419 } 420 b = bytes[offset] 421 offset++ 422 if b&0x80 == 0 { 423 // The length is encoded in the bottom 7 bits. 424 ret.length = int(b & 0x7f) 425 } else { 426 // Bottom 7 bits give the number of length bytes to follow. 427 numBytes := int(b & 0x7f) 428 if numBytes == 0 { 429 err = SyntaxError{"indefinite length found (not DER)"} 430 return 431 } 432 ret.length = 0 433 for i := 0; i < numBytes; i++ { 434 if offset >= len(bytes) { 435 err = SyntaxError{"truncated tag or length"} 436 return 437 } 438 b = bytes[offset] 439 offset++ 440 if ret.length >= 1<<23 { 441 // We can't shift ret.length up without 442 // overflowing. 443 err = StructuralError{"length too large"} 444 return 445 } 446 ret.length <<= 8 447 ret.length |= int(b) 448 if ret.length == 0 { 449 // DER requires that lengths be minimal. 450 err = StructuralError{"superfluous leading zeros in length"} 451 return 452 } 453 } 454 } 455 456 return 457 } 458 459 // parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse 460 // a number of ASN.1 values from the given byte slice and returns them as a 461 // slice of Go values of the given type. 462 func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err error) { 463 expectedTag, compoundType, ok := getUniversalType(elemType) 464 if !ok { 465 err = StructuralError{"unknown Go type for slice"} 466 return 467 } 468 469 // First we iterate over the input and count the number of elements, 470 // checking that the types are correct in each case. 471 numElements := 0 472 for offset := 0; offset < len(bytes); { 473 var t tagAndLength 474 t, offset, err = parseTagAndLength(bytes, offset) 475 if err != nil { 476 return 477 } 478 // We pretend that GENERAL STRINGs are PRINTABLE STRINGs so 479 // that a sequence of them can be parsed into a []string. 480 if t.tag == tagGeneralString { 481 t.tag = tagPrintableString 482 } 483 if t.class != classUniversal || t.isCompound != compoundType || t.tag != expectedTag { 484 err = StructuralError{"sequence tag mismatch"} 485 return 486 } 487 if invalidLength(offset, t.length, len(bytes)) { 488 err = SyntaxError{"truncated sequence"} 489 return 490 } 491 offset += t.length 492 numElements++ 493 } 494 ret = reflect.MakeSlice(sliceType, numElements, numElements) 495 params := fieldParameters{} 496 offset := 0 497 for i := 0; i < numElements; i++ { 498 offset, err = parseField(ret.Index(i), bytes, offset, params) 499 if err != nil { 500 return 501 } 502 } 503 return 504 } 505 506 var ( 507 bitStringType = reflect.TypeOf(BitString{}) 508 objectIdentifierType = reflect.TypeOf(ObjectIdentifier{}) 509 enumeratedType = reflect.TypeOf(Enumerated(0)) 510 flagType = reflect.TypeOf(Flag(false)) 511 timeType = reflect.TypeOf(time.Time{}) 512 rawValueType = reflect.TypeOf(RawValue{}) 513 rawContentsType = reflect.TypeOf(RawContent(nil)) 514 bigIntType = reflect.TypeOf(new(big.Int)) 515 ) 516 517 // invalidLength returns true iff offset + length > sliceLength, or if the 518 // addition would overflow. 519 func invalidLength(offset, length, sliceLength int) bool { 520 return offset+length < offset || offset+length > sliceLength 521 } 522 523 // START CT CHANGES 524 525 // Tests whether the data in |bytes| would be a valid ISO8859-1 string. 526 // Clearly, a sequence of bytes comprised solely of valid ISO8859-1 527 // codepoints does not imply that the encoding MUST be ISO8859-1, rather that 528 // you would not encounter an error trying to interpret the data as such. 529 func couldBeISO8859_1(bytes []byte) bool { 530 for _, b := range bytes { 531 if b < 0x20 || (b >= 0x7F && b < 0xA0) { 532 return false 533 } 534 } 535 return true 536 } 537 538 // Checks whether the data in |bytes| would be a valid T.61 string. 539 // Clearly, a sequence of bytes comprised solely of valid T.61 540 // codepoints does not imply that the encoding MUST be T.61, rather that 541 // you would not encounter an error trying to interpret the data as such. 542 func couldBeT61(bytes []byte) bool { 543 for _, b := range bytes { 544 switch b { 545 case 0x00: 546 // Since we're guessing at (incorrect) encodings for a 547 // PrintableString, we'll err on the side of caution and disallow 548 // strings with a NUL in them, don't want to re-create a PayPal NUL 549 // situation in monitors. 550 fallthrough 551 case 0x23, 0x24, 0x5C, 0x5E, 0x60, 0x7B, 0x7D, 0x7E, 0xA5, 0xA6, 0xAC, 0xAD, 0xAE, 0xAF, 552 0xB9, 0xBA, 0xC0, 0xC9, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 553 0xDA, 0xDB, 0xDC, 0xDE, 0xDF, 0xE5, 0xFF: 554 // These are all invalid code points in T.61, so it can't be a T.61 string. 555 return false 556 } 557 } 558 return true 559 } 560 561 // Converts the data in |bytes| to the equivalent UTF-8 string. 562 func iso8859_1ToUTF8(bytes []byte) string { 563 buf := make([]rune, len(bytes)) 564 for i, b := range bytes { 565 buf[i] = rune(b) 566 } 567 return string(buf) 568 } 569 570 // END CT CHANGES 571 572 // parseField is the main parsing function. Given a byte slice and an offset 573 // into the array, it will try to parse a suitable ASN.1 value out and store it 574 // in the given Value. 575 func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err error) { 576 offset = initOffset 577 fieldType := v.Type() 578 579 // If we have run out of data, it may be that there are optional elements at the end. 580 if offset == len(bytes) { 581 if !setDefaultValue(v, params) { 582 err = SyntaxError{"sequence truncated"} 583 } 584 return 585 } 586 587 // Deal with raw values. 588 if fieldType == rawValueType { 589 var t tagAndLength 590 t, offset, err = parseTagAndLength(bytes, offset) 591 if err != nil { 592 return 593 } 594 if invalidLength(offset, t.length, len(bytes)) { 595 err = SyntaxError{"data truncated"} 596 return 597 } 598 result := RawValue{t.class, t.tag, t.isCompound, bytes[offset : offset+t.length], bytes[initOffset : offset+t.length]} 599 offset += t.length 600 v.Set(reflect.ValueOf(result)) 601 return 602 } 603 604 // Deal with the ANY type. 605 if ifaceType := fieldType; ifaceType.Kind() == reflect.Interface && ifaceType.NumMethod() == 0 { 606 var t tagAndLength 607 t, offset, err = parseTagAndLength(bytes, offset) 608 if err != nil { 609 return 610 } 611 if invalidLength(offset, t.length, len(bytes)) { 612 err = SyntaxError{"data truncated"} 613 return 614 } 615 var result interface{} 616 if !t.isCompound && t.class == classUniversal { 617 innerBytes := bytes[offset : offset+t.length] 618 switch t.tag { 619 case tagPrintableString: 620 result, err = parsePrintableString(innerBytes) 621 // START CT CHANGES 622 if err != nil && strings.Contains(err.Error(), "PrintableString contains invalid character") { 623 // Probably an ISO8859-1 string stuffed in, check if it 624 // would be valid and assume that's what's happened if so, 625 // otherwise try T.61, failing that give up and just assign 626 // the bytes 627 switch { 628 case couldBeISO8859_1(innerBytes): 629 result, err = iso8859_1ToUTF8(innerBytes), nil 630 case couldBeT61(innerBytes): 631 result, err = parseT61String(innerBytes) 632 default: 633 result = nil 634 err = errors.New("PrintableString contains invalid character, but couldn't determine correct String type.") 635 } 636 } 637 // END CT CHANGES 638 case tagIA5String: 639 result, err = parseIA5String(innerBytes) 640 case tagT61String: 641 result, err = parseT61String(innerBytes) 642 case tagUTF8String: 643 result, err = parseUTF8String(innerBytes) 644 case tagInteger: 645 result, err = parseInt64(innerBytes) 646 case tagBitString: 647 result, err = parseBitString(innerBytes) 648 case tagOID: 649 result, err = parseObjectIdentifier(innerBytes) 650 case tagUTCTime: 651 result, err = parseUTCTime(innerBytes) 652 case tagOctetString: 653 result = innerBytes 654 default: 655 // If we don't know how to handle the type, we just leave Value as nil. 656 } 657 } 658 offset += t.length 659 if err != nil { 660 return 661 } 662 if result != nil { 663 v.Set(reflect.ValueOf(result)) 664 } 665 return 666 } 667 universalTag, compoundType, ok1 := getUniversalType(fieldType) 668 if !ok1 { 669 err = StructuralError{fmt.Sprintf("unknown Go type: %v", fieldType)} 670 return 671 } 672 673 t, offset, err := parseTagAndLength(bytes, offset) 674 if err != nil { 675 return 676 } 677 if params.explicit { 678 expectedClass := classContextSpecific 679 if params.application { 680 expectedClass = classApplication 681 } 682 if t.class == expectedClass && t.tag == *params.tag && (t.length == 0 || t.isCompound) { 683 if t.length > 0 { 684 t, offset, err = parseTagAndLength(bytes, offset) 685 if err != nil { 686 return 687 } 688 } else { 689 if fieldType != flagType { 690 err = StructuralError{"zero length explicit tag was not an asn1.Flag"} 691 return 692 } 693 v.SetBool(true) 694 return 695 } 696 } else { 697 // The tags didn't match, it might be an optional element. 698 ok := setDefaultValue(v, params) 699 if ok { 700 offset = initOffset 701 } else { 702 err = StructuralError{"explicitly tagged member didn't match"} 703 } 704 return 705 } 706 } 707 708 // Special case for strings: all the ASN.1 string types map to the Go 709 // type string. getUniversalType returns the tag for PrintableString 710 // when it sees a string, so if we see a different string type on the 711 // wire, we change the universal type to match. 712 if universalTag == tagPrintableString { 713 switch t.tag { 714 case tagIA5String, tagGeneralString, tagT61String, tagUTF8String: 715 universalTag = t.tag 716 } 717 } 718 719 // Special case for time: UTCTime and GeneralizedTime both map to the 720 // Go type time.Time. 721 if universalTag == tagUTCTime && t.tag == tagGeneralizedTime { 722 universalTag = tagGeneralizedTime 723 } 724 725 expectedClass := classUniversal 726 expectedTag := universalTag 727 728 if !params.explicit && params.tag != nil { 729 expectedClass = classContextSpecific 730 expectedTag = *params.tag 731 } 732 733 if !params.explicit && params.application && params.tag != nil { 734 expectedClass = classApplication 735 expectedTag = *params.tag 736 } 737 738 // We have unwrapped any explicit tagging at this point. 739 if t.class != expectedClass || t.tag != expectedTag || t.isCompound != compoundType { 740 // Tags don't match. Again, it could be an optional element. 741 ok := setDefaultValue(v, params) 742 if ok { 743 offset = initOffset 744 } else { 745 err = StructuralError{fmt.Sprintf("tags don't match (%d vs %+v) %+v %s @%d", expectedTag, t, params, fieldType.Name(), offset)} 746 } 747 return 748 } 749 if invalidLength(offset, t.length, len(bytes)) { 750 err = SyntaxError{"data truncated"} 751 return 752 } 753 innerBytes := bytes[offset : offset+t.length] 754 offset += t.length 755 756 // We deal with the structures defined in this package first. 757 switch fieldType { 758 case objectIdentifierType: 759 newSlice, err1 := parseObjectIdentifier(innerBytes) 760 v.Set(reflect.MakeSlice(v.Type(), len(newSlice), len(newSlice))) 761 if err1 == nil { 762 reflect.Copy(v, reflect.ValueOf(newSlice)) 763 } 764 err = err1 765 return 766 case bitStringType: 767 bs, err1 := parseBitString(innerBytes) 768 if err1 == nil { 769 v.Set(reflect.ValueOf(bs)) 770 } 771 err = err1 772 return 773 case timeType: 774 var time time.Time 775 var err1 error 776 if universalTag == tagUTCTime { 777 time, err1 = parseUTCTime(innerBytes) 778 } else { 779 time, err1 = parseGeneralizedTime(innerBytes) 780 } 781 if err1 == nil { 782 v.Set(reflect.ValueOf(time)) 783 } 784 err = err1 785 return 786 case enumeratedType: 787 parsedInt, err1 := parseInt32(innerBytes) 788 if err1 == nil { 789 v.SetInt(int64(parsedInt)) 790 } 791 err = err1 792 return 793 case flagType: 794 v.SetBool(true) 795 return 796 case bigIntType: 797 parsedInt := parseBigInt(innerBytes) 798 v.Set(reflect.ValueOf(parsedInt)) 799 return 800 } 801 switch val := v; val.Kind() { 802 case reflect.Bool: 803 parsedBool, err1 := parseBool(innerBytes) 804 if err1 == nil { 805 val.SetBool(parsedBool) 806 } 807 err = err1 808 return 809 case reflect.Int, reflect.Int32, reflect.Int64: 810 if val.Type().Size() == 4 { 811 parsedInt, err1 := parseInt32(innerBytes) 812 if err1 == nil { 813 val.SetInt(int64(parsedInt)) 814 } 815 err = err1 816 } else { 817 parsedInt, err1 := parseInt64(innerBytes) 818 if err1 == nil { 819 val.SetInt(parsedInt) 820 } 821 err = err1 822 } 823 return 824 // TODO(dfc) Add support for the remaining integer types 825 case reflect.Struct: 826 structType := fieldType 827 828 if structType.NumField() > 0 && 829 structType.Field(0).Type == rawContentsType { 830 bytes := bytes[initOffset:offset] 831 val.Field(0).Set(reflect.ValueOf(RawContent(bytes))) 832 } 833 834 innerOffset := 0 835 for i := 0; i < structType.NumField(); i++ { 836 field := structType.Field(i) 837 if i == 0 && field.Type == rawContentsType { 838 continue 839 } 840 innerOffset, err = parseField(val.Field(i), innerBytes, innerOffset, parseFieldParameters(field.Tag.Get("asn1"))) 841 if err != nil { 842 return 843 } 844 } 845 // We allow extra bytes at the end of the SEQUENCE because 846 // adding elements to the end has been used in X.509 as the 847 // version numbers have increased. 848 return 849 case reflect.Slice: 850 sliceType := fieldType 851 if sliceType.Elem().Kind() == reflect.Uint8 { 852 val.Set(reflect.MakeSlice(sliceType, len(innerBytes), len(innerBytes))) 853 reflect.Copy(val, reflect.ValueOf(innerBytes)) 854 return 855 } 856 newSlice, err1 := parseSequenceOf(innerBytes, sliceType, sliceType.Elem()) 857 if err1 == nil { 858 val.Set(newSlice) 859 } 860 err = err1 861 return 862 case reflect.String: 863 var v string 864 switch universalTag { 865 case tagPrintableString: 866 v, err = parsePrintableString(innerBytes) 867 case tagIA5String: 868 v, err = parseIA5String(innerBytes) 869 case tagT61String: 870 v, err = parseT61String(innerBytes) 871 case tagUTF8String: 872 v, err = parseUTF8String(innerBytes) 873 case tagGeneralString: 874 // GeneralString is specified in ISO-2022/ECMA-35, 875 // A brief review suggests that it includes structures 876 // that allow the encoding to change midstring and 877 // such. We give up and pass it as an 8-bit string. 878 v, err = parseT61String(innerBytes) 879 default: 880 err = SyntaxError{fmt.Sprintf("internal error: unknown string type %d", universalTag)} 881 } 882 if err == nil { 883 val.SetString(v) 884 } 885 return 886 } 887 err = StructuralError{"unsupported: " + v.Type().String()} 888 return 889 } 890 891 // setDefaultValue is used to install a default value, from a tag string, into 892 // a Value. It is successful is the field was optional, even if a default value 893 // wasn't provided or it failed to install it into the Value. 894 func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) { 895 if !params.optional { 896 return 897 } 898 ok = true 899 if params.defaultValue == nil { 900 return 901 } 902 switch val := v; val.Kind() { 903 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 904 val.SetInt(*params.defaultValue) 905 } 906 return 907 } 908 909 // Unmarshal parses the DER-encoded ASN.1 data structure b 910 // and uses the reflect package to fill in an arbitrary value pointed at by val. 911 // Because Unmarshal uses the reflect package, the structs 912 // being written to must use upper case field names. 913 // 914 // An ASN.1 INTEGER can be written to an int, int32, int64, 915 // or *big.Int (from the math/big package). 916 // If the encoded value does not fit in the Go type, 917 // Unmarshal returns a parse error. 918 // 919 // An ASN.1 BIT STRING can be written to a BitString. 920 // 921 // An ASN.1 OCTET STRING can be written to a []byte. 922 // 923 // An ASN.1 OBJECT IDENTIFIER can be written to an 924 // ObjectIdentifier. 925 // 926 // An ASN.1 ENUMERATED can be written to an Enumerated. 927 // 928 // An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time. 929 // 930 // An ASN.1 PrintableString or IA5String can be written to a string. 931 // 932 // Any of the above ASN.1 values can be written to an interface{}. 933 // The value stored in the interface has the corresponding Go type. 934 // For integers, that type is int64. 935 // 936 // An ASN.1 SEQUENCE OF x or SET OF x can be written 937 // to a slice if an x can be written to the slice's element type. 938 // 939 // An ASN.1 SEQUENCE or SET can be written to a struct 940 // if each of the elements in the sequence can be 941 // written to the corresponding element in the struct. 942 // 943 // The following tags on struct fields have special meaning to Unmarshal: 944 // 945 // optional marks the field as ASN.1 OPTIONAL 946 // [explicit] tag:x specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC 947 // default:x sets the default value for optional integer fields 948 // 949 // If the type of the first field of a structure is RawContent then the raw 950 // ASN1 contents of the struct will be stored in it. 951 // 952 // Other ASN.1 types are not supported; if it encounters them, 953 // Unmarshal returns a parse error. 954 func Unmarshal(b []byte, val interface{}) (rest []byte, err error) { 955 return UnmarshalWithParams(b, val, "") 956 } 957 958 // UnmarshalWithParams allows field parameters to be specified for the 959 // top-level element. The form of the params is the same as the field tags. 960 func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) { 961 v := reflect.ValueOf(val).Elem() 962 offset, err := parseField(v, b, 0, parseFieldParameters(params)) 963 if err != nil { 964 return nil, err 965 } 966 return b[offset:], nil 967 }