extensions.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. package x509util
  2. import (
  3. "crypto/x509"
  4. "crypto/x509/pkix"
  5. "encoding/asn1"
  6. "encoding/json"
  7. "fmt"
  8. "math/big"
  9. "net"
  10. "net/url"
  11. "strings"
  12. "github.com/pkg/errors"
  13. )
  14. func convertName(s string) string {
  15. return strings.ReplaceAll(strings.ToLower(s), "_", "")
  16. }
  17. // Names used for key usages.
  18. var (
  19. KeyUsageDigitalSignature = convertName("DigitalSignature")
  20. KeyUsageContentCommitment = convertName("ContentCommitment")
  21. KeyUsageKeyEncipherment = convertName("KeyEncipherment")
  22. KeyUsageDataEncipherment = convertName("DataEncipherment")
  23. KeyUsageKeyAgreement = convertName("KeyAgreement")
  24. KeyUsageCertSign = convertName("CertSign")
  25. KeyUsageCRLSign = convertName("CRLSign")
  26. KeyUsageEncipherOnly = convertName("EncipherOnly")
  27. KeyUsageDecipherOnly = convertName("DecipherOnly")
  28. )
  29. // Names used for extended key usages.
  30. var (
  31. ExtKeyUsageAny = convertName("Any")
  32. ExtKeyUsageServerAuth = convertName("ServerAuth")
  33. ExtKeyUsageClientAuth = convertName("ClientAuth")
  34. ExtKeyUsageCodeSigning = convertName("CodeSigning")
  35. ExtKeyUsageEmailProtection = convertName("EmailProtection")
  36. ExtKeyUsageIPSECEndSystem = convertName("IPSECEndSystem")
  37. ExtKeyUsageIPSECTunnel = convertName("IPSECTunnel")
  38. ExtKeyUsageIPSECUser = convertName("IPSECUser")
  39. ExtKeyUsageTimeStamping = convertName("TimeStamping")
  40. ExtKeyUsageOCSPSigning = convertName("OCSPSigning")
  41. ExtKeyUsageMicrosoftServerGatedCrypto = convertName("MicrosoftServerGatedCrypto")
  42. ExtKeyUsageNetscapeServerGatedCrypto = convertName("NetscapeServerGatedCrypto")
  43. ExtKeyUsageMicrosoftCommercialCodeSigning = convertName("MicrosoftCommercialCodeSigning")
  44. ExtKeyUsageMicrosoftKernelCodeSigning = convertName("MicrosoftKernelCodeSigning")
  45. )
  46. // Names used and SubjectAlternativeNames types.
  47. const (
  48. AutoType = "auto"
  49. DNSType = "dns"
  50. EmailType = "email"
  51. IPType = "ip"
  52. URIType = "uri"
  53. )
  54. // Extension is the JSON representation of a raw X.509 extensions.
  55. type Extension struct {
  56. ID ObjectIdentifier `json:"id"`
  57. Critical bool `json:"critical"`
  58. Value []byte `json:"value"`
  59. }
  60. // newExtensions creates an Extension from a standard pkix.Extension.
  61. func newExtension(e pkix.Extension) Extension {
  62. return Extension{
  63. ID: ObjectIdentifier(e.Id),
  64. Critical: e.Critical,
  65. Value: e.Value,
  66. }
  67. }
  68. // newExtensions creates a slice of Extension from a slice of pkix.Exntesion.
  69. func newExtensions(extensions []pkix.Extension) []Extension {
  70. if extensions == nil {
  71. return nil
  72. }
  73. ret := make([]Extension, len(extensions))
  74. for i, e := range extensions {
  75. ret[i] = newExtension(e)
  76. }
  77. return ret
  78. }
  79. // Set adds the extension to the given X509 certificate.
  80. func (e Extension) Set(c *x509.Certificate) {
  81. c.ExtraExtensions = append(c.ExtraExtensions, pkix.Extension{
  82. Id: asn1.ObjectIdentifier(e.ID),
  83. Critical: e.Critical,
  84. Value: e.Value,
  85. })
  86. }
  87. // ObjectIdentifier represents a JSON strings that unmarshals into an ASN1
  88. // object identifier or OID.
  89. type ObjectIdentifier asn1.ObjectIdentifier
  90. // MarshalJSON implements the json.Marshaler interface and returns the string
  91. // version of the asn1.ObjectIdentifier.
  92. func (o ObjectIdentifier) MarshalJSON() ([]byte, error) {
  93. return json.Marshal(asn1.ObjectIdentifier(o).String())
  94. }
  95. // UnmarshalJSON implements the json.Unmarshaler interface and coverts a strings
  96. // like "2.5.29.17" into an ASN1 object identifier.
  97. func (o *ObjectIdentifier) UnmarshalJSON(data []byte) error {
  98. s, err := unmarshalString(data)
  99. if err != nil {
  100. return err
  101. }
  102. oid, err := parseObjectIdentifier(s)
  103. if err != nil {
  104. return err
  105. }
  106. *o = ObjectIdentifier(oid)
  107. return nil
  108. }
  109. type SubjectAlternativeName struct {
  110. Type string `json:"type"`
  111. Value string `json:"value"`
  112. }
  113. func (s SubjectAlternativeName) Set(c *x509.Certificate) {
  114. switch strings.ToLower(s.Type) {
  115. case DNSType:
  116. c.DNSNames = append(c.DNSNames, s.Value)
  117. case EmailType:
  118. c.EmailAddresses = append(c.EmailAddresses, s.Value)
  119. case IPType:
  120. // The validation of the IP would happen in the unmarshaling, but just
  121. // to be sure we are only adding valid IPs.
  122. if ip := net.ParseIP(s.Value); ip != nil {
  123. c.IPAddresses = append(c.IPAddresses, ip)
  124. }
  125. case URIType:
  126. if u, err := url.Parse(s.Value); err == nil {
  127. c.URIs = append(c.URIs, u)
  128. }
  129. case "", AutoType:
  130. dnsNames, ips, emails, uris := SplitSANs([]string{s.Value})
  131. c.DNSNames = append(c.DNSNames, dnsNames...)
  132. c.IPAddresses = append(c.IPAddresses, ips...)
  133. c.EmailAddresses = append(c.EmailAddresses, emails...)
  134. c.URIs = append(c.URIs, uris...)
  135. default:
  136. panic(fmt.Sprintf("unsupported subject alternative name type %s", s.Type))
  137. }
  138. }
  139. // KeyUsage type represents the JSON array used to represent the key usages of a
  140. // X509 certificate.
  141. type KeyUsage x509.KeyUsage
  142. // Set sets the key usage to the given certificate.
  143. func (k KeyUsage) Set(c *x509.Certificate) {
  144. c.KeyUsage = x509.KeyUsage(k)
  145. }
  146. // UnmarshalJSON implements the json.Unmarshaler interface and coverts a string
  147. // or a list of strings into a key usage.
  148. func (k *KeyUsage) UnmarshalJSON(data []byte) error {
  149. ms, err := unmarshalMultiString(data)
  150. if err != nil {
  151. return err
  152. }
  153. *k = 0
  154. for _, s := range ms {
  155. var ku x509.KeyUsage
  156. switch convertName(s) {
  157. case KeyUsageDigitalSignature:
  158. ku = x509.KeyUsageDigitalSignature
  159. case KeyUsageContentCommitment:
  160. ku = x509.KeyUsageContentCommitment
  161. case KeyUsageKeyEncipherment:
  162. ku = x509.KeyUsageKeyEncipherment
  163. case KeyUsageDataEncipherment:
  164. ku = x509.KeyUsageDataEncipherment
  165. case KeyUsageKeyAgreement:
  166. ku = x509.KeyUsageKeyAgreement
  167. case KeyUsageCertSign:
  168. ku = x509.KeyUsageCertSign
  169. case KeyUsageCRLSign:
  170. ku = x509.KeyUsageCRLSign
  171. case KeyUsageEncipherOnly:
  172. ku = x509.KeyUsageEncipherOnly
  173. case KeyUsageDecipherOnly:
  174. ku = x509.KeyUsageDecipherOnly
  175. default:
  176. return errors.Errorf("unsupported keyUsage %s", s)
  177. }
  178. *k |= KeyUsage(ku)
  179. }
  180. return nil
  181. }
  182. // ExtKeyUsage represents a JSON array of extended key usages.
  183. type ExtKeyUsage []x509.ExtKeyUsage
  184. // Set sets the extended key usages in the given certificate.
  185. func (k ExtKeyUsage) Set(c *x509.Certificate) {
  186. c.ExtKeyUsage = []x509.ExtKeyUsage(k)
  187. }
  188. // UnmarshalJSON implements the json.Unmarshaler interface and coverts a string
  189. // or a list of strings into a list of extended key usages.
  190. func (k *ExtKeyUsage) UnmarshalJSON(data []byte) error {
  191. ms, err := unmarshalMultiString(data)
  192. if err != nil {
  193. return err
  194. }
  195. eku := make([]x509.ExtKeyUsage, len(ms))
  196. for i, s := range ms {
  197. var ku x509.ExtKeyUsage
  198. switch convertName(s) {
  199. case ExtKeyUsageAny:
  200. ku = x509.ExtKeyUsageAny
  201. case ExtKeyUsageServerAuth:
  202. ku = x509.ExtKeyUsageServerAuth
  203. case ExtKeyUsageClientAuth:
  204. ku = x509.ExtKeyUsageClientAuth
  205. case ExtKeyUsageCodeSigning:
  206. ku = x509.ExtKeyUsageCodeSigning
  207. case ExtKeyUsageEmailProtection:
  208. ku = x509.ExtKeyUsageEmailProtection
  209. case ExtKeyUsageIPSECEndSystem:
  210. ku = x509.ExtKeyUsageIPSECEndSystem
  211. case ExtKeyUsageIPSECTunnel:
  212. ku = x509.ExtKeyUsageIPSECTunnel
  213. case ExtKeyUsageIPSECUser:
  214. ku = x509.ExtKeyUsageIPSECUser
  215. case ExtKeyUsageTimeStamping:
  216. ku = x509.ExtKeyUsageTimeStamping
  217. case ExtKeyUsageOCSPSigning:
  218. ku = x509.ExtKeyUsageOCSPSigning
  219. case ExtKeyUsageMicrosoftServerGatedCrypto:
  220. ku = x509.ExtKeyUsageMicrosoftServerGatedCrypto
  221. case ExtKeyUsageNetscapeServerGatedCrypto:
  222. ku = x509.ExtKeyUsageNetscapeServerGatedCrypto
  223. case ExtKeyUsageMicrosoftCommercialCodeSigning:
  224. ku = x509.ExtKeyUsageMicrosoftCommercialCodeSigning
  225. case ExtKeyUsageMicrosoftKernelCodeSigning:
  226. ku = x509.ExtKeyUsageMicrosoftKernelCodeSigning
  227. default:
  228. return errors.Errorf("unsupported extKeyUsage %s", s)
  229. }
  230. eku[i] = ku
  231. }
  232. *k = ExtKeyUsage(eku)
  233. return nil
  234. }
  235. // SubjectKeyID represents the binary value of the subject key identifier
  236. // extension, this should be the SHA-1 hash of the public key. In JSON this
  237. // value should be a base64-encoded string, and in most cases it should not be
  238. // set because it will be automatically generated.
  239. type SubjectKeyID []byte
  240. // Set sets the subject key identifier to the given certificate.
  241. func (id SubjectKeyID) Set(c *x509.Certificate) {
  242. c.SubjectKeyId = id
  243. }
  244. // AuthorityKeyID represents the binary value of the authority key identifier
  245. // extension. It should be the subject key identifier of the parent certificate.
  246. // In JSON this value should be a base64-encoded string, and in most cases it
  247. // should not be set, as it will be automatically provided.
  248. type AuthorityKeyID []byte
  249. // Set sets the authority key identifier to the given certificate.
  250. func (id AuthorityKeyID) Set(c *x509.Certificate) {
  251. c.AuthorityKeyId = id
  252. }
  253. // OCSPServer contains the list of OSCP servers that will be encoded in the
  254. // authority information access extension.
  255. type OCSPServer MultiString
  256. // UnmarshalJSON implements the json.Unmarshaler interface in OCSPServer.
  257. func (o *OCSPServer) UnmarshalJSON(data []byte) error {
  258. ms, err := unmarshalMultiString(data)
  259. if err != nil {
  260. return err
  261. }
  262. *o = ms
  263. return nil
  264. }
  265. // Set sets the list of OSCP servers to the given certificate.
  266. func (o OCSPServer) Set(c *x509.Certificate) {
  267. c.OCSPServer = o
  268. }
  269. // IssuingCertificateURL contains the list of the issuing certificate url that
  270. // will be encoded in the authority information access extension.
  271. type IssuingCertificateURL MultiString
  272. // UnmarshalJSON implements the json.Unmarshaler interface in IssuingCertificateURL.
  273. func (u *IssuingCertificateURL) UnmarshalJSON(data []byte) error {
  274. ms, err := unmarshalMultiString(data)
  275. if err != nil {
  276. return err
  277. }
  278. *u = ms
  279. return nil
  280. }
  281. // Set sets the list of issuing certificate urls to the given certificate.
  282. func (u IssuingCertificateURL) Set(c *x509.Certificate) {
  283. c.IssuingCertificateURL = u
  284. }
  285. // CRLDistributionPoints contains the list of CRL distribution points that will
  286. // be encoded in the CRL distribution points extension.
  287. type CRLDistributionPoints MultiString
  288. // UnmarshalJSON implements the json.Unmarshaler interface in CRLDistributionPoints.
  289. func (u *CRLDistributionPoints) UnmarshalJSON(data []byte) error {
  290. ms, err := unmarshalMultiString(data)
  291. if err != nil {
  292. return err
  293. }
  294. *u = ms
  295. return nil
  296. }
  297. // Set sets the CRL distribution points to the given certificate.
  298. func (u CRLDistributionPoints) Set(c *x509.Certificate) {
  299. c.CRLDistributionPoints = u
  300. }
  301. // PolicyIdentifiers represents the list of OIDs to set in the certificate
  302. // policies extension.
  303. type PolicyIdentifiers MultiObjectIdentifier
  304. // MarshalJSON implements the json.Marshaler interface in PolicyIdentifiers.
  305. func (p PolicyIdentifiers) MarshalJSON() ([]byte, error) {
  306. return MultiObjectIdentifier(p).MarshalJSON()
  307. }
  308. // UnmarshalJSON implements the json.Unmarshaler interface in PolicyIdentifiers.
  309. func (p *PolicyIdentifiers) UnmarshalJSON(data []byte) error {
  310. var v MultiObjectIdentifier
  311. if err := json.Unmarshal(data, &v); err != nil {
  312. return errors.Wrap(err, "error unmarshaling json")
  313. }
  314. *p = PolicyIdentifiers(v)
  315. return nil
  316. }
  317. // Sets sets the policy identifiers to the given certificate.
  318. func (p PolicyIdentifiers) Set(c *x509.Certificate) {
  319. c.PolicyIdentifiers = p
  320. }
  321. // BasicConstraints represents the X509 basic constraints extension and defines
  322. // if a certificate is a CA and then maximum depth of valid certification paths
  323. // that include the certificate. A MaxPathLen of zero indicates that no non-
  324. // self-issued intermediate CA certificates may follow in a valid certification
  325. // path. To do not impose a limit the MaxPathLen should be set to -1.
  326. type BasicConstraints struct {
  327. IsCA bool `json:"isCA"`
  328. MaxPathLen int `json:"maxPathLen"`
  329. }
  330. // Set sets the basic constraints to the given certificate.
  331. func (b BasicConstraints) Set(c *x509.Certificate) {
  332. c.IsCA = b.IsCA
  333. if c.IsCA {
  334. c.BasicConstraintsValid = true
  335. switch {
  336. case b.MaxPathLen == 0:
  337. c.MaxPathLen = 0
  338. c.MaxPathLenZero = true
  339. case b.MaxPathLen < 0:
  340. c.MaxPathLen = -1
  341. c.MaxPathLenZero = false
  342. default:
  343. c.MaxPathLen = b.MaxPathLen
  344. c.MaxPathLenZero = false
  345. }
  346. } else {
  347. c.BasicConstraintsValid = false
  348. c.MaxPathLen = 0
  349. c.MaxPathLenZero = false
  350. }
  351. }
  352. // NameConstraints represents the X509 Name constraints extension and defines a
  353. // names space within which all subject names in subsequent certificates in a
  354. // certificate path must be located. The name constraints extension must be used
  355. // only in a CA.
  356. type NameConstraints struct {
  357. Critical bool `json:"critical"`
  358. PermittedDNSDomains MultiString `json:"permittedDNSDomains"`
  359. ExcludedDNSDomains MultiString `json:"excludedDNSDomains"`
  360. PermittedIPRanges MultiIPNet `json:"permittedIPRanges"`
  361. ExcludedIPRanges MultiIPNet `json:"excludedIPRanges"`
  362. PermittedEmailAddresses MultiString `json:"permittedEmailAddresses"`
  363. ExcludedEmailAddresses MultiString `json:"excludedEmailAddresses"`
  364. PermittedURIDomains MultiString `json:"permittedURIDomains"`
  365. ExcludedURIDomains MultiString `json:"excludedURIDomains"`
  366. }
  367. // Sets sets the name constraints in the given certificate.
  368. func (n NameConstraints) Set(c *x509.Certificate) {
  369. c.PermittedDNSDomainsCritical = n.Critical
  370. c.PermittedDNSDomains = n.PermittedDNSDomains
  371. c.ExcludedDNSDomains = n.ExcludedDNSDomains
  372. c.PermittedIPRanges = n.PermittedIPRanges
  373. c.ExcludedIPRanges = n.ExcludedIPRanges
  374. c.PermittedEmailAddresses = n.PermittedEmailAddresses
  375. c.ExcludedEmailAddresses = n.ExcludedEmailAddresses
  376. c.PermittedURIDomains = n.PermittedURIDomains
  377. c.ExcludedURIDomains = n.ExcludedURIDomains
  378. }
  379. // SerialNumber is the JSON representation of the X509 serial number.
  380. type SerialNumber struct {
  381. *big.Int
  382. }
  383. // Set sets the serial number in the given certificate.
  384. func (s SerialNumber) Set(c *x509.Certificate) {
  385. c.SerialNumber = s.Int
  386. }
  387. func (s *SerialNumber) MarshalJSON() ([]byte, error) {
  388. if s == nil || s.Int == nil {
  389. return []byte(`null`), nil
  390. }
  391. return s.Int.MarshalJSON()
  392. }
  393. // UnmarshalJSON implements the json.Unmarshal interface and unmarshals an
  394. // integer or a string into a serial number. If a string is used, a prefix of
  395. // “0b” or “0B” selects base 2, “0”, “0o” or “0O” selects base 8, and “0x” or
  396. // “0X” selects base 16. Otherwise, the selected base is 10 and no prefix is
  397. // accepted.
  398. func (s *SerialNumber) UnmarshalJSON(data []byte) error {
  399. if sn, ok := maybeString(data); ok {
  400. // Using base 0 to accept prefixes 0b, 0o, 0x but defaults as base 10.
  401. b, ok := new(big.Int).SetString(sn, 0)
  402. if !ok {
  403. return errors.Errorf("error unmarshaling json: serialNumber %s is not valid", sn)
  404. }
  405. *s = SerialNumber{
  406. Int: b,
  407. }
  408. return nil
  409. }
  410. // Assume a number.
  411. var i int64
  412. if err := json.Unmarshal(data, &i); err != nil {
  413. return errors.Wrap(err, "error unmarshaling json")
  414. }
  415. *s = SerialNumber{
  416. Int: new(big.Int).SetInt64(i),
  417. }
  418. return nil
  419. }