parser.go 32 KB

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