Elia Battiston | 4750d3c | 2022-07-14 13:24:56 +0000 | [diff] [blame] | 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 | // jtasn1 addition of following case |
| 640 | case TagGeneralString: |
| 641 | result, err = parseIA5String(innerBytes) |
| 642 | case TagT61String: |
| 643 | result, err = parseT61String(innerBytes) |
| 644 | case TagUTF8String: |
| 645 | result, err = parseUTF8String(innerBytes) |
| 646 | case TagInteger: |
| 647 | result, err = parseInt64(innerBytes) |
| 648 | case TagBitString: |
| 649 | result, err = parseBitString(innerBytes) |
| 650 | case TagOID: |
| 651 | result, err = parseObjectIdentifier(innerBytes) |
| 652 | case TagUTCTime: |
| 653 | result, err = parseUTCTime(innerBytes) |
| 654 | case TagGeneralizedTime: |
| 655 | result, err = parseGeneralizedTime(innerBytes) |
| 656 | case TagOctetString: |
| 657 | result = innerBytes |
| 658 | default: |
| 659 | // If we don't know how to handle the type, we just leave Value as nil. |
| 660 | } |
| 661 | } |
| 662 | offset += t.length |
| 663 | if err != nil { |
| 664 | return |
| 665 | } |
| 666 | if result != nil { |
| 667 | v.Set(reflect.ValueOf(result)) |
| 668 | } |
| 669 | return |
| 670 | } |
| 671 | universalTag, compoundType, ok1 := getUniversalType(fieldType) |
| 672 | if !ok1 { |
| 673 | err = StructuralError{fmt.Sprintf("unknown Go type: %v", fieldType)} |
| 674 | return |
| 675 | } |
| 676 | |
| 677 | t, offset, err := parseTagAndLength(bytes, offset) |
| 678 | if err != nil { |
| 679 | return |
| 680 | } |
| 681 | if params.explicit { |
| 682 | expectedClass := ClassContextSpecific |
| 683 | if params.application { |
| 684 | expectedClass = ClassApplication |
| 685 | } |
| 686 | if offset == len(bytes) { |
| 687 | err = StructuralError{"explicit tag has no child"} |
| 688 | return |
| 689 | } |
| 690 | if t.class == expectedClass && t.tag == *params.tag && (t.length == 0 || t.isCompound) { |
| 691 | if t.length > 0 { |
| 692 | t, offset, err = parseTagAndLength(bytes, offset) |
| 693 | if err != nil { |
| 694 | return |
| 695 | } |
| 696 | } else { |
| 697 | if fieldType != flagType { |
| 698 | err = StructuralError{"zero length explicit tag was not an asn1.Flag"} |
| 699 | return |
| 700 | } |
| 701 | v.SetBool(true) |
| 702 | return |
| 703 | } |
| 704 | } else { |
| 705 | // The tags didn't match, it might be an optional element. |
| 706 | ok := setDefaultValue(v, params) |
| 707 | if ok { |
| 708 | offset = initOffset |
| 709 | } else { |
| 710 | err = StructuralError{"explicitly tagged member didn't match"} |
| 711 | } |
| 712 | return |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | // Special case for strings: all the ASN.1 string types map to the Go |
| 717 | // type string. getUniversalType returns the tag for PrintableString |
| 718 | // when it sees a string, so if we see a different string type on the |
| 719 | // wire, we change the universal type to match. |
| 720 | if universalTag == TagPrintableString { |
| 721 | if t.class == ClassUniversal { |
| 722 | switch t.tag { |
| 723 | case TagIA5String, TagGeneralString, TagT61String, TagUTF8String: |
| 724 | universalTag = t.tag |
| 725 | } |
| 726 | } else if params.stringType != 0 { |
| 727 | universalTag = params.stringType |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | // Special case for time: UTCTime and GeneralizedTime both map to the |
| 732 | // Go type time.Time. |
| 733 | if universalTag == TagUTCTime && t.tag == TagGeneralizedTime && t.class == ClassUniversal { |
| 734 | universalTag = TagGeneralizedTime |
| 735 | } |
| 736 | |
| 737 | if params.set { |
| 738 | universalTag = TagSet |
| 739 | } |
| 740 | |
| 741 | expectedClass := ClassUniversal |
| 742 | expectedTag := universalTag |
| 743 | |
| 744 | if !params.explicit && params.tag != nil { |
| 745 | expectedClass = ClassContextSpecific |
| 746 | expectedTag = *params.tag |
| 747 | } |
| 748 | |
| 749 | if !params.explicit && params.application && params.tag != nil { |
| 750 | expectedClass = ClassApplication |
| 751 | expectedTag = *params.tag |
| 752 | } |
| 753 | |
| 754 | // We have unwrapped any explicit tagging at this point. |
| 755 | if t.class != expectedClass || t.tag != expectedTag || t.isCompound != compoundType { |
| 756 | // Tags don't match. Again, it could be an optional element. |
| 757 | ok := setDefaultValue(v, params) |
| 758 | if ok { |
| 759 | offset = initOffset |
| 760 | } else { |
| 761 | err = StructuralError{fmt.Sprintf("tags don't match (%d vs %+v) %+v %s @%d", expectedTag, t, params, fieldType.Name(), offset)} |
| 762 | } |
| 763 | return |
| 764 | } |
| 765 | if invalidLength(offset, t.length, len(bytes)) { |
| 766 | err = SyntaxError{"data truncated"} |
| 767 | return |
| 768 | } |
| 769 | innerBytes := bytes[offset : offset+t.length] |
| 770 | offset += t.length |
| 771 | |
| 772 | // We deal with the structures defined in this package first. |
| 773 | switch fieldType { |
| 774 | case objectIdentifierType: |
| 775 | newSlice, err1 := parseObjectIdentifier(innerBytes) |
| 776 | v.Set(reflect.MakeSlice(v.Type(), len(newSlice), len(newSlice))) |
| 777 | if err1 == nil { |
| 778 | reflect.Copy(v, reflect.ValueOf(newSlice)) |
| 779 | } |
| 780 | err = err1 |
| 781 | return |
| 782 | case bitStringType: |
| 783 | bs, err1 := parseBitString(innerBytes) |
| 784 | if err1 == nil { |
| 785 | v.Set(reflect.ValueOf(bs)) |
| 786 | } |
| 787 | err = err1 |
| 788 | return |
| 789 | case timeType: |
| 790 | var time time.Time |
| 791 | var err1 error |
| 792 | if universalTag == TagUTCTime { |
| 793 | time, err1 = parseUTCTime(innerBytes) |
| 794 | } else { |
| 795 | time, err1 = parseGeneralizedTime(innerBytes) |
| 796 | } |
| 797 | if err1 == nil { |
| 798 | v.Set(reflect.ValueOf(time)) |
| 799 | } |
| 800 | err = err1 |
| 801 | return |
| 802 | case enumeratedType: |
| 803 | parsedInt, err1 := parseInt32(innerBytes) |
| 804 | if err1 == nil { |
| 805 | v.SetInt(int64(parsedInt)) |
| 806 | } |
| 807 | err = err1 |
| 808 | return |
| 809 | case flagType: |
| 810 | v.SetBool(true) |
| 811 | return |
| 812 | case bigIntType: |
| 813 | parsedInt, err1 := parseBigInt(innerBytes) |
| 814 | if err1 == nil { |
| 815 | v.Set(reflect.ValueOf(parsedInt)) |
| 816 | } |
| 817 | err = err1 |
| 818 | return |
| 819 | } |
| 820 | switch val := v; val.Kind() { |
| 821 | case reflect.Bool: |
| 822 | parsedBool, err1 := parseBool(innerBytes) |
| 823 | if err1 == nil { |
| 824 | val.SetBool(parsedBool) |
| 825 | } |
| 826 | err = err1 |
| 827 | return |
| 828 | case reflect.Int, reflect.Int32, reflect.Int64: |
| 829 | if val.Type().Size() == 4 { |
| 830 | parsedInt, err1 := parseInt32(innerBytes) |
| 831 | if err1 == nil { |
| 832 | val.SetInt(int64(parsedInt)) |
| 833 | } |
| 834 | err = err1 |
| 835 | } else { |
| 836 | parsedInt, err1 := parseInt64(innerBytes) |
| 837 | if err1 == nil { |
| 838 | val.SetInt(parsedInt) |
| 839 | } |
| 840 | err = err1 |
| 841 | } |
| 842 | return |
| 843 | // TODO(dfc) Add support for the remaining integer types |
| 844 | case reflect.Struct: |
| 845 | structType := fieldType |
| 846 | |
| 847 | if structType.NumField() > 0 && |
| 848 | structType.Field(0).Type == rawContentsType { |
| 849 | bytes := bytes[initOffset:offset] |
| 850 | val.Field(0).Set(reflect.ValueOf(RawContent(bytes))) |
| 851 | } |
| 852 | |
| 853 | innerOffset := 0 |
| 854 | for i := 0; i < structType.NumField(); i++ { |
| 855 | field := structType.Field(i) |
| 856 | if i == 0 && field.Type == rawContentsType { |
| 857 | continue |
| 858 | } |
| 859 | innerOffset, err = parseField(val.Field(i), innerBytes, innerOffset, parseFieldParameters(field.Tag.Get("asn1"))) |
| 860 | if err != nil { |
| 861 | return |
| 862 | } |
| 863 | } |
| 864 | // We allow extra bytes at the end of the SEQUENCE because |
| 865 | // adding elements to the end has been used in X.509 as the |
| 866 | // version numbers have increased. |
| 867 | return |
| 868 | case reflect.Slice: |
| 869 | sliceType := fieldType |
| 870 | if sliceType.Elem().Kind() == reflect.Uint8 { |
| 871 | val.Set(reflect.MakeSlice(sliceType, len(innerBytes), len(innerBytes))) |
| 872 | reflect.Copy(val, reflect.ValueOf(innerBytes)) |
| 873 | return |
| 874 | } |
| 875 | newSlice, err1 := parseSequenceOf(innerBytes, sliceType, sliceType.Elem()) |
| 876 | if err1 == nil { |
| 877 | val.Set(newSlice) |
| 878 | } |
| 879 | err = err1 |
| 880 | return |
| 881 | case reflect.String: |
| 882 | var v string |
| 883 | switch universalTag { |
| 884 | case TagPrintableString: |
| 885 | v, err = parsePrintableString(innerBytes) |
| 886 | case TagIA5String: |
| 887 | v, err = parseIA5String(innerBytes) |
| 888 | case TagT61String: |
| 889 | v, err = parseT61String(innerBytes) |
| 890 | case TagUTF8String: |
| 891 | v, err = parseUTF8String(innerBytes) |
| 892 | case TagGeneralString: |
| 893 | // GeneralString is specified in ISO-2022/ECMA-35, |
| 894 | // A brief review suggests that it includes structures |
| 895 | // that allow the encoding to change midstring and |
| 896 | // such. We give up and pass it as an 8-bit string. |
| 897 | v, err = parseT61String(innerBytes) |
| 898 | default: |
| 899 | err = SyntaxError{fmt.Sprintf("internal error: unknown string type %d", universalTag)} |
| 900 | } |
| 901 | if err == nil { |
| 902 | val.SetString(v) |
| 903 | } |
| 904 | return |
| 905 | } |
| 906 | err = StructuralError{"unsupported: " + v.Type().String()} |
| 907 | return |
| 908 | } |
| 909 | |
| 910 | // canHaveDefaultValue reports whether k is a Kind that we will set a default |
| 911 | // value for. (A signed integer, essentially.) |
| 912 | func canHaveDefaultValue(k reflect.Kind) bool { |
| 913 | switch k { |
| 914 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 915 | return true |
| 916 | } |
| 917 | |
| 918 | return false |
| 919 | } |
| 920 | |
| 921 | // setDefaultValue is used to install a default value, from a tag string, into |
| 922 | // a Value. It is successful if the field was optional, even if a default value |
| 923 | // wasn't provided or it failed to install it into the Value. |
| 924 | func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) { |
| 925 | if !params.optional { |
| 926 | return |
| 927 | } |
| 928 | ok = true |
| 929 | if params.defaultValue == nil { |
| 930 | return |
| 931 | } |
| 932 | if canHaveDefaultValue(v.Kind()) { |
| 933 | v.SetInt(*params.defaultValue) |
| 934 | } |
| 935 | return |
| 936 | } |
| 937 | |
| 938 | // Unmarshal parses the DER-encoded ASN.1 data structure b |
| 939 | // and uses the reflect package to fill in an arbitrary value pointed at by val. |
| 940 | // Because Unmarshal uses the reflect package, the structs |
| 941 | // being written to must use upper case field names. |
| 942 | // |
| 943 | // An ASN.1 INTEGER can be written to an int, int32, int64, |
| 944 | // or *big.Int (from the math/big package). |
| 945 | // If the encoded value does not fit in the Go type, |
| 946 | // Unmarshal returns a parse error. |
| 947 | // |
| 948 | // An ASN.1 BIT STRING can be written to a BitString. |
| 949 | // |
| 950 | // An ASN.1 OCTET STRING can be written to a []byte. |
| 951 | // |
| 952 | // An ASN.1 OBJECT IDENTIFIER can be written to an |
| 953 | // ObjectIdentifier. |
| 954 | // |
| 955 | // An ASN.1 ENUMERATED can be written to an Enumerated. |
| 956 | // |
| 957 | // An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time. |
| 958 | // |
| 959 | // An ASN.1 PrintableString or IA5String can be written to a string. |
| 960 | // |
| 961 | // Any of the above ASN.1 values can be written to an interface{}. |
| 962 | // The value stored in the interface has the corresponding Go type. |
| 963 | // For integers, that type is int64. |
| 964 | // |
| 965 | // An ASN.1 SEQUENCE OF x or SET OF x can be written |
| 966 | // to a slice if an x can be written to the slice's element type. |
| 967 | // |
| 968 | // An ASN.1 SEQUENCE or SET can be written to a struct |
| 969 | // if each of the elements in the sequence can be |
| 970 | // written to the corresponding element in the struct. |
| 971 | // |
| 972 | // The following tags on struct fields have special meaning to Unmarshal: |
| 973 | // |
| 974 | // application specifies that a APPLICATION tag is used |
| 975 | // default:x sets the default value for optional integer fields |
| 976 | // explicit specifies that an additional, explicit tag wraps the implicit one |
| 977 | // optional marks the field as ASN.1 OPTIONAL |
| 978 | // set causes a SET, rather than a SEQUENCE type to be expected |
| 979 | // tag:x specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC |
| 980 | // |
| 981 | // If the type of the first field of a structure is RawContent then the raw |
| 982 | // ASN1 contents of the struct will be stored in it. |
| 983 | // |
| 984 | // If the type name of a slice element ends with "SET" then it's treated as if |
| 985 | // the "set" tag was set on it. This can be used with nested slices where a |
| 986 | // struct tag cannot be given. |
| 987 | // |
| 988 | // Other ASN.1 types are not supported; if it encounters them, |
| 989 | // Unmarshal returns a parse error. |
| 990 | func Unmarshal(b []byte, val interface{}) (rest []byte, err error) { |
| 991 | return UnmarshalWithParams(b, val, "") |
| 992 | } |
| 993 | |
| 994 | // UnmarshalWithParams allows field parameters to be specified for the |
| 995 | // top-level element. The form of the params is the same as the field tags. |
| 996 | func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) { |
| 997 | v := reflect.ValueOf(val).Elem() |
| 998 | offset, err := parseField(v, b, 0, parseFieldParameters(params)) |
| 999 | if err != nil { |
| 1000 | return nil, err |
| 1001 | } |
| 1002 | return b[offset:], nil |
| 1003 | } |