certificate.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. "github.com/pkg/errors"
  12. kmsapi "github.com/smallstep/certificates/kms/apiv1"
  13. pb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1"
  14. wrapperspb "google.golang.org/protobuf/types/known/wrapperspb"
  15. )
  16. var (
  17. oidExtensionSubjectKeyID = []int{2, 5, 29, 14}
  18. oidExtensionKeyUsage = []int{2, 5, 29, 15}
  19. oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
  20. oidExtensionAuthorityKeyID = []int{2, 5, 29, 35}
  21. oidExtensionBasicConstraints = []int{2, 5, 29, 19}
  22. oidExtensionSubjectAltName = []int{2, 5, 29, 17}
  23. oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
  24. oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
  25. oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
  26. )
  27. var extraExtensions = [...]asn1.ObjectIdentifier{
  28. oidExtensionSubjectKeyID, // Added by CAS
  29. oidExtensionKeyUsage, // Added in CertificateConfig.ReusableConfig
  30. oidExtensionExtendedKeyUsage, // Added in CertificateConfig.ReusableConfig
  31. oidExtensionAuthorityKeyID, // Added by CAS
  32. oidExtensionBasicConstraints, // Added in CertificateConfig.ReusableConfig
  33. oidExtensionSubjectAltName, // Added in CertificateConfig.SubjectConfig.SubjectAltName
  34. oidExtensionCRLDistributionPoints, // Added by CAS
  35. oidExtensionCertificatePolicies, // Added in CertificateConfig.ReusableConfig
  36. oidExtensionAuthorityInfoAccess, // Added in CertificateConfig.ReusableConfig and by CAS
  37. }
  38. var (
  39. oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
  40. oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
  41. oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
  42. oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
  43. oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
  44. oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
  45. oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
  46. oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
  47. )
  48. const (
  49. nameTypeEmail = 1
  50. nameTypeDNS = 2
  51. nameTypeURI = 6
  52. nameTypeIP = 7
  53. )
  54. func createCertificateConfig(tpl *x509.Certificate) (*pb.Certificate_Config, error) {
  55. pk, err := createPublicKey(tpl.PublicKey)
  56. if err != nil {
  57. return nil, err
  58. }
  59. config := &pb.CertificateConfig{
  60. SubjectConfig: &pb.CertificateConfig_SubjectConfig{
  61. Subject: createSubject(tpl),
  62. CommonName: tpl.Subject.CommonName,
  63. SubjectAltName: createSubjectAlternativeNames(tpl),
  64. },
  65. ReusableConfig: createReusableConfig(tpl),
  66. PublicKey: pk,
  67. }
  68. return &pb.Certificate_Config{
  69. Config: config,
  70. }, nil
  71. }
  72. func createPublicKey(key crypto.PublicKey) (*pb.PublicKey, error) {
  73. switch key := key.(type) {
  74. case *ecdsa.PublicKey:
  75. asn1Bytes, err := x509.MarshalPKIXPublicKey(key)
  76. if err != nil {
  77. return nil, errors.Wrap(err, "error marshaling public key")
  78. }
  79. return &pb.PublicKey{
  80. Type: pb.PublicKey_PEM_EC_KEY,
  81. Key: pem.EncodeToMemory(&pem.Block{
  82. Type: "PUBLIC KEY",
  83. Bytes: asn1Bytes,
  84. }),
  85. }, nil
  86. case *rsa.PublicKey:
  87. return &pb.PublicKey{
  88. Type: pb.PublicKey_PEM_RSA_KEY,
  89. Key: pem.EncodeToMemory(&pem.Block{
  90. Type: "RSA PUBLIC KEY",
  91. Bytes: x509.MarshalPKCS1PublicKey(key),
  92. }),
  93. }, nil
  94. default:
  95. return nil, errors.Errorf("unsupported public key type: %T", key)
  96. }
  97. }
  98. func createSubject(cert *x509.Certificate) *pb.Subject {
  99. sub := cert.Subject
  100. ret := new(pb.Subject)
  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 createReusableConfig(cert *x509.Certificate) *pb.ReusableConfigWrapper {
  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.ReusableConfigValues_CaOptions
  227. if cert.BasicConstraintsValid {
  228. var maxPathLength *wrapperspb.Int32Value
  229. switch {
  230. case cert.MaxPathLenZero:
  231. maxPathLength = wrapperspb.Int32(0)
  232. case cert.MaxPathLen > 0:
  233. maxPathLength = wrapperspb.Int32(int32(cert.MaxPathLen))
  234. default:
  235. maxPathLength = nil
  236. }
  237. caOptions = &pb.ReusableConfigValues_CaOptions{
  238. IsCa: wrapperspb.Bool(cert.IsCA),
  239. MaxIssuerPathLength: maxPathLength,
  240. }
  241. }
  242. var extraExtensions []*pb.X509Extension
  243. for _, ext := range cert.ExtraExtensions {
  244. if isExtraExtension(ext.Id) {
  245. extraExtensions = append(extraExtensions, &pb.X509Extension{
  246. ObjectId: createObjectID(ext.Id),
  247. Critical: ext.Critical,
  248. Value: ext.Value,
  249. })
  250. }
  251. }
  252. values := &pb.ReusableConfigValues{
  253. KeyUsage: &pb.KeyUsage{
  254. BaseKeyUsage: &pb.KeyUsage_KeyUsageOptions{
  255. DigitalSignature: cert.KeyUsage&x509.KeyUsageDigitalSignature > 0,
  256. ContentCommitment: cert.KeyUsage&x509.KeyUsageContentCommitment > 0,
  257. KeyEncipherment: cert.KeyUsage&x509.KeyUsageKeyEncipherment > 0,
  258. DataEncipherment: cert.KeyUsage&x509.KeyUsageDataEncipherment > 0,
  259. KeyAgreement: cert.KeyUsage&x509.KeyUsageKeyAgreement > 0,
  260. CertSign: cert.KeyUsage&x509.KeyUsageCertSign > 0,
  261. CrlSign: cert.KeyUsage&x509.KeyUsageCRLSign > 0,
  262. EncipherOnly: cert.KeyUsage&x509.KeyUsageEncipherOnly > 0,
  263. DecipherOnly: cert.KeyUsage&x509.KeyUsageDecipherOnly > 0,
  264. },
  265. ExtendedKeyUsage: ekuOptions,
  266. UnknownExtendedKeyUsages: unknownEKUs,
  267. },
  268. CaOptions: caOptions,
  269. PolicyIds: policyIDs,
  270. AiaOcspServers: cert.OCSPServer,
  271. AdditionalExtensions: extraExtensions,
  272. }
  273. return &pb.ReusableConfigWrapper{
  274. ConfigValues: &pb.ReusableConfigWrapper_ReusableConfigValues{
  275. ReusableConfigValues: values,
  276. },
  277. }
  278. }
  279. // isExtraExtension returns true if the extension oid is not managed in a
  280. // different way.
  281. func isExtraExtension(oid asn1.ObjectIdentifier) bool {
  282. for _, id := range extraExtensions {
  283. if id.Equal(oid) {
  284. return false
  285. }
  286. }
  287. return true
  288. }
  289. func createObjectID(oid asn1.ObjectIdentifier) *pb.ObjectId {
  290. ret := make([]int32, len(oid))
  291. for i, v := range oid {
  292. ret[i] = int32(v)
  293. }
  294. return &pb.ObjectId{
  295. ObjectIdPath: ret,
  296. }
  297. }
  298. func findExtraExtension(cert *x509.Certificate, oid asn1.ObjectIdentifier) (pkix.Extension, bool) {
  299. for _, ext := range cert.ExtraExtensions {
  300. if ext.Id.Equal(oid) {
  301. return ext, true
  302. }
  303. }
  304. return pkix.Extension{}, false
  305. }
  306. func createKeyVersionSpec(alg kmsapi.SignatureAlgorithm, bits int) (*pb.CertificateAuthority_KeyVersionSpec, error) {
  307. switch alg {
  308. case kmsapi.UnspecifiedSignAlgorithm, kmsapi.ECDSAWithSHA256:
  309. return &pb.CertificateAuthority_KeyVersionSpec{
  310. KeyVersion: &pb.CertificateAuthority_KeyVersionSpec_Algorithm{
  311. Algorithm: pb.CertificateAuthority_EC_P256_SHA256,
  312. },
  313. }, nil
  314. case kmsapi.ECDSAWithSHA384:
  315. return &pb.CertificateAuthority_KeyVersionSpec{
  316. KeyVersion: &pb.CertificateAuthority_KeyVersionSpec_Algorithm{
  317. Algorithm: pb.CertificateAuthority_EC_P384_SHA384,
  318. },
  319. }, nil
  320. case kmsapi.SHA256WithRSA:
  321. algo, err := getRSAPKCS1Algorithm(bits)
  322. if err != nil {
  323. return nil, err
  324. }
  325. return &pb.CertificateAuthority_KeyVersionSpec{
  326. KeyVersion: &pb.CertificateAuthority_KeyVersionSpec_Algorithm{
  327. Algorithm: algo,
  328. },
  329. }, nil
  330. case kmsapi.SHA256WithRSAPSS:
  331. algo, err := getRSAPSSAlgorithm(bits)
  332. if err != nil {
  333. return nil, err
  334. }
  335. return &pb.CertificateAuthority_KeyVersionSpec{
  336. KeyVersion: &pb.CertificateAuthority_KeyVersionSpec_Algorithm{
  337. Algorithm: algo,
  338. },
  339. }, nil
  340. default:
  341. return nil, fmt.Errorf("unknown or unsupported signature algorithm '%s'", alg)
  342. }
  343. }
  344. func getRSAPKCS1Algorithm(bits int) (pb.CertificateAuthority_SignHashAlgorithm, error) {
  345. switch bits {
  346. case 0, 3072:
  347. return pb.CertificateAuthority_RSA_PKCS1_3072_SHA256, nil
  348. case 2048:
  349. return pb.CertificateAuthority_RSA_PKCS1_2048_SHA256, nil
  350. case 4096:
  351. return pb.CertificateAuthority_RSA_PKCS1_4096_SHA256, nil
  352. default:
  353. return 0, fmt.Errorf("unsupported RSA PKCS #1 key size '%d'", bits)
  354. }
  355. }
  356. func getRSAPSSAlgorithm(bits int) (pb.CertificateAuthority_SignHashAlgorithm, error) {
  357. switch bits {
  358. case 0, 3072:
  359. return pb.CertificateAuthority_RSA_PSS_3072_SHA256, nil
  360. case 2048:
  361. return pb.CertificateAuthority_RSA_PSS_2048_SHA256, nil
  362. case 4096:
  363. return pb.CertificateAuthority_RSA_PSS_4096_SHA256, nil
  364. default:
  365. return 0, fmt.Errorf("unsupported RSA-PSS key size '%d'", bits)
  366. }
  367. }