Source file src/crypto/x509/parser.go

     1  // Copyright 2021 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  package x509
     5  
     6  import (
     7  	"bytes"
     8  	"crypto/dsa"
     9  	"crypto/ecdsa"
    10  	"crypto/ed25519"
    11  	"crypto/elliptic"
    12  	"crypto/rsa"
    13  	"crypto/x509/pkix"
    14  	"encoding/asn1"
    15  	"errors"
    16  	"fmt"
    17  	"math/big"
    18  	"net"
    19  	"net/url"
    20  	"strconv"
    21  	"strings"
    22  	"time"
    23  	"unicode/utf16"
    24  	"unicode/utf8"
    25  
    26  	"golang.org/x/crypto/cryptobyte"
    27  	cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
    28  )
    29  
    30  // isPrintable reports whether the given b is in the ASN.1 PrintableString set.
    31  // This is a simplified version of encoding/asn1.isPrintable.
    32  func isPrintable(b byte) bool {
    33  	return 'a' <= b && b <= 'z' ||
    34  		'A' <= b && b <= 'Z' ||
    35  		'0' <= b && b <= '9' ||
    36  		'\'' <= b && b <= ')' ||
    37  		'+' <= b && b <= '/' ||
    38  		b == ' ' ||
    39  		b == ':' ||
    40  		b == '=' ||
    41  		b == '?' ||
    42  		// This is technically not allowed in a PrintableString.
    43  		// However, x509 certificates with wildcard strings don't
    44  		// always use the correct string type so we permit it.
    45  		b == '*' ||
    46  		// This is not technically allowed either. However, not
    47  		// only is it relatively common, but there are also a
    48  		// handful of CA certificates that contain it. At least
    49  		// one of which will not expire until 2027.
    50  		b == '&'
    51  }
    52  
    53  // parseASN1String parses the ASN.1 string types T61String, PrintableString,
    54  // UTF8String, BMPString, IA5String, and NumericString. This is mostly copied
    55  // from the respective encoding/asn1.parse... methods, rather than just
    56  // increasing the API surface of that package.
    57  func parseASN1String(tag cryptobyte_asn1.Tag, value []byte) (string, error) {
    58  	switch tag {
    59  	case cryptobyte_asn1.T61String:
    60  		return string(value), nil
    61  	case cryptobyte_asn1.PrintableString:
    62  		for _, b := range value {
    63  			if !isPrintable(b) {
    64  				return "", errors.New("invalid PrintableString")
    65  			}
    66  		}
    67  		return string(value), nil
    68  	case cryptobyte_asn1.UTF8String:
    69  		if !utf8.Valid(value) {
    70  			return "", errors.New("invalid UTF-8 string")
    71  		}
    72  		return string(value), nil
    73  	case cryptobyte_asn1.Tag(asn1.TagBMPString):
    74  		if len(value)%2 != 0 {
    75  			return "", errors.New("invalid BMPString")
    76  		}
    77  
    78  		// Strip terminator if present.
    79  		if l := len(value); l >= 2 && value[l-1] == 0 && value[l-2] == 0 {
    80  			value = value[:l-2]
    81  		}
    82  
    83  		s := make([]uint16, 0, len(value)/2)
    84  		for len(value) > 0 {
    85  			s = append(s, uint16(value[0])<<8+uint16(value[1]))
    86  			value = value[2:]
    87  		}
    88  
    89  		return string(utf16.Decode(s)), nil
    90  	case cryptobyte_asn1.IA5String:
    91  		s := string(value)
    92  		if isIA5String(s) != nil {
    93  			return "", errors.New("invalid IA5String")
    94  		}
    95  		return s, nil
    96  	case cryptobyte_asn1.Tag(asn1.TagNumericString):
    97  		for _, b := range value {
    98  			if !('0' <= b && b <= '9' || b == ' ') {
    99  				return "", errors.New("invalid NumericString")
   100  			}
   101  		}
   102  		return string(value), nil
   103  	}
   104  	return "", fmt.Errorf("unsupported string type: %v", tag)
   105  }
   106  
   107  // parseName parses a DER encoded Name as defined in RFC 5280. We may
   108  // want to export this function in the future for use in crypto/tls.
   109  func parseName(raw cryptobyte.String) (*pkix.RDNSequence, error) {
   110  	if !raw.ReadASN1(&raw, cryptobyte_asn1.SEQUENCE) {
   111  		return nil, errors.New("x509: invalid RDNSequence")
   112  	}
   113  
   114  	var rdnSeq pkix.RDNSequence
   115  	for !raw.Empty() {
   116  		var rdnSet pkix.RelativeDistinguishedNameSET
   117  		var set cryptobyte.String
   118  		if !raw.ReadASN1(&set, cryptobyte_asn1.SET) {
   119  			return nil, errors.New("x509: invalid RDNSequence")
   120  		}
   121  		for !set.Empty() {
   122  			var atav cryptobyte.String
   123  			if !set.ReadASN1(&atav, cryptobyte_asn1.SEQUENCE) {
   124  				return nil, errors.New("x509: invalid RDNSequence: invalid attribute")
   125  			}
   126  			var attr pkix.AttributeTypeAndValue
   127  			if !atav.ReadASN1ObjectIdentifier(&attr.Type) {
   128  				return nil, errors.New("x509: invalid RDNSequence: invalid attribute type")
   129  			}
   130  			var rawValue cryptobyte.String
   131  			var valueTag cryptobyte_asn1.Tag
   132  			if !atav.ReadAnyASN1(&rawValue, &valueTag) {
   133  				return nil, errors.New("x509: invalid RDNSequence: invalid attribute value")
   134  			}
   135  			var err error
   136  			attr.Value, err = parseASN1String(valueTag, rawValue)
   137  			if err != nil {
   138  				return nil, fmt.Errorf("x509: invalid RDNSequence: invalid attribute value: %s", err)
   139  			}
   140  			rdnSet = append(rdnSet, attr)
   141  		}
   142  
   143  		rdnSeq = append(rdnSeq, rdnSet)
   144  	}
   145  
   146  	return &rdnSeq, nil
   147  }
   148  
   149  func parseAI(der cryptobyte.String) (pkix.AlgorithmIdentifier, error) {
   150  	ai := pkix.AlgorithmIdentifier{}
   151  	if !der.ReadASN1ObjectIdentifier(&ai.Algorithm) {
   152  		return ai, errors.New("x509: malformed OID")
   153  	}
   154  	if der.Empty() {
   155  		return ai, nil
   156  	}
   157  	var params cryptobyte.String
   158  	var tag cryptobyte_asn1.Tag
   159  	if !der.ReadAnyASN1Element(&params, &tag) {
   160  		return ai, errors.New("x509: malformed parameters")
   161  	}
   162  	ai.Parameters.Tag = int(tag)
   163  	ai.Parameters.FullBytes = params
   164  	return ai, nil
   165  }
   166  
   167  func parseValidity(der cryptobyte.String) (time.Time, time.Time, error) {
   168  	extract := func() (time.Time, error) {
   169  		var t time.Time
   170  		switch {
   171  		case der.PeekASN1Tag(cryptobyte_asn1.UTCTime):
   172  			// TODO(rolandshoemaker): once #45411 is fixed, the following code
   173  			// should be replaced with a call to der.ReadASN1UTCTime.
   174  			var utc cryptobyte.String
   175  			if !der.ReadASN1(&utc, cryptobyte_asn1.UTCTime) {
   176  				return t, errors.New("x509: malformed UTCTime")
   177  			}
   178  			s := string(utc)
   179  
   180  			formatStr := "0601021504Z0700"
   181  			var err error
   182  			t, err = time.Parse(formatStr, s)
   183  			if err != nil {
   184  				formatStr = "060102150405Z0700"
   185  				t, err = time.Parse(formatStr, s)
   186  			}
   187  			if err != nil {
   188  				return t, err
   189  			}
   190  
   191  			if serialized := t.Format(formatStr); serialized != s {
   192  				return t, errors.New("x509: malformed UTCTime")
   193  			}
   194  
   195  			if t.Year() >= 2050 {
   196  				// UTCTime only encodes times prior to 2050. See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1
   197  				t = t.AddDate(-100, 0, 0)
   198  			}
   199  		case der.PeekASN1Tag(cryptobyte_asn1.GeneralizedTime):
   200  			if !der.ReadASN1GeneralizedTime(&t) {
   201  				return t, errors.New("x509: malformed GeneralizedTime")
   202  			}
   203  		default:
   204  			return t, errors.New("x509: unsupported time format")
   205  		}
   206  		return t, nil
   207  	}
   208  
   209  	notBefore, err := extract()
   210  	if err != nil {
   211  		return time.Time{}, time.Time{}, err
   212  	}
   213  	notAfter, err := extract()
   214  	if err != nil {
   215  		return time.Time{}, time.Time{}, err
   216  	}
   217  
   218  	return notBefore, notAfter, nil
   219  }
   220  
   221  func parseExtension(der cryptobyte.String) (pkix.Extension, error) {
   222  	var ext pkix.Extension
   223  	if !der.ReadASN1ObjectIdentifier(&ext.Id) {
   224  		return ext, errors.New("x509: malformed extension OID field")
   225  	}
   226  	if der.PeekASN1Tag(cryptobyte_asn1.BOOLEAN) {
   227  		if !der.ReadASN1Boolean(&ext.Critical) {
   228  			return ext, errors.New("x509: malformed extension critical field")
   229  		}
   230  	}
   231  	var val cryptobyte.String
   232  	if !der.ReadASN1(&val, cryptobyte_asn1.OCTET_STRING) {
   233  		return ext, errors.New("x509: malformed extension value field")
   234  	}
   235  	ext.Value = val
   236  	return ext, nil
   237  }
   238  
   239  func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (any, error) {
   240  	der := cryptobyte.String(keyData.PublicKey.RightAlign())
   241  	switch algo {
   242  	case RSA:
   243  		// RSA public keys must have a NULL in the parameters.
   244  		// See RFC 3279, Section 2.3.1.
   245  		if !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1.NullBytes) {
   246  			return nil, errors.New("x509: RSA key missing NULL parameters")
   247  		}
   248  
   249  		p := &pkcs1PublicKey{N: new(big.Int)}
   250  		if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
   251  			return nil, errors.New("x509: invalid RSA public key")
   252  		}
   253  		if !der.ReadASN1Integer(p.N) {
   254  			return nil, errors.New("x509: invalid RSA modulus")
   255  		}
   256  		if !der.ReadASN1Integer(&p.E) {
   257  			return nil, errors.New("x509: invalid RSA public exponent")
   258  		}
   259  
   260  		if p.N.Sign() <= 0 {
   261  			return nil, errors.New("x509: RSA modulus is not a positive number")
   262  		}
   263  		if p.E <= 0 {
   264  			return nil, errors.New("x509: RSA public exponent is not a positive number")
   265  		}
   266  
   267  		pub := &rsa.PublicKey{
   268  			E: p.E,
   269  			N: p.N,
   270  		}
   271  		return pub, nil
   272  	case ECDSA:
   273  		paramsDer := cryptobyte.String(keyData.Algorithm.Parameters.FullBytes)
   274  		namedCurveOID := new(asn1.ObjectIdentifier)
   275  		if !paramsDer.ReadASN1ObjectIdentifier(namedCurveOID) {
   276  			return nil, errors.New("x509: invalid ECDSA parameters")
   277  		}
   278  		namedCurve := namedCurveFromOID(*namedCurveOID)
   279  		if namedCurve == nil {
   280  			return nil, errors.New("x509: unsupported elliptic curve")
   281  		}
   282  		x, y := elliptic.Unmarshal(namedCurve, der)
   283  		if x == nil {
   284  			return nil, errors.New("x509: failed to unmarshal elliptic curve point")
   285  		}
   286  		pub := &ecdsa.PublicKey{
   287  			Curve: namedCurve,
   288  			X:     x,
   289  			Y:     y,
   290  		}
   291  		return pub, nil
   292  	case Ed25519:
   293  		// RFC 8410, Section 3
   294  		// > For all of the OIDs, the parameters MUST be absent.
   295  		if len(keyData.Algorithm.Parameters.FullBytes) != 0 {
   296  			return nil, errors.New("x509: Ed25519 key encoded with illegal parameters")
   297  		}
   298  		if len(der) != ed25519.PublicKeySize {
   299  			return nil, errors.New("x509: wrong Ed25519 public key size")
   300  		}
   301  		return ed25519.PublicKey(der), nil
   302  	case DSA:
   303  		y := new(big.Int)
   304  		if !der.ReadASN1Integer(y) {
   305  			return nil, errors.New("x509: invalid DSA public key")
   306  		}
   307  		pub := &dsa.PublicKey{
   308  			Y: y,
   309  			Parameters: dsa.Parameters{
   310  				P: new(big.Int),
   311  				Q: new(big.Int),
   312  				G: new(big.Int),
   313  			},
   314  		}
   315  		paramsDer := cryptobyte.String(keyData.Algorithm.Parameters.FullBytes)
   316  		if !paramsDer.ReadASN1(&paramsDer, cryptobyte_asn1.SEQUENCE) ||
   317  			!paramsDer.ReadASN1Integer(pub.Parameters.P) ||
   318  			!paramsDer.ReadASN1Integer(pub.Parameters.Q) ||
   319  			!paramsDer.ReadASN1Integer(pub.Parameters.G) {
   320  			return nil, errors.New("x509: invalid DSA parameters")
   321  		}
   322  		if pub.Y.Sign() <= 0 || pub.Parameters.P.Sign() <= 0 ||
   323  			pub.Parameters.Q.Sign() <= 0 || pub.Parameters.G.Sign() <= 0 {
   324  			return nil, errors.New("x509: zero or negative DSA parameter")
   325  		}
   326  		return pub, nil
   327  	default:
   328  		return nil, nil
   329  	}
   330  }
   331  
   332  func parseKeyUsageExtension(der cryptobyte.String) (KeyUsage, error) {
   333  	var usageBits asn1.BitString
   334  	if !der.ReadASN1BitString(&usageBits) {
   335  		return 0, errors.New("x509: invalid key usage")
   336  	}
   337  
   338  	var usage int
   339  	for i := 0; i < 9; i++ {
   340  		if usageBits.At(i) != 0 {
   341  			usage |= 1 << uint(i)
   342  		}
   343  	}
   344  	return KeyUsage(usage), nil
   345  }
   346  
   347  func parseBasicConstraintsExtension(der cryptobyte.String) (bool, int, error) {
   348  	var isCA bool
   349  	if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
   350  		return false, 0, errors.New("x509: invalid basic constraints a")
   351  	}
   352  	if der.PeekASN1Tag(cryptobyte_asn1.BOOLEAN) {
   353  		if !der.ReadASN1Boolean(&isCA) {
   354  			return false, 0, errors.New("x509: invalid basic constraints b")
   355  		}
   356  	}
   357  	maxPathLen := -1
   358  	if !der.Empty() && der.PeekASN1Tag(cryptobyte_asn1.INTEGER) {
   359  		if !der.ReadASN1Integer(&maxPathLen) {
   360  			return false, 0, errors.New("x509: invalid basic constraints c")
   361  		}
   362  	}
   363  
   364  	// TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285)
   365  	return isCA, maxPathLen, nil
   366  }
   367  
   368  func forEachSAN(der cryptobyte.String, callback func(tag int, data []byte) error) error {
   369  	if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
   370  		return errors.New("x509: invalid subject alternative names")
   371  	}
   372  	for !der.Empty() {
   373  		var san cryptobyte.String
   374  		var tag cryptobyte_asn1.Tag
   375  		if !der.ReadAnyASN1(&san, &tag) {
   376  			return errors.New("x509: invalid subject alternative name")
   377  		}
   378  		if err := callback(int(tag^0x80), san); err != nil {
   379  			return err
   380  		}
   381  	}
   382  
   383  	return nil
   384  }
   385  
   386  func parseSANExtension(der cryptobyte.String) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error) {
   387  	err = forEachSAN(der, func(tag int, data []byte) error {
   388  		switch tag {
   389  		case nameTypeEmail:
   390  			email := string(data)
   391  			if err := isIA5String(email); err != nil {
   392  				return errors.New("x509: SAN rfc822Name is malformed")
   393  			}
   394  			emailAddresses = append(emailAddresses, email)
   395  		case nameTypeDNS:
   396  			name := string(data)
   397  			if err := isIA5String(name); err != nil {
   398  				return errors.New("x509: SAN dNSName is malformed")
   399  			}
   400  			dnsNames = append(dnsNames, string(name))
   401  		case nameTypeURI:
   402  			uriStr := string(data)
   403  			if err := isIA5String(uriStr); err != nil {
   404  				return errors.New("x509: SAN uniformResourceIdentifier is malformed")
   405  			}
   406  			uri, err := url.Parse(uriStr)
   407  			if err != nil {
   408  				return fmt.Errorf("x509: cannot parse URI %q: %s", uriStr, err)
   409  			}
   410  			if len(uri.Host) > 0 {
   411  				if _, ok := domainToReverseLabels(uri.Host); !ok {
   412  					return fmt.Errorf("x509: cannot parse URI %q: invalid domain", uriStr)
   413  				}
   414  			}
   415  			uris = append(uris, uri)
   416  		case nameTypeIP:
   417  			switch len(data) {
   418  			case net.IPv4len, net.IPv6len:
   419  				ipAddresses = append(ipAddresses, data)
   420  			default:
   421  				return errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data)))
   422  			}
   423  		}
   424  
   425  		return nil
   426  	})
   427  
   428  	return
   429  }
   430  
   431  func parseExtKeyUsageExtension(der cryptobyte.String) ([]ExtKeyUsage, []asn1.ObjectIdentifier, error) {
   432  	var extKeyUsages []ExtKeyUsage
   433  	var unknownUsages []asn1.ObjectIdentifier
   434  	if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
   435  		return nil, nil, errors.New("x509: invalid extended key usages")
   436  	}
   437  	for !der.Empty() {
   438  		var eku asn1.ObjectIdentifier
   439  		if !der.ReadASN1ObjectIdentifier(&eku) {
   440  			return nil, nil, errors.New("x509: invalid extended key usages")
   441  		}
   442  		if extKeyUsage, ok := extKeyUsageFromOID(eku); ok {
   443  			extKeyUsages = append(extKeyUsages, extKeyUsage)
   444  		} else {
   445  			unknownUsages = append(unknownUsages, eku)
   446  		}
   447  	}
   448  	return extKeyUsages, unknownUsages, nil
   449  }
   450  
   451  func parseCertificatePoliciesExtension(der cryptobyte.String) ([]asn1.ObjectIdentifier, error) {
   452  	var oids []asn1.ObjectIdentifier
   453  	if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
   454  		return nil, errors.New("x509: invalid certificate policies")
   455  	}
   456  	for !der.Empty() {
   457  		var cp cryptobyte.String
   458  		if !der.ReadASN1(&cp, cryptobyte_asn1.SEQUENCE) {
   459  			return nil, errors.New("x509: invalid certificate policies")
   460  		}
   461  		var oid asn1.ObjectIdentifier
   462  		if !cp.ReadASN1ObjectIdentifier(&oid) {
   463  			return nil, errors.New("x509: invalid certificate policies")
   464  		}
   465  		oids = append(oids, oid)
   466  	}
   467  
   468  	return oids, nil
   469  }
   470  
   471  // isValidIPMask reports whether mask consists of zero or more 1 bits, followed by zero bits.
   472  func isValidIPMask(mask []byte) bool {
   473  	seenZero := false
   474  
   475  	for _, b := range mask {
   476  		if seenZero {
   477  			if b != 0 {
   478  				return false
   479  			}
   480  
   481  			continue
   482  		}
   483  
   484  		switch b {
   485  		case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe:
   486  			seenZero = true
   487  		case 0xff:
   488  		default:
   489  			return false
   490  		}
   491  	}
   492  
   493  	return true
   494  }
   495  
   496  func parseNameConstraintsExtension(out *Certificate, e pkix.Extension) (unhandled bool, err error) {
   497  	// RFC 5280, 4.2.1.10
   498  
   499  	// NameConstraints ::= SEQUENCE {
   500  	//      permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
   501  	//      excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
   502  	//
   503  	// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
   504  	//
   505  	// GeneralSubtree ::= SEQUENCE {
   506  	//      base                    GeneralName,
   507  	//      minimum         [0]     BaseDistance DEFAULT 0,
   508  	//      maximum         [1]     BaseDistance OPTIONAL }
   509  	//
   510  	// BaseDistance ::= INTEGER (0..MAX)
   511  
   512  	outer := cryptobyte.String(e.Value)
   513  	var toplevel, permitted, excluded cryptobyte.String
   514  	var havePermitted, haveExcluded bool
   515  	if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) ||
   516  		!outer.Empty() ||
   517  		!toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) ||
   518  		!toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) ||
   519  		!toplevel.Empty() {
   520  		return false, errors.New("x509: invalid NameConstraints extension")
   521  	}
   522  
   523  	if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 {
   524  		// From RFC 5280, Section 4.2.1.10:
   525  		//   “either the permittedSubtrees field
   526  		//   or the excludedSubtrees MUST be
   527  		//   present”
   528  		return false, errors.New("x509: empty name constraints extension")
   529  	}
   530  
   531  	getValues := func(subtrees cryptobyte.String) (dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) {
   532  		for !subtrees.Empty() {
   533  			var seq, value cryptobyte.String
   534  			var tag cryptobyte_asn1.Tag
   535  			if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) ||
   536  				!seq.ReadAnyASN1(&value, &tag) {
   537  				return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension")
   538  			}
   539  
   540  			var (
   541  				dnsTag   = cryptobyte_asn1.Tag(2).ContextSpecific()
   542  				emailTag = cryptobyte_asn1.Tag(1).ContextSpecific()
   543  				ipTag    = cryptobyte_asn1.Tag(7).ContextSpecific()
   544  				uriTag   = cryptobyte_asn1.Tag(6).ContextSpecific()
   545  			)
   546  
   547  			switch tag {
   548  			case dnsTag:
   549  				domain := string(value)
   550  				if err := isIA5String(domain); err != nil {
   551  					return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
   552  				}
   553  
   554  				trimmedDomain := domain
   555  				if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
   556  					// constraints can have a leading
   557  					// period to exclude the domain
   558  					// itself, but that's not valid in a
   559  					// normal domain name.
   560  					trimmedDomain = trimmedDomain[1:]
   561  				}
   562  				if _, ok := domainToReverseLabels(trimmedDomain); !ok {
   563  					return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse dnsName constraint %q", domain)
   564  				}
   565  				dnsNames = append(dnsNames, domain)
   566  
   567  			case ipTag:
   568  				l := len(value)
   569  				var ip, mask []byte
   570  
   571  				switch l {
   572  				case 8:
   573  					ip = value[:4]
   574  					mask = value[4:]
   575  
   576  				case 32:
   577  					ip = value[:16]
   578  					mask = value[16:]
   579  
   580  				default:
   581  					return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l)
   582  				}
   583  
   584  				if !isValidIPMask(mask) {
   585  					return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask)
   586  				}
   587  
   588  				ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)})
   589  
   590  			case emailTag:
   591  				constraint := string(value)
   592  				if err := isIA5String(constraint); err != nil {
   593  					return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
   594  				}
   595  
   596  				// If the constraint contains an @ then
   597  				// it specifies an exact mailbox name.
   598  				if strings.Contains(constraint, "@") {
   599  					if _, ok := parseRFC2821Mailbox(constraint); !ok {
   600  						return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
   601  					}
   602  				} else {
   603  					// Otherwise it's a domain name.
   604  					domain := constraint
   605  					if len(domain) > 0 && domain[0] == '.' {
   606  						domain = domain[1:]
   607  					}
   608  					if _, ok := domainToReverseLabels(domain); !ok {
   609  						return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
   610  					}
   611  				}
   612  				emails = append(emails, constraint)
   613  
   614  			case uriTag:
   615  				domain := string(value)
   616  				if err := isIA5String(domain); err != nil {
   617  					return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
   618  				}
   619  
   620  				if net.ParseIP(domain) != nil {
   621  					return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain)
   622  				}
   623  
   624  				trimmedDomain := domain
   625  				if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
   626  					// constraints can have a leading
   627  					// period to exclude the domain itself,
   628  					// but that's not valid in a normal
   629  					// domain name.
   630  					trimmedDomain = trimmedDomain[1:]
   631  				}
   632  				if _, ok := domainToReverseLabels(trimmedDomain); !ok {
   633  					return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q", domain)
   634  				}
   635  				uriDomains = append(uriDomains, domain)
   636  
   637  			default:
   638  				unhandled = true
   639  			}
   640  		}
   641  
   642  		return dnsNames, ips, emails, uriDomains, nil
   643  	}
   644  
   645  	if out.PermittedDNSDomains, out.PermittedIPRanges, out.PermittedEmailAddresses, out.PermittedURIDomains, err = getValues(permitted); err != nil {
   646  		return false, err
   647  	}
   648  	if out.ExcludedDNSDomains, out.ExcludedIPRanges, out.ExcludedEmailAddresses, out.ExcludedURIDomains, err = getValues(excluded); err != nil {
   649  		return false, err
   650  	}
   651  	out.PermittedDNSDomainsCritical = e.Critical
   652  
   653  	return unhandled, nil
   654  }
   655  
   656  func processExtensions(out *Certificate) error {
   657  	var err error
   658  	for _, e := range out.Extensions {
   659  		unhandled := false
   660  
   661  		if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
   662  			switch e.Id[3] {
   663  			case 15:
   664  				out.KeyUsage, err = parseKeyUsageExtension(e.Value)
   665  				if err != nil {
   666  					return err
   667  				}
   668  			case 19:
   669  				out.IsCA, out.MaxPathLen, err = parseBasicConstraintsExtension(e.Value)
   670  				if err != nil {
   671  					return err
   672  				}
   673  				out.BasicConstraintsValid = true
   674  				out.MaxPathLenZero = out.MaxPathLen == 0
   675  			case 17:
   676  				out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(e.Value)
   677  				if err != nil {
   678  					return err
   679  				}
   680  
   681  				if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 && len(out.URIs) == 0 {
   682  					// If we didn't parse anything then we do the critical check, below.
   683  					unhandled = true
   684  				}
   685  
   686  			case 30:
   687  				unhandled, err = parseNameConstraintsExtension(out, e)
   688  				if err != nil {
   689  					return err
   690  				}
   691  
   692  			case 31:
   693  				// RFC 5280, 4.2.1.13
   694  
   695  				// CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
   696  				//
   697  				// DistributionPoint ::= SEQUENCE {
   698  				//     distributionPoint       [0]     DistributionPointName OPTIONAL,
   699  				//     reasons                 [1]     ReasonFlags OPTIONAL,
   700  				//     cRLIssuer               [2]     GeneralNames OPTIONAL }
   701  				//
   702  				// DistributionPointName ::= CHOICE {
   703  				//     fullName                [0]     GeneralNames,
   704  				//     nameRelativeToCRLIssuer [1]     RelativeDistinguishedName }
   705  				val := cryptobyte.String(e.Value)
   706  				if !val.ReadASN1(&val, cryptobyte_asn1.SEQUENCE) {
   707  					return errors.New("x509: invalid CRL distribution points")
   708  				}
   709  				for !val.Empty() {
   710  					var dpDER cryptobyte.String
   711  					if !val.ReadASN1(&dpDER, cryptobyte_asn1.SEQUENCE) {
   712  						return errors.New("x509: invalid CRL distribution point")
   713  					}
   714  					var dpNameDER cryptobyte.String
   715  					var dpNamePresent bool
   716  					if !dpDER.ReadOptionalASN1(&dpNameDER, &dpNamePresent, cryptobyte_asn1.Tag(0).Constructed().ContextSpecific()) {
   717  						return errors.New("x509: invalid CRL distribution point")
   718  					}
   719  					if !dpNamePresent {
   720  						continue
   721  					}
   722  					if !dpNameDER.ReadASN1(&dpNameDER, cryptobyte_asn1.Tag(0).Constructed().ContextSpecific()) {
   723  						return errors.New("x509: invalid CRL distribution point")
   724  					}
   725  					for !dpNameDER.Empty() {
   726  						if !dpNameDER.PeekASN1Tag(cryptobyte_asn1.Tag(6).ContextSpecific()) {
   727  							break
   728  						}
   729  						var uri cryptobyte.String
   730  						if !dpNameDER.ReadASN1(&uri, cryptobyte_asn1.Tag(6).ContextSpecific()) {
   731  							return errors.New("x509: invalid CRL distribution point")
   732  						}
   733  						out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(uri))
   734  					}
   735  				}
   736  
   737  			case 35:
   738  				// RFC 5280, 4.2.1.1
   739  				val := cryptobyte.String(e.Value)
   740  				var akid cryptobyte.String
   741  				if !val.ReadASN1(&akid, cryptobyte_asn1.SEQUENCE) {
   742  					return errors.New("x509: invalid authority key identifier")
   743  				}
   744  				if akid.PeekASN1Tag(cryptobyte_asn1.Tag(0).ContextSpecific()) {
   745  					if !akid.ReadASN1(&akid, cryptobyte_asn1.Tag(0).ContextSpecific()) {
   746  						return errors.New("x509: invalid authority key identifier")
   747  					}
   748  					out.AuthorityKeyId = akid
   749  				}
   750  			case 37:
   751  				out.ExtKeyUsage, out.UnknownExtKeyUsage, err = parseExtKeyUsageExtension(e.Value)
   752  				if err != nil {
   753  					return err
   754  				}
   755  			case 14:
   756  				// RFC 5280, 4.2.1.2
   757  				val := cryptobyte.String(e.Value)
   758  				var skid cryptobyte.String
   759  				if !val.ReadASN1(&skid, cryptobyte_asn1.OCTET_STRING) {
   760  					return errors.New("x509: invalid subject key identifier")
   761  				}
   762  				out.SubjectKeyId = skid
   763  			case 32:
   764  				out.PolicyIdentifiers, err = parseCertificatePoliciesExtension(e.Value)
   765  				if err != nil {
   766  					return err
   767  				}
   768  			default:
   769  				// Unknown extensions are recorded if critical.
   770  				unhandled = true
   771  			}
   772  		} else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
   773  			// RFC 5280 4.2.2.1: Authority Information Access
   774  			val := cryptobyte.String(e.Value)
   775  			if !val.ReadASN1(&val, cryptobyte_asn1.SEQUENCE) {
   776  				return errors.New("x509: invalid authority info access")
   777  			}
   778  			for !val.Empty() {
   779  				var aiaDER cryptobyte.String
   780  				if !val.ReadASN1(&aiaDER, cryptobyte_asn1.SEQUENCE) {
   781  					return errors.New("x509: invalid authority info access")
   782  				}
   783  				var method asn1.ObjectIdentifier
   784  				if !aiaDER.ReadASN1ObjectIdentifier(&method) {
   785  					return errors.New("x509: invalid authority info access")
   786  				}
   787  				if !aiaDER.PeekASN1Tag(cryptobyte_asn1.Tag(6).ContextSpecific()) {
   788  					continue
   789  				}
   790  				if !aiaDER.ReadASN1(&aiaDER, cryptobyte_asn1.Tag(6).ContextSpecific()) {
   791  					return errors.New("x509: invalid authority info access")
   792  				}
   793  				switch {
   794  				case method.Equal(oidAuthorityInfoAccessOcsp):
   795  					out.OCSPServer = append(out.OCSPServer, string(aiaDER))
   796  				case method.Equal(oidAuthorityInfoAccessIssuers):
   797  					out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(aiaDER))
   798  				}
   799  			}
   800  		} else {
   801  			// Unknown extensions are recorded if critical.
   802  			unhandled = true
   803  		}
   804  
   805  		if e.Critical && unhandled {
   806  			out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
   807  		}
   808  	}
   809  
   810  	return nil
   811  }
   812  
   813  func parseCertificate(der []byte) (*Certificate, error) {
   814  	cert := &Certificate{}
   815  
   816  	input := cryptobyte.String(der)
   817  	// we read the SEQUENCE including length and tag bytes so that
   818  	// we can populate Certificate.Raw, before unwrapping the
   819  	// SEQUENCE so it can be operated on
   820  	if !input.ReadASN1Element(&input, cryptobyte_asn1.SEQUENCE) {
   821  		return nil, errors.New("x509: malformed certificate")
   822  	}
   823  	cert.Raw = input
   824  	if !input.ReadASN1(&input, cryptobyte_asn1.SEQUENCE) {
   825  		return nil, errors.New("x509: malformed certificate")
   826  	}
   827  
   828  	var tbs cryptobyte.String
   829  	// do the same trick again as above to extract the raw
   830  	// bytes for Certificate.RawTBSCertificate
   831  	if !input.ReadASN1Element(&tbs, cryptobyte_asn1.SEQUENCE) {
   832  		return nil, errors.New("x509: malformed tbs certificate")
   833  	}
   834  	cert.RawTBSCertificate = tbs
   835  	if !tbs.ReadASN1(&tbs, cryptobyte_asn1.SEQUENCE) {
   836  		return nil, errors.New("x509: malformed tbs certificate")
   837  	}
   838  
   839  	if !tbs.ReadOptionalASN1Integer(&cert.Version, cryptobyte_asn1.Tag(0).Constructed().ContextSpecific(), 0) {
   840  		return nil, errors.New("x509: malformed version")
   841  	}
   842  	if cert.Version < 0 {
   843  		return nil, errors.New("x509: malformed version")
   844  	}
   845  	// for backwards compat reasons Version is one-indexed,
   846  	// rather than zero-indexed as defined in 5280
   847  	cert.Version++
   848  	if cert.Version > 3 {
   849  		return nil, errors.New("x509: invalid version")
   850  	}
   851  
   852  	serial := new(big.Int)
   853  	if !tbs.ReadASN1Integer(serial) {
   854  		return nil, errors.New("x509: malformed serial number")
   855  	}
   856  	// we ignore the presence of negative serial numbers because
   857  	// of their prevalence, despite them being invalid
   858  	// TODO(rolandshoemaker): revist this decision, there are currently
   859  	// only 10 trusted certificates with negative serial numbers
   860  	// according to censys.io.
   861  	cert.SerialNumber = serial
   862  
   863  	var sigAISeq cryptobyte.String
   864  	if !tbs.ReadASN1(&sigAISeq, cryptobyte_asn1.SEQUENCE) {
   865  		return nil, errors.New("x509: malformed signature algorithm identifier")
   866  	}
   867  	// Before parsing the inner algorithm identifier, extract
   868  	// the outer algorithm identifier and make sure that they
   869  	// match.
   870  	var outerSigAISeq cryptobyte.String
   871  	if !input.ReadASN1(&outerSigAISeq, cryptobyte_asn1.SEQUENCE) {
   872  		return nil, errors.New("x509: malformed algorithm identifier")
   873  	}
   874  	if !bytes.Equal(outerSigAISeq, sigAISeq) {
   875  		return nil, errors.New("x509: inner and outer signature algorithm identifiers don't match")
   876  	}
   877  	sigAI, err := parseAI(sigAISeq)
   878  	if err != nil {
   879  		return nil, err
   880  	}
   881  	cert.SignatureAlgorithm = getSignatureAlgorithmFromAI(sigAI)
   882  
   883  	var issuerSeq cryptobyte.String
   884  	if !tbs.ReadASN1Element(&issuerSeq, cryptobyte_asn1.SEQUENCE) {
   885  		return nil, errors.New("x509: malformed issuer")
   886  	}
   887  	cert.RawIssuer = issuerSeq
   888  	issuerRDNs, err := parseName(issuerSeq)
   889  	if err != nil {
   890  		return nil, err
   891  	}
   892  	cert.Issuer.FillFromRDNSequence(issuerRDNs)
   893  
   894  	var validity cryptobyte.String
   895  	if !tbs.ReadASN1(&validity, cryptobyte_asn1.SEQUENCE) {
   896  		return nil, errors.New("x509: malformed validity")
   897  	}
   898  	cert.NotBefore, cert.NotAfter, err = parseValidity(validity)
   899  	if err != nil {
   900  		return nil, err
   901  	}
   902  
   903  	var subjectSeq cryptobyte.String
   904  	if !tbs.ReadASN1Element(&subjectSeq, cryptobyte_asn1.SEQUENCE) {
   905  		return nil, errors.New("x509: malformed issuer")
   906  	}
   907  	cert.RawSubject = subjectSeq
   908  	subjectRDNs, err := parseName(subjectSeq)
   909  	if err != nil {
   910  		return nil, err
   911  	}
   912  	cert.Subject.FillFromRDNSequence(subjectRDNs)
   913  
   914  	var spki cryptobyte.String
   915  	if !tbs.ReadASN1Element(&spki, cryptobyte_asn1.SEQUENCE) {
   916  		return nil, errors.New("x509: malformed spki")
   917  	}
   918  	cert.RawSubjectPublicKeyInfo = spki
   919  	if !spki.ReadASN1(&spki, cryptobyte_asn1.SEQUENCE) {
   920  		return nil, errors.New("x509: malformed spki")
   921  	}
   922  	var pkAISeq cryptobyte.String
   923  	if !spki.ReadASN1(&pkAISeq, cryptobyte_asn1.SEQUENCE) {
   924  		return nil, errors.New("x509: malformed public key algorithm identifier")
   925  	}
   926  	pkAI, err := parseAI(pkAISeq)
   927  	if err != nil {
   928  		return nil, err
   929  	}
   930  	cert.PublicKeyAlgorithm = getPublicKeyAlgorithmFromOID(pkAI.Algorithm)
   931  	var spk asn1.BitString
   932  	if !spki.ReadASN1BitString(&spk) {
   933  		return nil, errors.New("x509: malformed subjectPublicKey")
   934  	}
   935  	cert.PublicKey, err = parsePublicKey(cert.PublicKeyAlgorithm, &publicKeyInfo{
   936  		Algorithm: pkAI,
   937  		PublicKey: spk,
   938  	})
   939  	if err != nil {
   940  		return nil, err
   941  	}
   942  
   943  	if cert.Version > 1 {
   944  		if !tbs.SkipOptionalASN1(cryptobyte_asn1.Tag(1).ContextSpecific()) {
   945  			return nil, errors.New("x509: malformed issuerUniqueID")
   946  		}
   947  		if !tbs.SkipOptionalASN1(cryptobyte_asn1.Tag(2).ContextSpecific()) {
   948  			return nil, errors.New("x509: malformed subjectUniqueID")
   949  		}
   950  		if cert.Version == 3 {
   951  			var extensions cryptobyte.String
   952  			var present bool
   953  			if !tbs.ReadOptionalASN1(&extensions, &present, cryptobyte_asn1.Tag(3).Constructed().ContextSpecific()) {
   954  				return nil, errors.New("x509: malformed extensions")
   955  			}
   956  			if present {
   957  				if !extensions.ReadASN1(&extensions, cryptobyte_asn1.SEQUENCE) {
   958  					return nil, errors.New("x509: malformed extensions")
   959  				}
   960  				for !extensions.Empty() {
   961  					var extension cryptobyte.String
   962  					if !extensions.ReadASN1(&extension, cryptobyte_asn1.SEQUENCE) {
   963  						return nil, errors.New("x509: malformed extension")
   964  					}
   965  					ext, err := parseExtension(extension)
   966  					if err != nil {
   967  						return nil, err
   968  					}
   969  					cert.Extensions = append(cert.Extensions, ext)
   970  				}
   971  				err = processExtensions(cert)
   972  				if err != nil {
   973  					return nil, err
   974  				}
   975  			}
   976  		}
   977  	}
   978  
   979  	var signature asn1.BitString
   980  	if !input.ReadASN1BitString(&signature) {
   981  		return nil, errors.New("x509: malformed signature")
   982  	}
   983  	cert.Signature = signature.RightAlign()
   984  
   985  	return cert, nil
   986  }
   987  
   988  // ParseCertificate parses a single certificate from the given ASN.1 DER data.
   989  func ParseCertificate(der []byte) (*Certificate, error) {
   990  	cert, err := parseCertificate(der)
   991  	if err != nil {
   992  		return nil, err
   993  	}
   994  	if len(der) != len(cert.Raw) {
   995  		return nil, errors.New("x509: trailing data")
   996  	}
   997  	return cert, err
   998  }
   999  
  1000  // ParseCertificates parses one or more certificates from the given ASN.1 DER
  1001  // data. The certificates must be concatenated with no intermediate padding.
  1002  func ParseCertificates(der []byte) ([]*Certificate, error) {
  1003  	var certs []*Certificate
  1004  	for len(der) > 0 {
  1005  		cert, err := parseCertificate(der)
  1006  		if err != nil {
  1007  			return nil, err
  1008  		}
  1009  		certs = append(certs, cert)
  1010  		der = der[len(cert.Raw):]
  1011  	}
  1012  	return certs, nil
  1013  }
  1014  

View as plain text