4
0

certificate.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. package cloudcas
  2. import (
  3. "crypto"
  4. "crypto/ecdsa"
  5. "crypto/rsa"
  6. "crypto/x509"
  7. "crypto/x509/pkix"
  8. "encoding/asn1"
  9. "encoding/pem"
  10. "fmt"
  11. pb "cloud.google.com/go/security/privateca/apiv1/privatecapb"
  12. "github.com/pkg/errors"
  13. kmsapi "go.step.sm/crypto/kms/apiv1"
  14. )
  15. var (
  16. oidExtensionSubjectKeyID = []int{2, 5, 29, 14}
  17. oidExtensionKeyUsage = []int{2, 5, 29, 15}
  18. oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
  19. oidExtensionAuthorityKeyID = []int{2, 5, 29, 35}
  20. oidExtensionBasicConstraints = []int{2, 5, 29, 19}
  21. oidExtensionSubjectAltName = []int{2, 5, 29, 17}
  22. oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
  23. oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
  24. oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
  25. )
  26. var extraExtensions = [...]asn1.ObjectIdentifier{
  27. oidExtensionSubjectKeyID, // Added by CAS
  28. oidExtensionKeyUsage, // Added in CertificateConfig.ReusableConfig
  29. oidExtensionExtendedKeyUsage, // Added in CertificateConfig.ReusableConfig
  30. oidExtensionAuthorityKeyID, // Added by CAS
  31. oidExtensionBasicConstraints, // Added in CertificateConfig.ReusableConfig
  32. oidExtensionSubjectAltName, // Added in CertificateConfig.SubjectConfig.SubjectAltName
  33. oidExtensionCRLDistributionPoints, // Added by CAS
  34. oidExtensionCertificatePolicies, // Added in CertificateConfig.ReusableConfig
  35. oidExtensionAuthorityInfoAccess, // Added in CertificateConfig.ReusableConfig and by CAS
  36. }
  37. var (
  38. oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
  39. oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
  40. oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
  41. oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
  42. oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
  43. oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
  44. oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
  45. oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
  46. )
  47. const (
  48. nameTypeEmail = 1
  49. nameTypeDNS = 2
  50. nameTypeURI = 6
  51. nameTypeIP = 7
  52. )
  53. func createCertificateConfig(tpl *x509.Certificate) (*pb.Certificate_Config, error) {
  54. pk, err := createPublicKey(tpl.PublicKey)
  55. if err != nil {
  56. return nil, err
  57. }
  58. config := &pb.CertificateConfig{
  59. SubjectConfig: &pb.CertificateConfig_SubjectConfig{
  60. Subject: createSubject(tpl),
  61. SubjectAltName: createSubjectAlternativeNames(tpl),
  62. },
  63. X509Config: createX509Parameters(tpl),
  64. PublicKey: pk,
  65. }
  66. return &pb.Certificate_Config{
  67. Config: config,
  68. }, nil
  69. }
  70. func createPublicKey(key crypto.PublicKey) (*pb.PublicKey, error) {
  71. switch key := key.(type) {
  72. case *ecdsa.PublicKey:
  73. asn1Bytes, err := x509.MarshalPKIXPublicKey(key)
  74. if err != nil {
  75. return nil, errors.Wrap(err, "error marshaling public key")
  76. }
  77. return &pb.PublicKey{
  78. Format: pb.PublicKey_PEM,
  79. Key: pem.EncodeToMemory(&pem.Block{
  80. Type: "PUBLIC KEY",
  81. Bytes: asn1Bytes,
  82. }),
  83. }, nil
  84. case *rsa.PublicKey:
  85. return &pb.PublicKey{
  86. Format: pb.PublicKey_PEM,
  87. Key: pem.EncodeToMemory(&pem.Block{
  88. Type: "RSA PUBLIC KEY",
  89. Bytes: x509.MarshalPKCS1PublicKey(key),
  90. }),
  91. }, nil
  92. default:
  93. return nil, errors.Errorf("unsupported public key type: %T", key)
  94. }
  95. }
  96. func createSubject(cert *x509.Certificate) *pb.Subject {
  97. sub := cert.Subject
  98. ret := &pb.Subject{
  99. CommonName: sub.CommonName,
  100. }
  101. if len(sub.Country) > 0 {
  102. ret.CountryCode = sub.Country[0]
  103. }
  104. if len(sub.Organization) > 0 {
  105. ret.Organization = sub.Organization[0]
  106. }
  107. if len(sub.OrganizationalUnit) > 0 {
  108. ret.OrganizationalUnit = sub.OrganizationalUnit[0]
  109. }
  110. if len(sub.Locality) > 0 {
  111. ret.Locality = sub.Locality[0]
  112. }
  113. if len(sub.Province) > 0 {
  114. ret.Province = sub.Province[0]
  115. }
  116. if len(sub.StreetAddress) > 0 {
  117. ret.StreetAddress = sub.StreetAddress[0]
  118. }
  119. if len(sub.PostalCode) > 0 {
  120. ret.PostalCode = sub.PostalCode[0]
  121. }
  122. return ret
  123. }
  124. func createSubjectAlternativeNames(cert *x509.Certificate) *pb.SubjectAltNames {
  125. ret := new(pb.SubjectAltNames)
  126. ret.DnsNames = cert.DNSNames
  127. ret.EmailAddresses = cert.EmailAddresses
  128. if n := len(cert.IPAddresses); n > 0 {
  129. ret.IpAddresses = make([]string, n)
  130. for i, ip := range cert.IPAddresses {
  131. ret.IpAddresses[i] = ip.String()
  132. }
  133. }
  134. if n := len(cert.URIs); n > 0 {
  135. ret.Uris = make([]string, n)
  136. for i, u := range cert.URIs {
  137. ret.Uris[i] = u.String()
  138. }
  139. }
  140. // Add extra SANs coming from the extensions
  141. if ext, ok := findExtraExtension(cert, oidExtensionSubjectAltName); ok {
  142. var rawValues []asn1.RawValue
  143. if _, err := asn1.Unmarshal(ext.Value, &rawValues); err == nil {
  144. var newValues []asn1.RawValue
  145. for _, v := range rawValues {
  146. if v.Class == asn1.ClassContextSpecific {
  147. switch v.Tag {
  148. case nameTypeDNS:
  149. if len(ret.DnsNames) == 0 {
  150. newValues = append(newValues, v)
  151. }
  152. case nameTypeEmail:
  153. if len(ret.EmailAddresses) == 0 {
  154. newValues = append(newValues, v)
  155. }
  156. case nameTypeIP:
  157. if len(ret.IpAddresses) == 0 {
  158. newValues = append(newValues, v)
  159. }
  160. case nameTypeURI:
  161. if len(ret.Uris) == 0 {
  162. newValues = append(newValues, v)
  163. }
  164. default:
  165. newValues = append(newValues, v)
  166. }
  167. } else {
  168. newValues = append(newValues, v)
  169. }
  170. }
  171. if len(newValues) > 0 {
  172. if b, err := asn1.Marshal(newValues); err == nil {
  173. ret.CustomSans = []*pb.X509Extension{{
  174. ObjectId: createObjectID(ext.Id),
  175. Critical: ext.Critical,
  176. Value: b,
  177. }}
  178. }
  179. }
  180. }
  181. }
  182. return ret
  183. }
  184. func createX509Parameters(cert *x509.Certificate) *pb.X509Parameters {
  185. var unknownEKUs []*pb.ObjectId
  186. var ekuOptions = &pb.KeyUsage_ExtendedKeyUsageOptions{}
  187. for _, eku := range cert.ExtKeyUsage {
  188. switch eku {
  189. case x509.ExtKeyUsageAny:
  190. unknownEKUs = append(unknownEKUs, createObjectID(oidExtKeyUsageAny))
  191. case x509.ExtKeyUsageServerAuth:
  192. ekuOptions.ServerAuth = true
  193. case x509.ExtKeyUsageClientAuth:
  194. ekuOptions.ClientAuth = true
  195. case x509.ExtKeyUsageCodeSigning:
  196. ekuOptions.CodeSigning = true
  197. case x509.ExtKeyUsageEmailProtection:
  198. ekuOptions.EmailProtection = true
  199. case x509.ExtKeyUsageIPSECEndSystem:
  200. unknownEKUs = append(unknownEKUs, createObjectID(oidExtKeyUsageIPSECEndSystem))
  201. case x509.ExtKeyUsageIPSECTunnel:
  202. unknownEKUs = append(unknownEKUs, createObjectID(oidExtKeyUsageIPSECTunnel))
  203. case x509.ExtKeyUsageIPSECUser:
  204. unknownEKUs = append(unknownEKUs, createObjectID(oidExtKeyUsageIPSECUser))
  205. case x509.ExtKeyUsageTimeStamping:
  206. ekuOptions.TimeStamping = true
  207. case x509.ExtKeyUsageOCSPSigning:
  208. ekuOptions.OcspSigning = true
  209. case x509.ExtKeyUsageMicrosoftServerGatedCrypto:
  210. unknownEKUs = append(unknownEKUs, createObjectID(oidExtKeyUsageMicrosoftServerGatedCrypto))
  211. case x509.ExtKeyUsageNetscapeServerGatedCrypto:
  212. unknownEKUs = append(unknownEKUs, createObjectID(oidExtKeyUsageNetscapeServerGatedCrypto))
  213. case x509.ExtKeyUsageMicrosoftCommercialCodeSigning:
  214. unknownEKUs = append(unknownEKUs, createObjectID(oidExtKeyUsageMicrosoftCommercialCodeSigning))
  215. case x509.ExtKeyUsageMicrosoftKernelCodeSigning:
  216. unknownEKUs = append(unknownEKUs, createObjectID(oidExtKeyUsageMicrosoftKernelCodeSigning))
  217. }
  218. }
  219. for _, oid := range cert.UnknownExtKeyUsage {
  220. unknownEKUs = append(unknownEKUs, createObjectID(oid))
  221. }
  222. var policyIDs []*pb.ObjectId
  223. for _, oid := range cert.PolicyIdentifiers {
  224. policyIDs = append(policyIDs, createObjectID(oid))
  225. }
  226. var caOptions *pb.X509Parameters_CaOptions
  227. if cert.BasicConstraintsValid {
  228. caOptions = new(pb.X509Parameters_CaOptions)
  229. var maxPathLength int32
  230. switch {
  231. case cert.MaxPathLenZero:
  232. maxPathLength = 0
  233. caOptions.MaxIssuerPathLength = &maxPathLength
  234. case cert.MaxPathLen > 0:
  235. maxPathLength = int32(cert.MaxPathLen)
  236. caOptions.MaxIssuerPathLength = &maxPathLength
  237. }
  238. caOptions.IsCa = &cert.IsCA
  239. }
  240. var extraExtensions []*pb.X509Extension
  241. for _, ext := range cert.ExtraExtensions {
  242. if isExtraExtension(ext.Id) {
  243. extraExtensions = append(extraExtensions, &pb.X509Extension{
  244. ObjectId: createObjectID(ext.Id),
  245. Critical: ext.Critical,
  246. Value: ext.Value,
  247. })
  248. }
  249. }
  250. return &pb.X509Parameters{
  251. KeyUsage: &pb.KeyUsage{
  252. BaseKeyUsage: &pb.KeyUsage_KeyUsageOptions{
  253. DigitalSignature: cert.KeyUsage&x509.KeyUsageDigitalSignature > 0,
  254. ContentCommitment: cert.KeyUsage&x509.KeyUsageContentCommitment > 0,
  255. KeyEncipherment: cert.KeyUsage&x509.KeyUsageKeyEncipherment > 0,
  256. DataEncipherment: cert.KeyUsage&x509.KeyUsageDataEncipherment > 0,
  257. KeyAgreement: cert.KeyUsage&x509.KeyUsageKeyAgreement > 0,
  258. CertSign: cert.KeyUsage&x509.KeyUsageCertSign > 0,
  259. CrlSign: cert.KeyUsage&x509.KeyUsageCRLSign > 0,
  260. EncipherOnly: cert.KeyUsage&x509.KeyUsageEncipherOnly > 0,
  261. DecipherOnly: cert.KeyUsage&x509.KeyUsageDecipherOnly > 0,
  262. },
  263. ExtendedKeyUsage: ekuOptions,
  264. UnknownExtendedKeyUsages: unknownEKUs,
  265. },
  266. CaOptions: caOptions,
  267. PolicyIds: policyIDs,
  268. AiaOcspServers: cert.OCSPServer,
  269. AdditionalExtensions: extraExtensions,
  270. }
  271. }
  272. // isExtraExtension returns true if the extension oid is not managed in a
  273. // different way.
  274. func isExtraExtension(oid asn1.ObjectIdentifier) bool {
  275. for _, id := range extraExtensions {
  276. if id.Equal(oid) {
  277. return false
  278. }
  279. }
  280. return true
  281. }
  282. func createObjectID(oid asn1.ObjectIdentifier) *pb.ObjectId {
  283. ret := make([]int32, len(oid))
  284. for i, v := range oid {
  285. ret[i] = int32(v)
  286. }
  287. return &pb.ObjectId{
  288. ObjectIdPath: ret,
  289. }
  290. }
  291. func findExtraExtension(cert *x509.Certificate, oid asn1.ObjectIdentifier) (pkix.Extension, bool) {
  292. for _, ext := range cert.ExtraExtensions {
  293. if ext.Id.Equal(oid) {
  294. return ext, true
  295. }
  296. }
  297. return pkix.Extension{}, false
  298. }
  299. func createKeyVersionSpec(alg kmsapi.SignatureAlgorithm, bits int) (*pb.CertificateAuthority_KeyVersionSpec, error) {
  300. switch alg {
  301. case kmsapi.UnspecifiedSignAlgorithm, kmsapi.ECDSAWithSHA256:
  302. return &pb.CertificateAuthority_KeyVersionSpec{
  303. KeyVersion: &pb.CertificateAuthority_KeyVersionSpec_Algorithm{
  304. Algorithm: pb.CertificateAuthority_EC_P256_SHA256,
  305. },
  306. }, nil
  307. case kmsapi.ECDSAWithSHA384:
  308. return &pb.CertificateAuthority_KeyVersionSpec{
  309. KeyVersion: &pb.CertificateAuthority_KeyVersionSpec_Algorithm{
  310. Algorithm: pb.CertificateAuthority_EC_P384_SHA384,
  311. },
  312. }, nil
  313. case kmsapi.SHA256WithRSA:
  314. algo, err := getRSAPKCS1Algorithm(bits)
  315. if err != nil {
  316. return nil, err
  317. }
  318. return &pb.CertificateAuthority_KeyVersionSpec{
  319. KeyVersion: &pb.CertificateAuthority_KeyVersionSpec_Algorithm{
  320. Algorithm: algo,
  321. },
  322. }, nil
  323. case kmsapi.SHA256WithRSAPSS:
  324. algo, err := getRSAPSSAlgorithm(bits)
  325. if err != nil {
  326. return nil, err
  327. }
  328. return &pb.CertificateAuthority_KeyVersionSpec{
  329. KeyVersion: &pb.CertificateAuthority_KeyVersionSpec_Algorithm{
  330. Algorithm: algo,
  331. },
  332. }, nil
  333. default:
  334. return nil, fmt.Errorf("unknown or unsupported signature algorithm '%s'", alg)
  335. }
  336. }
  337. func getRSAPKCS1Algorithm(bits int) (pb.CertificateAuthority_SignHashAlgorithm, error) {
  338. switch bits {
  339. case 0, 3072:
  340. return pb.CertificateAuthority_RSA_PKCS1_3072_SHA256, nil
  341. case 2048:
  342. return pb.CertificateAuthority_RSA_PKCS1_2048_SHA256, nil
  343. case 4096:
  344. return pb.CertificateAuthority_RSA_PKCS1_4096_SHA256, nil
  345. default:
  346. return 0, fmt.Errorf("unsupported RSA PKCS #1 key size '%d'", bits)
  347. }
  348. }
  349. func getRSAPSSAlgorithm(bits int) (pb.CertificateAuthority_SignHashAlgorithm, error) {
  350. switch bits {
  351. case 0, 3072:
  352. return pb.CertificateAuthority_RSA_PSS_3072_SHA256, nil
  353. case 2048:
  354. return pb.CertificateAuthority_RSA_PSS_2048_SHA256, nil
  355. case 4096:
  356. return pb.CertificateAuthority_RSA_PSS_4096_SHA256, nil
  357. default:
  358. return 0, fmt.Errorf("unsupported RSA-PSS key size '%d'", bits)
  359. }
  360. }