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