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