local.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. // Package local implements certificate signature functionality for CFSSL.
  2. package local
  3. import (
  4. "bytes"
  5. "context"
  6. "crypto"
  7. "crypto/ecdsa"
  8. "crypto/elliptic"
  9. "crypto/rand"
  10. "crypto/x509"
  11. "crypto/x509/pkix"
  12. "database/sql"
  13. "encoding/asn1"
  14. "encoding/hex"
  15. "encoding/pem"
  16. "errors"
  17. "fmt"
  18. "io"
  19. "math/big"
  20. "net"
  21. "net/http"
  22. "net/mail"
  23. "net/url"
  24. "os"
  25. "time"
  26. "github.com/cloudflare/cfssl/certdb"
  27. "github.com/cloudflare/cfssl/config"
  28. cferr "github.com/cloudflare/cfssl/errors"
  29. "github.com/cloudflare/cfssl/helpers"
  30. "github.com/cloudflare/cfssl/info"
  31. "github.com/cloudflare/cfssl/log"
  32. "github.com/cloudflare/cfssl/signer"
  33. ct "github.com/google/certificate-transparency-go"
  34. "github.com/google/certificate-transparency-go/client"
  35. "github.com/google/certificate-transparency-go/jsonclient"
  36. zx509 "github.com/zmap/zcrypto/x509"
  37. "github.com/zmap/zlint/v3"
  38. "github.com/zmap/zlint/v3/lint"
  39. )
  40. // Signer contains a signer that uses the standard library to
  41. // support both ECDSA and RSA CA keys.
  42. type Signer struct {
  43. ca *x509.Certificate
  44. priv crypto.Signer
  45. // lintPriv is generated randomly when pre-issuance linting is configured and
  46. // used to sign TBSCertificates for linting.
  47. lintPriv crypto.Signer
  48. policy *config.Signing
  49. sigAlgo x509.SignatureAlgorithm
  50. dbAccessor certdb.Accessor
  51. }
  52. // NewSigner creates a new Signer directly from a
  53. // private key and certificate, with optional policy.
  54. func NewSigner(priv crypto.Signer, cert *x509.Certificate, sigAlgo x509.SignatureAlgorithm, policy *config.Signing) (*Signer, error) {
  55. if policy == nil {
  56. policy = &config.Signing{
  57. Profiles: map[string]*config.SigningProfile{},
  58. Default: config.DefaultConfig()}
  59. }
  60. if !policy.Valid() {
  61. return nil, cferr.New(cferr.PolicyError, cferr.InvalidPolicy)
  62. }
  63. var lintPriv crypto.Signer
  64. // If there is at least one profile (including the default) that configures
  65. // pre-issuance linting then generate the one-off lintPriv key.
  66. for _, profile := range policy.Profiles {
  67. if profile.LintErrLevel > 0 || policy.Default.LintErrLevel > 0 {
  68. // In the future there may be demand for specifying the type of signer used
  69. // for pre-issuance linting in configuration. For now we assume that signing
  70. // with a randomly generated P-256 ECDSA private key is acceptable for all cases
  71. // where linting is requested.
  72. k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  73. if err != nil {
  74. return nil, cferr.New(cferr.PrivateKeyError, cferr.GenerationFailed)
  75. }
  76. lintPriv = k
  77. break
  78. }
  79. }
  80. return &Signer{
  81. ca: cert,
  82. priv: priv,
  83. lintPriv: lintPriv,
  84. sigAlgo: sigAlgo,
  85. policy: policy,
  86. }, nil
  87. }
  88. // NewSignerFromFile generates a new local signer from a caFile
  89. // and a caKey file, both PEM encoded.
  90. func NewSignerFromFile(caFile, caKeyFile string, policy *config.Signing) (*Signer, error) {
  91. log.Debug("Loading CA: ", caFile)
  92. ca, err := helpers.ReadBytes(caFile)
  93. if err != nil {
  94. return nil, err
  95. }
  96. log.Debug("Loading CA key: ", caKeyFile)
  97. cakey, err := helpers.ReadBytes(caKeyFile)
  98. if err != nil {
  99. return nil, cferr.Wrap(cferr.CertificateError, cferr.ReadFailed, err)
  100. }
  101. parsedCa, err := helpers.ParseCertificatePEM(ca)
  102. if err != nil {
  103. return nil, err
  104. }
  105. strPassword := os.Getenv("CFSSL_CA_PK_PASSWORD")
  106. password := []byte(strPassword)
  107. if strPassword == "" {
  108. password = nil
  109. }
  110. priv, err := helpers.ParsePrivateKeyPEMWithPassword(cakey, password)
  111. if err != nil {
  112. log.Debugf("Malformed private key %v", err)
  113. return nil, err
  114. }
  115. return NewSigner(priv, parsedCa, signer.DefaultSigAlgo(priv), policy)
  116. }
  117. // LintError is an error type returned when pre-issuance linting is configured
  118. // in a signing profile and a TBS Certificate fails linting. It wraps the
  119. // concrete zlint LintResults so that callers can further inspect the cause of
  120. // the failing lints.
  121. type LintError struct {
  122. ErrorResults map[string]lint.LintResult
  123. }
  124. func (e *LintError) Error() string {
  125. return fmt.Sprintf("pre-issuance linting found %d error results",
  126. len(e.ErrorResults))
  127. }
  128. // lint performs pre-issuance linting of a given TBS certificate template when
  129. // the provided errLevel is > 0. Note that the template is provided by-value and
  130. // not by-reference. This is important as the lint function needs to mutate the
  131. // template's signature algorithm to match the lintPriv.
  132. func (s *Signer) lint(template x509.Certificate, errLevel lint.LintStatus, lintRegistry lint.Registry) error {
  133. // Always return nil when linting is disabled (lint.Reserved == 0).
  134. if errLevel == lint.Reserved {
  135. return nil
  136. }
  137. // without a lintPriv key to use to sign the tbsCertificate we can't lint it.
  138. if s.lintPriv == nil {
  139. return cferr.New(cferr.PrivateKeyError, cferr.Unavailable)
  140. }
  141. // The template's SignatureAlgorithm must be mutated to match the lintPriv or
  142. // x509.CreateCertificate will error because of the mismatch. At the time of
  143. // writing s.lintPriv is always an ECDSA private key. This switch will need to
  144. // be expanded if the lint key type is made configurable.
  145. switch s.lintPriv.(type) {
  146. case *ecdsa.PrivateKey:
  147. template.SignatureAlgorithm = x509.ECDSAWithSHA256
  148. default:
  149. return cferr.New(cferr.PrivateKeyError, cferr.KeyMismatch)
  150. }
  151. prelintBytes, err := x509.CreateCertificate(rand.Reader, &template, s.ca, template.PublicKey, s.lintPriv)
  152. if err != nil {
  153. return cferr.Wrap(cferr.CertificateError, cferr.Unknown, err)
  154. }
  155. prelintCert, err := zx509.ParseCertificate(prelintBytes)
  156. if err != nil {
  157. return cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
  158. }
  159. errorResults := map[string]lint.LintResult{}
  160. results := zlint.LintCertificateEx(prelintCert, lintRegistry)
  161. for name, res := range results.Results {
  162. if res.Status > errLevel {
  163. errorResults[name] = *res
  164. }
  165. }
  166. if len(errorResults) > 0 {
  167. return &LintError{
  168. ErrorResults: errorResults,
  169. }
  170. }
  171. return nil
  172. }
  173. func (s *Signer) sign(template *x509.Certificate, lintErrLevel lint.LintStatus, lintRegistry lint.Registry) (cert []byte, err error) {
  174. var initRoot bool
  175. if s.ca == nil {
  176. if !template.IsCA {
  177. err = cferr.New(cferr.PolicyError, cferr.InvalidRequest)
  178. return
  179. }
  180. template.DNSNames = nil
  181. template.EmailAddresses = nil
  182. template.URIs = nil
  183. s.ca = template
  184. initRoot = true
  185. }
  186. if err := s.lint(*template, lintErrLevel, lintRegistry); err != nil {
  187. return nil, err
  188. }
  189. derBytes, err := x509.CreateCertificate(rand.Reader, template, s.ca, template.PublicKey, s.priv)
  190. if err != nil {
  191. return nil, cferr.Wrap(cferr.CertificateError, cferr.Unknown, err)
  192. }
  193. if initRoot {
  194. s.ca, err = x509.ParseCertificate(derBytes)
  195. if err != nil {
  196. return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
  197. }
  198. }
  199. cert = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  200. log.Infof("signed certificate with serial number %d", template.SerialNumber)
  201. return
  202. }
  203. // replaceSliceIfEmpty replaces the contents of replaced with newContents if
  204. // the slice referenced by replaced is empty
  205. func replaceSliceIfEmpty(replaced, newContents *[]string) {
  206. if len(*replaced) == 0 {
  207. *replaced = *newContents
  208. }
  209. }
  210. // PopulateSubjectFromCSR has functionality similar to Name, except
  211. // it fills the fields of the resulting pkix.Name with req's if the
  212. // subject's corresponding fields are empty
  213. func PopulateSubjectFromCSR(s *signer.Subject, req pkix.Name) pkix.Name {
  214. // if no subject, use req
  215. if s == nil {
  216. return req
  217. }
  218. name := s.Name()
  219. if name.CommonName == "" {
  220. name.CommonName = req.CommonName
  221. }
  222. replaceSliceIfEmpty(&name.Country, &req.Country)
  223. replaceSliceIfEmpty(&name.Province, &req.Province)
  224. replaceSliceIfEmpty(&name.Locality, &req.Locality)
  225. replaceSliceIfEmpty(&name.Organization, &req.Organization)
  226. replaceSliceIfEmpty(&name.OrganizationalUnit, &req.OrganizationalUnit)
  227. if name.SerialNumber == "" {
  228. name.SerialNumber = req.SerialNumber
  229. }
  230. return name
  231. }
  232. // OverrideHosts fills template's IPAddresses, EmailAddresses, DNSNames, and URIs with the
  233. // content of hosts, if it is not nil.
  234. func OverrideHosts(template *x509.Certificate, hosts []string) {
  235. if hosts != nil {
  236. template.IPAddresses = []net.IP{}
  237. template.EmailAddresses = []string{}
  238. template.DNSNames = []string{}
  239. template.URIs = []*url.URL{}
  240. }
  241. for i := range hosts {
  242. if ip := net.ParseIP(hosts[i]); ip != nil {
  243. template.IPAddresses = append(template.IPAddresses, ip)
  244. } else if email, err := mail.ParseAddress(hosts[i]); err == nil && email != nil {
  245. template.EmailAddresses = append(template.EmailAddresses, email.Address)
  246. } else if uri, err := url.ParseRequestURI(hosts[i]); err == nil && uri != nil {
  247. template.URIs = append(template.URIs, uri)
  248. } else {
  249. template.DNSNames = append(template.DNSNames, hosts[i])
  250. }
  251. }
  252. }
  253. // Sign signs a new certificate based on the PEM-encoded client
  254. // certificate or certificate request with the signing profile,
  255. // specified by profileName.
  256. func (s *Signer) Sign(req signer.SignRequest) (cert []byte, err error) {
  257. profile, err := signer.Profile(s, req.Profile)
  258. if err != nil {
  259. return
  260. }
  261. block, _ := pem.Decode([]byte(req.Request))
  262. if block == nil {
  263. return nil, cferr.New(cferr.CSRError, cferr.DecodeFailed)
  264. }
  265. if block.Type != "NEW CERTIFICATE REQUEST" && block.Type != "CERTIFICATE REQUEST" {
  266. return nil, cferr.Wrap(cferr.CSRError,
  267. cferr.BadRequest, errors.New("not a csr"))
  268. }
  269. csrTemplate, err := signer.ParseCertificateRequest(s, profile, block.Bytes)
  270. if err != nil {
  271. return nil, err
  272. }
  273. // Copy out only the fields from the CSR authorized by policy.
  274. safeTemplate := x509.Certificate{}
  275. // If the profile contains no explicit whitelist, assume that all fields
  276. // should be copied from the CSR.
  277. if profile.CSRWhitelist == nil {
  278. safeTemplate = *csrTemplate
  279. } else {
  280. if profile.CSRWhitelist.Subject {
  281. safeTemplate.Subject = csrTemplate.Subject
  282. }
  283. if profile.CSRWhitelist.PublicKeyAlgorithm {
  284. safeTemplate.PublicKeyAlgorithm = csrTemplate.PublicKeyAlgorithm
  285. }
  286. if profile.CSRWhitelist.PublicKey {
  287. safeTemplate.PublicKey = csrTemplate.PublicKey
  288. }
  289. if profile.CSRWhitelist.SignatureAlgorithm {
  290. safeTemplate.SignatureAlgorithm = csrTemplate.SignatureAlgorithm
  291. }
  292. if profile.CSRWhitelist.DNSNames {
  293. safeTemplate.DNSNames = csrTemplate.DNSNames
  294. }
  295. if profile.CSRWhitelist.IPAddresses {
  296. safeTemplate.IPAddresses = csrTemplate.IPAddresses
  297. }
  298. if profile.CSRWhitelist.EmailAddresses {
  299. safeTemplate.EmailAddresses = csrTemplate.EmailAddresses
  300. }
  301. if profile.CSRWhitelist.URIs {
  302. safeTemplate.URIs = csrTemplate.URIs
  303. }
  304. }
  305. if req.CRLOverride != "" {
  306. safeTemplate.CRLDistributionPoints = []string{req.CRLOverride}
  307. }
  308. if safeTemplate.IsCA {
  309. if !profile.CAConstraint.IsCA {
  310. log.Error("local signer policy disallows issuing CA certificate")
  311. return nil, cferr.New(cferr.PolicyError, cferr.InvalidRequest)
  312. }
  313. if s.ca != nil && s.ca.MaxPathLen > 0 {
  314. if safeTemplate.MaxPathLen >= s.ca.MaxPathLen {
  315. log.Error("local signer certificate disallows CA MaxPathLen extending")
  316. // do not sign a cert with pathlen > current
  317. return nil, cferr.New(cferr.PolicyError, cferr.InvalidRequest)
  318. }
  319. } else if s.ca != nil && s.ca.MaxPathLen == 0 && s.ca.MaxPathLenZero {
  320. log.Error("local signer certificate disallows issuing CA certificate")
  321. // signer has pathlen of 0, do not sign more intermediate CAs
  322. return nil, cferr.New(cferr.PolicyError, cferr.InvalidRequest)
  323. }
  324. }
  325. OverrideHosts(&safeTemplate, req.Hosts)
  326. safeTemplate.Subject = PopulateSubjectFromCSR(req.Subject, safeTemplate.Subject)
  327. // If there is a whitelist, ensure that both the Common Name and SAN DNSNames match
  328. if profile.NameWhitelist != nil {
  329. if safeTemplate.Subject.CommonName != "" {
  330. if profile.NameWhitelist.Find([]byte(safeTemplate.Subject.CommonName)) == nil {
  331. return nil, cferr.New(cferr.PolicyError, cferr.UnmatchedWhitelist)
  332. }
  333. }
  334. for _, name := range safeTemplate.DNSNames {
  335. if profile.NameWhitelist.Find([]byte(name)) == nil {
  336. return nil, cferr.New(cferr.PolicyError, cferr.UnmatchedWhitelist)
  337. }
  338. }
  339. for _, name := range safeTemplate.EmailAddresses {
  340. if profile.NameWhitelist.Find([]byte(name)) == nil {
  341. return nil, cferr.New(cferr.PolicyError, cferr.UnmatchedWhitelist)
  342. }
  343. }
  344. for _, name := range safeTemplate.URIs {
  345. if profile.NameWhitelist.Find([]byte(name.String())) == nil {
  346. return nil, cferr.New(cferr.PolicyError, cferr.UnmatchedWhitelist)
  347. }
  348. }
  349. }
  350. if profile.ClientProvidesSerialNumbers {
  351. if req.Serial == nil {
  352. return nil, cferr.New(cferr.CertificateError, cferr.MissingSerial)
  353. }
  354. safeTemplate.SerialNumber = req.Serial
  355. } else {
  356. // RFC 5280 4.1.2.2:
  357. // Certificate users MUST be able to handle serialNumber
  358. // values up to 20 octets. Conforming CAs MUST NOT use
  359. // serialNumber values longer than 20 octets.
  360. //
  361. // If CFSSL is providing the serial numbers, it makes
  362. // sense to use the max supported size.
  363. serialNumber := make([]byte, 20)
  364. _, err = io.ReadFull(rand.Reader, serialNumber)
  365. if err != nil {
  366. return nil, cferr.Wrap(cferr.CertificateError, cferr.Unknown, err)
  367. }
  368. // SetBytes interprets buf as the bytes of a big-endian
  369. // unsigned integer. The leading byte should be masked
  370. // off to ensure it isn't negative.
  371. serialNumber[0] &= 0x7F
  372. safeTemplate.SerialNumber = new(big.Int).SetBytes(serialNumber)
  373. }
  374. if len(req.Extensions) > 0 {
  375. for _, ext := range req.Extensions {
  376. oid := asn1.ObjectIdentifier(ext.ID)
  377. if !profile.ExtensionWhitelist[oid.String()] {
  378. return nil, cferr.New(cferr.CertificateError, cferr.InvalidRequest)
  379. }
  380. rawValue, err := hex.DecodeString(ext.Value)
  381. if err != nil {
  382. return nil, cferr.Wrap(cferr.CertificateError, cferr.InvalidRequest, err)
  383. }
  384. safeTemplate.ExtraExtensions = append(safeTemplate.ExtraExtensions, pkix.Extension{
  385. Id: oid,
  386. Critical: ext.Critical,
  387. Value: rawValue,
  388. })
  389. }
  390. }
  391. var distPoints = safeTemplate.CRLDistributionPoints
  392. err = signer.FillTemplate(&safeTemplate, s.policy.Default, profile, req.NotBefore, req.NotAfter)
  393. if err != nil {
  394. return nil, err
  395. }
  396. if distPoints != nil && len(distPoints) > 0 {
  397. safeTemplate.CRLDistributionPoints = distPoints
  398. }
  399. var certTBS = safeTemplate
  400. if len(profile.CTLogServers) > 0 || req.ReturnPrecert {
  401. // Add a poison extension which prevents validation
  402. var poisonExtension = pkix.Extension{Id: signer.CTPoisonOID, Critical: true, Value: []byte{0x05, 0x00}}
  403. var poisonedPreCert = certTBS
  404. poisonedPreCert.ExtraExtensions = append(safeTemplate.ExtraExtensions, poisonExtension)
  405. cert, err = s.sign(&poisonedPreCert, profile.LintErrLevel, profile.LintRegistry)
  406. if err != nil {
  407. return
  408. }
  409. if req.ReturnPrecert {
  410. return cert, nil
  411. }
  412. derCert, _ := pem.Decode(cert)
  413. prechain := []ct.ASN1Cert{{Data: derCert.Bytes}, {Data: s.ca.Raw}}
  414. var sctList []ct.SignedCertificateTimestamp
  415. for _, server := range profile.CTLogServers {
  416. log.Infof("submitting poisoned precertificate to %s", server)
  417. ctclient, err := client.New(server, nil, jsonclient.Options{})
  418. if err != nil {
  419. return nil, cferr.Wrap(cferr.CTError, cferr.PrecertSubmissionFailed, err)
  420. }
  421. var resp *ct.SignedCertificateTimestamp
  422. ctx := context.Background()
  423. resp, err = ctclient.AddPreChain(ctx, prechain)
  424. if err != nil {
  425. return nil, cferr.Wrap(cferr.CTError, cferr.PrecertSubmissionFailed, err)
  426. }
  427. sctList = append(sctList, *resp)
  428. }
  429. var serializedSCTList []byte
  430. serializedSCTList, err = helpers.SerializeSCTList(sctList)
  431. if err != nil {
  432. return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, err)
  433. }
  434. // Serialize again as an octet string before embedding
  435. serializedSCTList, err = asn1.Marshal(serializedSCTList)
  436. if err != nil {
  437. return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, err)
  438. }
  439. var SCTListExtension = pkix.Extension{Id: signer.SCTListOID, Critical: false, Value: serializedSCTList}
  440. certTBS.ExtraExtensions = append(certTBS.ExtraExtensions, SCTListExtension)
  441. }
  442. var signedCert []byte
  443. signedCert, err = s.sign(&certTBS, profile.LintErrLevel, profile.LintRegistry)
  444. if err != nil {
  445. return nil, err
  446. }
  447. // Get the AKI from signedCert. This is required to support Go 1.9+.
  448. // In prior versions of Go, x509.CreateCertificate updated the
  449. // AuthorityKeyId of certTBS.
  450. parsedCert, _ := helpers.ParseCertificatePEM(signedCert)
  451. if s.dbAccessor != nil {
  452. now := time.Now()
  453. var certRecord = certdb.CertificateRecord{
  454. Serial: certTBS.SerialNumber.String(),
  455. // this relies on the specific behavior of x509.CreateCertificate
  456. // which sets the AuthorityKeyId from the signer's SubjectKeyId
  457. AKI: hex.EncodeToString(parsedCert.AuthorityKeyId),
  458. CALabel: req.Label,
  459. Status: "good",
  460. Expiry: certTBS.NotAfter,
  461. PEM: string(signedCert),
  462. IssuedAt: &now,
  463. NotBefore: &certTBS.NotBefore,
  464. CommonName: sql.NullString{String: certTBS.Subject.CommonName, Valid: true},
  465. }
  466. if err := certRecord.SetMetadata(req.Metadata); err != nil {
  467. return nil, err
  468. }
  469. if err := certRecord.SetSANs(certTBS.DNSNames); err != nil {
  470. return nil, err
  471. }
  472. if err := s.dbAccessor.InsertCertificate(certRecord); err != nil {
  473. return nil, err
  474. }
  475. log.Debug("saved certificate with serial number ", certTBS.SerialNumber)
  476. }
  477. return signedCert, nil
  478. }
  479. // SignFromPrecert creates and signs a certificate from an existing precertificate
  480. // that was previously signed by Signer.ca and inserts the provided SCTs into the
  481. // new certificate. The resulting certificate will be a exact copy of the precert
  482. // except for the removal of the poison extension and the addition of the SCT list
  483. // extension. SignFromPrecert does not verify that the contents of the certificate
  484. // still match the signing profile of the signer, it only requires that the precert
  485. // was previously signed by the Signers CA. Similarly, any linting configured
  486. // by the profile used to sign the precert will not be re-applied to the final
  487. // cert and must be done separately by the caller.
  488. func (s *Signer) SignFromPrecert(precert *x509.Certificate, scts []ct.SignedCertificateTimestamp) ([]byte, error) {
  489. // Verify certificate was signed by s.ca
  490. if err := precert.CheckSignatureFrom(s.ca); err != nil {
  491. return nil, err
  492. }
  493. // Verify certificate is a precert
  494. isPrecert := false
  495. poisonIndex := 0
  496. for i, ext := range precert.Extensions {
  497. if ext.Id.Equal(signer.CTPoisonOID) {
  498. if !ext.Critical {
  499. return nil, cferr.New(cferr.CTError, cferr.PrecertInvalidPoison)
  500. }
  501. // Check extension contains ASN.1 NULL
  502. if bytes.Compare(ext.Value, []byte{0x05, 0x00}) != 0 {
  503. return nil, cferr.New(cferr.CTError, cferr.PrecertInvalidPoison)
  504. }
  505. isPrecert = true
  506. poisonIndex = i
  507. break
  508. }
  509. }
  510. if !isPrecert {
  511. return nil, cferr.New(cferr.CTError, cferr.PrecertMissingPoison)
  512. }
  513. // Serialize SCTs into list format and create extension
  514. serializedList, err := helpers.SerializeSCTList(scts)
  515. if err != nil {
  516. return nil, err
  517. }
  518. // Serialize again as an octet string before embedding
  519. serializedList, err = asn1.Marshal(serializedList)
  520. if err != nil {
  521. return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, err)
  522. }
  523. sctExt := pkix.Extension{Id: signer.SCTListOID, Critical: false, Value: serializedList}
  524. // Create the new tbsCert from precert. Do explicit copies of any slices so that we don't
  525. // use memory that may be altered by us or the caller at a later stage.
  526. tbsCert := x509.Certificate{
  527. SignatureAlgorithm: precert.SignatureAlgorithm,
  528. PublicKeyAlgorithm: precert.PublicKeyAlgorithm,
  529. PublicKey: precert.PublicKey,
  530. Version: precert.Version,
  531. SerialNumber: precert.SerialNumber,
  532. Issuer: precert.Issuer,
  533. Subject: precert.Subject,
  534. NotBefore: precert.NotBefore,
  535. NotAfter: precert.NotAfter,
  536. KeyUsage: precert.KeyUsage,
  537. BasicConstraintsValid: precert.BasicConstraintsValid,
  538. IsCA: precert.IsCA,
  539. MaxPathLen: precert.MaxPathLen,
  540. MaxPathLenZero: precert.MaxPathLenZero,
  541. PermittedDNSDomainsCritical: precert.PermittedDNSDomainsCritical,
  542. }
  543. if len(precert.Extensions) > 0 {
  544. tbsCert.ExtraExtensions = make([]pkix.Extension, len(precert.Extensions))
  545. copy(tbsCert.ExtraExtensions, precert.Extensions)
  546. }
  547. // Remove the poison extension from ExtraExtensions
  548. tbsCert.ExtraExtensions = append(tbsCert.ExtraExtensions[:poisonIndex], tbsCert.ExtraExtensions[poisonIndex+1:]...)
  549. // Insert the SCT list extension
  550. tbsCert.ExtraExtensions = append(tbsCert.ExtraExtensions, sctExt)
  551. // Sign the tbsCert. Linting is always disabled because there is no way for
  552. // this API to know the correct lint settings to use because there is no
  553. // reference to the signing profile of the precert available.
  554. return s.sign(&tbsCert, 0, nil)
  555. }
  556. // Info return a populated info.Resp struct or an error.
  557. func (s *Signer) Info(req info.Req) (resp *info.Resp, err error) {
  558. cert, err := s.Certificate(req.Label, req.Profile)
  559. if err != nil {
  560. return
  561. }
  562. profile, err := signer.Profile(s, req.Profile)
  563. if err != nil {
  564. return
  565. }
  566. resp = new(info.Resp)
  567. if cert.Raw != nil {
  568. resp.Certificate = string(bytes.TrimSpace(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})))
  569. }
  570. resp.Usage = profile.Usage
  571. resp.ExpiryString = profile.ExpiryString
  572. return
  573. }
  574. // SigAlgo returns the RSA signer's signature algorithm.
  575. func (s *Signer) SigAlgo() x509.SignatureAlgorithm {
  576. return s.sigAlgo
  577. }
  578. // Certificate returns the signer's certificate.
  579. func (s *Signer) Certificate(label, profile string) (*x509.Certificate, error) {
  580. cert := *s.ca
  581. return &cert, nil
  582. }
  583. // SetPolicy sets the signer's signature policy.
  584. func (s *Signer) SetPolicy(policy *config.Signing) {
  585. s.policy = policy
  586. }
  587. // SetDBAccessor sets the signers' cert db accessor
  588. func (s *Signer) SetDBAccessor(dba certdb.Accessor) {
  589. s.dbAccessor = dba
  590. }
  591. // GetDBAccessor returns the signers' cert db accessor
  592. func (s *Signer) GetDBAccessor() certdb.Accessor {
  593. return s.dbAccessor
  594. }
  595. // SetReqModifier does nothing for local
  596. func (s *Signer) SetReqModifier(func(*http.Request, []byte)) {
  597. // noop
  598. }
  599. // Policy returns the signer's policy.
  600. func (s *Signer) Policy() *config.Signing {
  601. return s.policy
  602. }