github.com/tidwall/go@v0.0.0-20170415222209-6694a6888b7d/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 // OBJECT IDENTIFIER 211 212 // An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER. 213 type ObjectIdentifier []int 214 215 // Equal reports whether oi and other represent the same identifier. 216 func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool { 217 if len(oi) != len(other) { 218 return false 219 } 220 for i := 0; i < len(oi); i++ { 221 if oi[i] != other[i] { 222 return false 223 } 224 } 225 226 return true 227 } 228 229 func (oi ObjectIdentifier) String() string { 230 var s string 231 232 for i, v := range oi { 233 if i > 0 { 234 s += "." 235 } 236 s += strconv.Itoa(v) 237 } 238 239 return s 240 } 241 242 // parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and 243 // returns it. An object identifier is a sequence of variable length integers 244 // that are assigned in a hierarchy. 245 func parseObjectIdentifier(bytes []byte) (s []int, err error) { 246 if len(bytes) == 0 { 247 err = SyntaxError{"zero length OBJECT IDENTIFIER"} 248 return 249 } 250 251 // In the worst case, we get two elements from the first byte (which is 252 // encoded differently) and then every varint is a single byte long. 253 s = make([]int, len(bytes)+1) 254 255 // The first varint is 40*value1 + value2: 256 // According to this packing, value1 can take the values 0, 1 and 2 only. 257 // When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2, 258 // then there are no restrictions on value2. 259 v, offset, err := parseBase128Int(bytes, 0) 260 if err != nil { 261 return 262 } 263 if v < 80 { 264 s[0] = v / 40 265 s[1] = v % 40 266 } else { 267 s[0] = 2 268 s[1] = v - 80 269 } 270 271 i := 2 272 for ; offset < len(bytes); i++ { 273 v, offset, err = parseBase128Int(bytes, offset) 274 if err != nil { 275 return 276 } 277 s[i] = v 278 } 279 s = s[0:i] 280 return 281 } 282 283 // ENUMERATED 284 285 // An Enumerated is represented as a plain int. 286 type Enumerated int 287 288 // FLAG 289 290 // A Flag accepts any data and is set to true if present. 291 type Flag bool 292 293 // parseBase128Int parses a base-128 encoded int from the given offset in the 294 // given byte slice. It returns the value and the new offset. 295 func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err error) { 296 offset = initOffset 297 var ret64 int64 298 for shifted := 0; offset < len(bytes); shifted++ { 299 // 5 * 7 bits per byte == 35 bits of data 300 // Thus the representation is either non-minimal or too large for an int32 301 if shifted == 5 { 302 err = StructuralError{"base 128 integer too large"} 303 return 304 } 305 ret64 <<= 7 306 b := bytes[offset] 307 ret64 |= int64(b & 0x7f) 308 offset++ 309 if b&0x80 == 0 { 310 ret = int(ret64) 311 // Ensure that the returned value fits in an int on all platforms 312 if ret64 > math.MaxInt32 { 313 err = StructuralError{"base 128 integer too large"} 314 } 315 return 316 } 317 } 318 err = SyntaxError{"truncated base 128 integer"} 319 return 320 } 321 322 // UTCTime 323 324 func parseUTCTime(bytes []byte) (ret time.Time, err error) { 325 s := string(bytes) 326 327 formatStr := "0601021504Z0700" 328 ret, err = time.Parse(formatStr, s) 329 if err != nil { 330 formatStr = "060102150405Z0700" 331 ret, err = time.Parse(formatStr, s) 332 } 333 if err != nil { 334 return 335 } 336 337 if serialized := ret.Format(formatStr); serialized != s { 338 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) 339 return 340 } 341 342 if ret.Year() >= 2050 { 343 // UTCTime only encodes times prior to 2050. See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1 344 ret = ret.AddDate(-100, 0, 0) 345 } 346 347 return 348 } 349 350 // parseGeneralizedTime parses the GeneralizedTime from the given byte slice 351 // and returns the resulting time. 352 func parseGeneralizedTime(bytes []byte) (ret time.Time, err error) { 353 const formatStr = "20060102150405Z0700" 354 s := string(bytes) 355 356 if ret, err = time.Parse(formatStr, s); err != nil { 357 return 358 } 359 360 if serialized := ret.Format(formatStr); serialized != s { 361 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) 362 } 363 364 return 365 } 366 367 // PrintableString 368 369 // parsePrintableString parses a ASN.1 PrintableString from the given byte 370 // array and returns it. 371 func parsePrintableString(bytes []byte) (ret string, err error) { 372 for _, b := range bytes { 373 if !isPrintable(b) { 374 err = SyntaxError{"PrintableString contains invalid character"} 375 return 376 } 377 } 378 ret = string(bytes) 379 return 380 } 381 382 // isPrintable reports whether the given b is in the ASN.1 PrintableString set. 383 func isPrintable(b byte) bool { 384 return 'a' <= b && b <= 'z' || 385 'A' <= b && b <= 'Z' || 386 '0' <= b && b <= '9' || 387 '\'' <= b && b <= ')' || 388 '+' <= b && b <= '/' || 389 b == ' ' || 390 b == ':' || 391 b == '=' || 392 b == '?' || 393 // This is technically not allowed in a PrintableString. 394 // However, x509 certificates with wildcard strings don't 395 // always use the correct string type so we permit it. 396 b == '*' 397 } 398 399 // IA5String 400 401 // parseIA5String parses a ASN.1 IA5String (ASCII string) from the given 402 // byte slice and returns it. 403 func parseIA5String(bytes []byte) (ret string, err error) { 404 for _, b := range bytes { 405 if b >= utf8.RuneSelf { 406 err = SyntaxError{"IA5String contains invalid character"} 407 return 408 } 409 } 410 ret = string(bytes) 411 return 412 } 413 414 // T61String 415 416 // parseT61String parses a ASN.1 T61String (8-bit clean string) from the given 417 // byte slice and returns it. 418 func parseT61String(bytes []byte) (ret string, err error) { 419 return string(bytes), nil 420 } 421 422 // UTF8String 423 424 // parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte 425 // array and returns it. 426 func parseUTF8String(bytes []byte) (ret string, err error) { 427 if !utf8.Valid(bytes) { 428 return "", errors.New("asn1: invalid UTF-8 string") 429 } 430 return string(bytes), nil 431 } 432 433 // A RawValue represents an undecoded ASN.1 object. 434 type RawValue struct { 435 Class, Tag int 436 IsCompound bool 437 Bytes []byte 438 FullBytes []byte // includes the tag and length 439 } 440 441 // RawContent is used to signal that the undecoded, DER data needs to be 442 // preserved for a struct. To use it, the first field of the struct must have 443 // this type. It's an error for any of the other fields to have this type. 444 type RawContent []byte 445 446 // Tagging 447 448 // parseTagAndLength parses an ASN.1 tag and length pair from the given offset 449 // into a byte slice. It returns the parsed data and the new offset. SET and 450 // SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we 451 // don't distinguish between ordered and unordered objects in this code. 452 func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err error) { 453 offset = initOffset 454 // parseTagAndLength should not be called without at least a single 455 // byte to read. Thus this check is for robustness: 456 if offset >= len(bytes) { 457 err = errors.New("asn1: internal error in parseTagAndLength") 458 return 459 } 460 b := bytes[offset] 461 offset++ 462 ret.class = int(b >> 6) 463 ret.isCompound = b&0x20 == 0x20 464 ret.tag = int(b & 0x1f) 465 466 // If the bottom five bits are set, then the tag number is actually base 128 467 // encoded afterwards 468 if ret.tag == 0x1f { 469 ret.tag, offset, err = parseBase128Int(bytes, offset) 470 if err != nil { 471 return 472 } 473 // Tags should be encoded in minimal form. 474 if ret.tag < 0x1f { 475 err = SyntaxError{"non-minimal tag"} 476 return 477 } 478 } 479 if offset >= len(bytes) { 480 err = SyntaxError{"truncated tag or length"} 481 return 482 } 483 b = bytes[offset] 484 offset++ 485 if b&0x80 == 0 { 486 // The length is encoded in the bottom 7 bits. 487 ret.length = int(b & 0x7f) 488 } else { 489 // Bottom 7 bits give the number of length bytes to follow. 490 numBytes := int(b & 0x7f) 491 if numBytes == 0 { 492 err = SyntaxError{"indefinite length found (not DER)"} 493 return 494 } 495 ret.length = 0 496 for i := 0; i < numBytes; i++ { 497 if offset >= len(bytes) { 498 err = SyntaxError{"truncated tag or length"} 499 return 500 } 501 b = bytes[offset] 502 offset++ 503 if ret.length >= 1<<23 { 504 // We can't shift ret.length up without 505 // overflowing. 506 err = StructuralError{"length too large"} 507 return 508 } 509 ret.length <<= 8 510 ret.length |= int(b) 511 if ret.length == 0 { 512 // DER requires that lengths be minimal. 513 err = StructuralError{"superfluous leading zeros in length"} 514 return 515 } 516 } 517 // Short lengths must be encoded in short form. 518 if ret.length < 0x80 { 519 err = StructuralError{"non-minimal length"} 520 return 521 } 522 } 523 524 return 525 } 526 527 // parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse 528 // a number of ASN.1 values from the given byte slice and returns them as a 529 // slice of Go values of the given type. 530 func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err error) { 531 expectedTag, compoundType, ok := getUniversalType(elemType) 532 if !ok { 533 err = StructuralError{"unknown Go type for slice"} 534 return 535 } 536 537 // First we iterate over the input and count the number of elements, 538 // checking that the types are correct in each case. 539 numElements := 0 540 for offset := 0; offset < len(bytes); { 541 var t tagAndLength 542 t, offset, err = parseTagAndLength(bytes, offset) 543 if err != nil { 544 return 545 } 546 switch t.tag { 547 case TagIA5String, TagGeneralString, TagT61String, TagUTF8String: 548 // We pretend that various other string types are 549 // PRINTABLE STRINGs so that a sequence of them can be 550 // parsed into a []string. 551 t.tag = TagPrintableString 552 case TagGeneralizedTime, TagUTCTime: 553 // Likewise, both time types are treated the same. 554 t.tag = TagUTCTime 555 } 556 557 if t.class != ClassUniversal || t.isCompound != compoundType || t.tag != expectedTag { 558 err = StructuralError{"sequence tag mismatch"} 559 return 560 } 561 if invalidLength(offset, t.length, len(bytes)) { 562 err = SyntaxError{"truncated sequence"} 563 return 564 } 565 offset += t.length 566 numElements++ 567 } 568 ret = reflect.MakeSlice(sliceType, numElements, numElements) 569 params := fieldParameters{} 570 offset := 0 571 for i := 0; i < numElements; i++ { 572 offset, err = parseField(ret.Index(i), bytes, offset, params) 573 if err != nil { 574 return 575 } 576 } 577 return 578 } 579 580 var ( 581 bitStringType = reflect.TypeOf(BitString{}) 582 objectIdentifierType = reflect.TypeOf(ObjectIdentifier{}) 583 enumeratedType = reflect.TypeOf(Enumerated(0)) 584 flagType = reflect.TypeOf(Flag(false)) 585 timeType = reflect.TypeOf(time.Time{}) 586 rawValueType = reflect.TypeOf(RawValue{}) 587 rawContentsType = reflect.TypeOf(RawContent(nil)) 588 bigIntType = reflect.TypeOf(new(big.Int)) 589 ) 590 591 // invalidLength returns true iff offset + length > sliceLength, or if the 592 // addition would overflow. 593 func invalidLength(offset, length, sliceLength int) bool { 594 return offset+length < offset || offset+length > sliceLength 595 } 596 597 // parseField is the main parsing function. Given a byte slice and an offset 598 // into the array, it will try to parse a suitable ASN.1 value out and store it 599 // in the given Value. 600 func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err error) { 601 offset = initOffset 602 fieldType := v.Type() 603 604 // If we have run out of data, it may be that there are optional elements at the end. 605 if offset == len(bytes) { 606 if !setDefaultValue(v, params) { 607 err = SyntaxError{"sequence truncated"} 608 } 609 return 610 } 611 612 // Deal with raw values. 613 if fieldType == rawValueType { 614 var t tagAndLength 615 t, offset, err = parseTagAndLength(bytes, offset) 616 if err != nil { 617 return 618 } 619 if invalidLength(offset, t.length, len(bytes)) { 620 err = SyntaxError{"data truncated"} 621 return 622 } 623 result := RawValue{t.class, t.tag, t.isCompound, bytes[offset : offset+t.length], bytes[initOffset : offset+t.length]} 624 offset += t.length 625 v.Set(reflect.ValueOf(result)) 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 universalTag, compoundType, ok1 := getUniversalType(fieldType) 678 if !ok1 { 679 err = StructuralError{fmt.Sprintf("unknown Go type: %v", fieldType)} 680 return 681 } 682 683 t, offset, err := parseTagAndLength(bytes, offset) 684 if err != nil { 685 return 686 } 687 if params.explicit { 688 expectedClass := ClassContextSpecific 689 if params.application { 690 expectedClass = ClassApplication 691 } 692 if offset == len(bytes) { 693 err = StructuralError{"explicit tag has no child"} 694 return 695 } 696 if t.class == expectedClass && t.tag == *params.tag && (t.length == 0 || t.isCompound) { 697 if t.length > 0 { 698 t, offset, err = parseTagAndLength(bytes, offset) 699 if err != nil { 700 return 701 } 702 } else { 703 if fieldType != flagType { 704 err = StructuralError{"zero length explicit tag was not an asn1.Flag"} 705 return 706 } 707 v.SetBool(true) 708 return 709 } 710 } else { 711 // The tags didn't match, it might be an optional element. 712 ok := setDefaultValue(v, params) 713 if ok { 714 offset = initOffset 715 } else { 716 err = StructuralError{"explicitly tagged member didn't match"} 717 } 718 return 719 } 720 } 721 722 // Special case for strings: all the ASN.1 string types map to the Go 723 // type string. getUniversalType returns the tag for PrintableString 724 // when it sees a string, so if we see a different string type on the 725 // wire, we change the universal type to match. 726 if universalTag == TagPrintableString { 727 if t.class == ClassUniversal { 728 switch t.tag { 729 case TagIA5String, TagGeneralString, TagT61String, TagUTF8String: 730 universalTag = t.tag 731 } 732 } else if params.stringType != 0 { 733 universalTag = params.stringType 734 } 735 } 736 737 // Special case for time: UTCTime and GeneralizedTime both map to the 738 // Go type time.Time. 739 if universalTag == TagUTCTime && t.tag == TagGeneralizedTime && t.class == ClassUniversal { 740 universalTag = TagGeneralizedTime 741 } 742 743 if params.set { 744 universalTag = TagSet 745 } 746 747 expectedClass := ClassUniversal 748 expectedTag := universalTag 749 750 if !params.explicit && params.tag != nil { 751 expectedClass = ClassContextSpecific 752 expectedTag = *params.tag 753 } 754 755 if !params.explicit && params.application && params.tag != nil { 756 expectedClass = ClassApplication 757 expectedTag = *params.tag 758 } 759 760 // We have unwrapped any explicit tagging at this point. 761 if t.class != expectedClass || t.tag != expectedTag || t.isCompound != compoundType { 762 // Tags don't match. Again, it could be an optional element. 763 ok := setDefaultValue(v, params) 764 if ok { 765 offset = initOffset 766 } else { 767 err = StructuralError{fmt.Sprintf("tags don't match (%d vs %+v) %+v %s @%d", expectedTag, t, params, fieldType.Name(), offset)} 768 } 769 return 770 } 771 if invalidLength(offset, t.length, len(bytes)) { 772 err = SyntaxError{"data truncated"} 773 return 774 } 775 innerBytes := bytes[offset : offset+t.length] 776 offset += t.length 777 778 // We deal with the structures defined in this package first. 779 switch fieldType { 780 case objectIdentifierType: 781 newSlice, err1 := parseObjectIdentifier(innerBytes) 782 v.Set(reflect.MakeSlice(v.Type(), len(newSlice), len(newSlice))) 783 if err1 == nil { 784 reflect.Copy(v, reflect.ValueOf(newSlice)) 785 } 786 err = err1 787 return 788 case bitStringType: 789 bs, err1 := parseBitString(innerBytes) 790 if err1 == nil { 791 v.Set(reflect.ValueOf(bs)) 792 } 793 err = err1 794 return 795 case timeType: 796 var time time.Time 797 var err1 error 798 if universalTag == TagUTCTime { 799 time, err1 = parseUTCTime(innerBytes) 800 } else { 801 time, err1 = parseGeneralizedTime(innerBytes) 802 } 803 if err1 == nil { 804 v.Set(reflect.ValueOf(time)) 805 } 806 err = err1 807 return 808 case enumeratedType: 809 parsedInt, err1 := parseInt32(innerBytes) 810 if err1 == nil { 811 v.SetInt(int64(parsedInt)) 812 } 813 err = err1 814 return 815 case flagType: 816 v.SetBool(true) 817 return 818 case bigIntType: 819 parsedInt, err1 := parseBigInt(innerBytes) 820 if err1 == nil { 821 v.Set(reflect.ValueOf(parsedInt)) 822 } 823 err = err1 824 return 825 } 826 switch val := v; val.Kind() { 827 case reflect.Bool: 828 parsedBool, err1 := parseBool(innerBytes) 829 if err1 == nil { 830 val.SetBool(parsedBool) 831 } 832 err = err1 833 return 834 case reflect.Int, reflect.Int32, reflect.Int64: 835 if val.Type().Size() == 4 { 836 parsedInt, err1 := parseInt32(innerBytes) 837 if err1 == nil { 838 val.SetInt(int64(parsedInt)) 839 } 840 err = err1 841 } else { 842 parsedInt, err1 := parseInt64(innerBytes) 843 if err1 == nil { 844 val.SetInt(parsedInt) 845 } 846 err = err1 847 } 848 return 849 // TODO(dfc) Add support for the remaining integer types 850 case reflect.Struct: 851 structType := fieldType 852 853 for i := 0; i < structType.NumField(); i++ { 854 if structType.Field(i).PkgPath != "" { 855 err = StructuralError{"struct contains unexported fields"} 856 return 857 } 858 } 859 860 if structType.NumField() > 0 && 861 structType.Field(0).Type == rawContentsType { 862 bytes := bytes[initOffset:offset] 863 val.Field(0).Set(reflect.ValueOf(RawContent(bytes))) 864 } 865 866 innerOffset := 0 867 for i := 0; i < structType.NumField(); i++ { 868 field := structType.Field(i) 869 if i == 0 && field.Type == rawContentsType { 870 continue 871 } 872 innerOffset, err = parseField(val.Field(i), innerBytes, innerOffset, parseFieldParameters(field.Tag.Get("asn1"))) 873 if err != nil { 874 return 875 } 876 } 877 // We allow extra bytes at the end of the SEQUENCE because 878 // adding elements to the end has been used in X.509 as the 879 // version numbers have increased. 880 return 881 case reflect.Slice: 882 sliceType := fieldType 883 if sliceType.Elem().Kind() == reflect.Uint8 { 884 val.Set(reflect.MakeSlice(sliceType, len(innerBytes), len(innerBytes))) 885 reflect.Copy(val, reflect.ValueOf(innerBytes)) 886 return 887 } 888 newSlice, err1 := parseSequenceOf(innerBytes, sliceType, sliceType.Elem()) 889 if err1 == nil { 890 val.Set(newSlice) 891 } 892 err = err1 893 return 894 case reflect.String: 895 var v string 896 switch universalTag { 897 case TagPrintableString: 898 v, err = parsePrintableString(innerBytes) 899 case TagIA5String: 900 v, err = parseIA5String(innerBytes) 901 case TagT61String: 902 v, err = parseT61String(innerBytes) 903 case TagUTF8String: 904 v, err = parseUTF8String(innerBytes) 905 case TagGeneralString: 906 // GeneralString is specified in ISO-2022/ECMA-35, 907 // A brief review suggests that it includes structures 908 // that allow the encoding to change midstring and 909 // such. We give up and pass it as an 8-bit string. 910 v, err = parseT61String(innerBytes) 911 default: 912 err = SyntaxError{fmt.Sprintf("internal error: unknown string type %d", universalTag)} 913 } 914 if err == nil { 915 val.SetString(v) 916 } 917 return 918 } 919 err = StructuralError{"unsupported: " + v.Type().String()} 920 return 921 } 922 923 // canHaveDefaultValue reports whether k is a Kind that we will set a default 924 // value for. (A signed integer, essentially.) 925 func canHaveDefaultValue(k reflect.Kind) bool { 926 switch k { 927 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 928 return true 929 } 930 931 return false 932 } 933 934 // setDefaultValue is used to install a default value, from a tag string, into 935 // a Value. It is successful if the field was optional, even if a default value 936 // wasn't provided or it failed to install it into the Value. 937 func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) { 938 if !params.optional { 939 return 940 } 941 ok = true 942 if params.defaultValue == nil { 943 return 944 } 945 if canHaveDefaultValue(v.Kind()) { 946 v.SetInt(*params.defaultValue) 947 } 948 return 949 } 950 951 // Unmarshal parses the DER-encoded ASN.1 data structure b 952 // and uses the reflect package to fill in an arbitrary value pointed at by val. 953 // Because Unmarshal uses the reflect package, the structs 954 // being written to must use upper case field names. 955 // 956 // An ASN.1 INTEGER can be written to an int, int32, int64, 957 // or *big.Int (from the math/big package). 958 // If the encoded value does not fit in the Go type, 959 // Unmarshal returns a parse error. 960 // 961 // An ASN.1 BIT STRING can be written to a BitString. 962 // 963 // An ASN.1 OCTET STRING can be written to a []byte. 964 // 965 // An ASN.1 OBJECT IDENTIFIER can be written to an 966 // ObjectIdentifier. 967 // 968 // An ASN.1 ENUMERATED can be written to an Enumerated. 969 // 970 // An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time. 971 // 972 // An ASN.1 PrintableString or IA5String can be written to a string. 973 // 974 // Any of the above ASN.1 values can be written to an interface{}. 975 // The value stored in the interface has the corresponding Go type. 976 // For integers, that type is int64. 977 // 978 // An ASN.1 SEQUENCE OF x or SET OF x can be written 979 // to a slice if an x can be written to the slice's element type. 980 // 981 // An ASN.1 SEQUENCE or SET can be written to a struct 982 // if each of the elements in the sequence can be 983 // written to the corresponding element in the struct. 984 // 985 // The following tags on struct fields have special meaning to Unmarshal: 986 // 987 // application specifies that a APPLICATION tag is used 988 // default:x sets the default value for optional integer fields (only used if optional is also present) 989 // explicit specifies that an additional, explicit tag wraps the implicit one 990 // optional marks the field as ASN.1 OPTIONAL 991 // set causes a SET, rather than a SEQUENCE type to be expected 992 // tag:x specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC 993 // 994 // If the type of the first field of a structure is RawContent then the raw 995 // ASN1 contents of the struct will be stored in it. 996 // 997 // If the type name of a slice element ends with "SET" then it's treated as if 998 // the "set" tag was set on it. This can be used with nested slices where a 999 // struct tag cannot be given. 1000 // 1001 // Other ASN.1 types are not supported; if it encounters them, 1002 // Unmarshal returns a parse error. 1003 func Unmarshal(b []byte, val interface{}) (rest []byte, err error) { 1004 return UnmarshalWithParams(b, val, "") 1005 } 1006 1007 // UnmarshalWithParams allows field parameters to be specified for the 1008 // top-level element. The form of the params is the same as the field tags. 1009 func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) { 1010 v := reflect.ValueOf(val).Elem() 1011 offset, err := parseField(v, b, 0, parseFieldParameters(params)) 1012 if err != nil { 1013 return nil, err 1014 } 1015 return b[offset:], nil 1016 }