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