local.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. // Package local implements certificate signature functionality for CFSSL.
  2. package local
  3. import (
  4. "bytes"
  5. "crypto"
  6. "crypto/rand"
  7. "crypto/x509"
  8. "crypto/x509/pkix"
  9. "encoding/asn1"
  10. "encoding/hex"
  11. "encoding/pem"
  12. "errors"
  13. "io"
  14. "math/big"
  15. "net"
  16. "net/http"
  17. "net/mail"
  18. "os"
  19. "github.com/cloudflare/cfssl/certdb"
  20. "github.com/cloudflare/cfssl/config"
  21. cferr "github.com/cloudflare/cfssl/errors"
  22. "github.com/cloudflare/cfssl/helpers"
  23. "github.com/cloudflare/cfssl/info"
  24. "github.com/cloudflare/cfssl/log"
  25. "github.com/cloudflare/cfssl/signer"
  26. "github.com/google/certificate-transparency-go"
  27. "github.com/google/certificate-transparency-go/client"
  28. "github.com/google/certificate-transparency-go/jsonclient"
  29. "golang.org/x/net/context"
  30. )
  31. // Signer contains a signer that uses the standard library to
  32. // support both ECDSA and RSA CA keys.
  33. type Signer struct {
  34. ca *x509.Certificate
  35. priv crypto.Signer
  36. policy *config.Signing
  37. sigAlgo x509.SignatureAlgorithm
  38. dbAccessor certdb.Accessor
  39. }
  40. // NewSigner creates a new Signer directly from a
  41. // private key and certificate, with optional policy.
  42. func NewSigner(priv crypto.Signer, cert *x509.Certificate, sigAlgo x509.SignatureAlgorithm, policy *config.Signing) (*Signer, error) {
  43. if policy == nil {
  44. policy = &config.Signing{
  45. Profiles: map[string]*config.SigningProfile{},
  46. Default: config.DefaultConfig()}
  47. }
  48. if !policy.Valid() {
  49. return nil, cferr.New(cferr.PolicyError, cferr.InvalidPolicy)
  50. }
  51. return &Signer{
  52. ca: cert,
  53. priv: priv,
  54. sigAlgo: sigAlgo,
  55. policy: policy,
  56. }, nil
  57. }
  58. // NewSignerFromFile generates a new local signer from a caFile
  59. // and a caKey file, both PEM encoded.
  60. func NewSignerFromFile(caFile, caKeyFile string, policy *config.Signing) (*Signer, error) {
  61. log.Debug("Loading CA: ", caFile)
  62. ca, err := helpers.ReadBytes(caFile)
  63. if err != nil {
  64. return nil, err
  65. }
  66. log.Debug("Loading CA key: ", caKeyFile)
  67. cakey, err := helpers.ReadBytes(caKeyFile)
  68. if err != nil {
  69. return nil, cferr.Wrap(cferr.CertificateError, cferr.ReadFailed, err)
  70. }
  71. parsedCa, err := helpers.ParseCertificatePEM(ca)
  72. if err != nil {
  73. return nil, err
  74. }
  75. strPassword := os.Getenv("CFSSL_CA_PK_PASSWORD")
  76. password := []byte(strPassword)
  77. if strPassword == "" {
  78. password = nil
  79. }
  80. priv, err := helpers.ParsePrivateKeyPEMWithPassword(cakey, password)
  81. if err != nil {
  82. log.Debug("Malformed private key %v", err)
  83. return nil, err
  84. }
  85. return NewSigner(priv, parsedCa, signer.DefaultSigAlgo(priv), policy)
  86. }
  87. func (s *Signer) sign(template *x509.Certificate) (cert []byte, err error) {
  88. var initRoot bool
  89. if s.ca == nil {
  90. if !template.IsCA {
  91. err = cferr.New(cferr.PolicyError, cferr.InvalidRequest)
  92. return
  93. }
  94. template.DNSNames = nil
  95. template.EmailAddresses = nil
  96. s.ca = template
  97. initRoot = true
  98. }
  99. derBytes, err := x509.CreateCertificate(rand.Reader, template, s.ca, template.PublicKey, s.priv)
  100. if err != nil {
  101. return nil, cferr.Wrap(cferr.CertificateError, cferr.Unknown, err)
  102. }
  103. if initRoot {
  104. s.ca, err = x509.ParseCertificate(derBytes)
  105. if err != nil {
  106. return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
  107. }
  108. }
  109. cert = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  110. log.Infof("signed certificate with serial number %d", template.SerialNumber)
  111. return
  112. }
  113. // replaceSliceIfEmpty replaces the contents of replaced with newContents if
  114. // the slice referenced by replaced is empty
  115. func replaceSliceIfEmpty(replaced, newContents *[]string) {
  116. if len(*replaced) == 0 {
  117. *replaced = *newContents
  118. }
  119. }
  120. // PopulateSubjectFromCSR has functionality similar to Name, except
  121. // it fills the fields of the resulting pkix.Name with req's if the
  122. // subject's corresponding fields are empty
  123. func PopulateSubjectFromCSR(s *signer.Subject, req pkix.Name) pkix.Name {
  124. // if no subject, use req
  125. if s == nil {
  126. return req
  127. }
  128. name := s.Name()
  129. if name.CommonName == "" {
  130. name.CommonName = req.CommonName
  131. }
  132. replaceSliceIfEmpty(&name.Country, &req.Country)
  133. replaceSliceIfEmpty(&name.Province, &req.Province)
  134. replaceSliceIfEmpty(&name.Locality, &req.Locality)
  135. replaceSliceIfEmpty(&name.Organization, &req.Organization)
  136. replaceSliceIfEmpty(&name.OrganizationalUnit, &req.OrganizationalUnit)
  137. if name.SerialNumber == "" {
  138. name.SerialNumber = req.SerialNumber
  139. }
  140. return name
  141. }
  142. // OverrideHosts fills template's IPAddresses, EmailAddresses, and DNSNames with the
  143. // content of hosts, if it is not nil.
  144. func OverrideHosts(template *x509.Certificate, hosts []string) {
  145. if hosts != nil {
  146. template.IPAddresses = []net.IP{}
  147. template.EmailAddresses = []string{}
  148. template.DNSNames = []string{}
  149. }
  150. for i := range hosts {
  151. if ip := net.ParseIP(hosts[i]); ip != nil {
  152. template.IPAddresses = append(template.IPAddresses, ip)
  153. } else if email, err := mail.ParseAddress(hosts[i]); err == nil && email != nil {
  154. template.EmailAddresses = append(template.EmailAddresses, email.Address)
  155. } else {
  156. template.DNSNames = append(template.DNSNames, hosts[i])
  157. }
  158. }
  159. }
  160. // Sign signs a new certificate based on the PEM-encoded client
  161. // certificate or certificate request with the signing profile,
  162. // specified by profileName.
  163. func (s *Signer) Sign(req signer.SignRequest) (cert []byte, err error) {
  164. profile, err := signer.Profile(s, req.Profile)
  165. if err != nil {
  166. return
  167. }
  168. block, _ := pem.Decode([]byte(req.Request))
  169. if block == nil {
  170. return nil, cferr.New(cferr.CSRError, cferr.DecodeFailed)
  171. }
  172. if block.Type != "NEW CERTIFICATE REQUEST" && block.Type != "CERTIFICATE REQUEST" {
  173. return nil, cferr.Wrap(cferr.CSRError,
  174. cferr.BadRequest, errors.New("not a csr"))
  175. }
  176. csrTemplate, err := signer.ParseCertificateRequest(s, block.Bytes)
  177. if err != nil {
  178. return nil, err
  179. }
  180. // Copy out only the fields from the CSR authorized by policy.
  181. safeTemplate := x509.Certificate{}
  182. // If the profile contains no explicit whitelist, assume that all fields
  183. // should be copied from the CSR.
  184. if profile.CSRWhitelist == nil {
  185. safeTemplate = *csrTemplate
  186. } else {
  187. if profile.CSRWhitelist.Subject {
  188. safeTemplate.Subject = csrTemplate.Subject
  189. }
  190. if profile.CSRWhitelist.PublicKeyAlgorithm {
  191. safeTemplate.PublicKeyAlgorithm = csrTemplate.PublicKeyAlgorithm
  192. }
  193. if profile.CSRWhitelist.PublicKey {
  194. safeTemplate.PublicKey = csrTemplate.PublicKey
  195. }
  196. if profile.CSRWhitelist.SignatureAlgorithm {
  197. safeTemplate.SignatureAlgorithm = csrTemplate.SignatureAlgorithm
  198. }
  199. if profile.CSRWhitelist.DNSNames {
  200. safeTemplate.DNSNames = csrTemplate.DNSNames
  201. }
  202. if profile.CSRWhitelist.IPAddresses {
  203. safeTemplate.IPAddresses = csrTemplate.IPAddresses
  204. }
  205. if profile.CSRWhitelist.EmailAddresses {
  206. safeTemplate.EmailAddresses = csrTemplate.EmailAddresses
  207. }
  208. }
  209. if req.CRLOverride != "" {
  210. safeTemplate.CRLDistributionPoints = []string{req.CRLOverride}
  211. }
  212. if safeTemplate.IsCA {
  213. if !profile.CAConstraint.IsCA {
  214. log.Error("local signer policy disallows issuing CA certificate")
  215. return nil, cferr.New(cferr.PolicyError, cferr.InvalidRequest)
  216. }
  217. if s.ca != nil && s.ca.MaxPathLen > 0 {
  218. if safeTemplate.MaxPathLen >= s.ca.MaxPathLen {
  219. log.Error("local signer certificate disallows CA MaxPathLen extending")
  220. // do not sign a cert with pathlen > current
  221. return nil, cferr.New(cferr.PolicyError, cferr.InvalidRequest)
  222. }
  223. } else if s.ca != nil && s.ca.MaxPathLen == 0 && s.ca.MaxPathLenZero {
  224. log.Error("local signer certificate disallows issuing CA certificate")
  225. // signer has pathlen of 0, do not sign more intermediate CAs
  226. return nil, cferr.New(cferr.PolicyError, cferr.InvalidRequest)
  227. }
  228. }
  229. OverrideHosts(&safeTemplate, req.Hosts)
  230. safeTemplate.Subject = PopulateSubjectFromCSR(req.Subject, safeTemplate.Subject)
  231. // If there is a whitelist, ensure that both the Common Name and SAN DNSNames match
  232. if profile.NameWhitelist != nil {
  233. if safeTemplate.Subject.CommonName != "" {
  234. if profile.NameWhitelist.Find([]byte(safeTemplate.Subject.CommonName)) == nil {
  235. return nil, cferr.New(cferr.PolicyError, cferr.UnmatchedWhitelist)
  236. }
  237. }
  238. for _, name := range safeTemplate.DNSNames {
  239. if profile.NameWhitelist.Find([]byte(name)) == nil {
  240. return nil, cferr.New(cferr.PolicyError, cferr.UnmatchedWhitelist)
  241. }
  242. }
  243. for _, name := range safeTemplate.EmailAddresses {
  244. if profile.NameWhitelist.Find([]byte(name)) == nil {
  245. return nil, cferr.New(cferr.PolicyError, cferr.UnmatchedWhitelist)
  246. }
  247. }
  248. }
  249. if profile.ClientProvidesSerialNumbers {
  250. if req.Serial == nil {
  251. return nil, cferr.New(cferr.CertificateError, cferr.MissingSerial)
  252. }
  253. safeTemplate.SerialNumber = req.Serial
  254. } else {
  255. // RFC 5280 4.1.2.2:
  256. // Certificate users MUST be able to handle serialNumber
  257. // values up to 20 octets. Conforming CAs MUST NOT use
  258. // serialNumber values longer than 20 octets.
  259. //
  260. // If CFSSL is providing the serial numbers, it makes
  261. // sense to use the max supported size.
  262. serialNumber := make([]byte, 20)
  263. _, err = io.ReadFull(rand.Reader, serialNumber)
  264. if err != nil {
  265. return nil, cferr.Wrap(cferr.CertificateError, cferr.Unknown, err)
  266. }
  267. // SetBytes interprets buf as the bytes of a big-endian
  268. // unsigned integer. The leading byte should be masked
  269. // off to ensure it isn't negative.
  270. serialNumber[0] &= 0x7F
  271. safeTemplate.SerialNumber = new(big.Int).SetBytes(serialNumber)
  272. }
  273. if len(req.Extensions) > 0 {
  274. for _, ext := range req.Extensions {
  275. oid := asn1.ObjectIdentifier(ext.ID)
  276. if !profile.ExtensionWhitelist[oid.String()] {
  277. return nil, cferr.New(cferr.CertificateError, cferr.InvalidRequest)
  278. }
  279. rawValue, err := hex.DecodeString(ext.Value)
  280. if err != nil {
  281. return nil, cferr.Wrap(cferr.CertificateError, cferr.InvalidRequest, err)
  282. }
  283. safeTemplate.ExtraExtensions = append(safeTemplate.ExtraExtensions, pkix.Extension{
  284. Id: oid,
  285. Critical: ext.Critical,
  286. Value: rawValue,
  287. })
  288. }
  289. }
  290. var distPoints = safeTemplate.CRLDistributionPoints
  291. err = signer.FillTemplate(&safeTemplate, s.policy.Default, profile, req.NotBefore, req.NotAfter)
  292. if err != nil {
  293. return nil, err
  294. }
  295. if distPoints != nil && len(distPoints) > 0 {
  296. safeTemplate.CRLDistributionPoints = distPoints
  297. }
  298. var certTBS = safeTemplate
  299. if len(profile.CTLogServers) > 0 || req.ReturnPrecert {
  300. // Add a poison extension which prevents validation
  301. var poisonExtension = pkix.Extension{Id: signer.CTPoisonOID, Critical: true, Value: []byte{0x05, 0x00}}
  302. var poisonedPreCert = certTBS
  303. poisonedPreCert.ExtraExtensions = append(safeTemplate.ExtraExtensions, poisonExtension)
  304. cert, err = s.sign(&poisonedPreCert)
  305. if err != nil {
  306. return
  307. }
  308. if req.ReturnPrecert {
  309. return cert, nil
  310. }
  311. derCert, _ := pem.Decode(cert)
  312. prechain := []ct.ASN1Cert{{Data: derCert.Bytes}, {Data: s.ca.Raw}}
  313. var sctList []ct.SignedCertificateTimestamp
  314. for _, server := range profile.CTLogServers {
  315. log.Infof("submitting poisoned precertificate to %s", server)
  316. ctclient, err := client.New(server, nil, jsonclient.Options{})
  317. if err != nil {
  318. return nil, cferr.Wrap(cferr.CTError, cferr.PrecertSubmissionFailed, err)
  319. }
  320. var resp *ct.SignedCertificateTimestamp
  321. ctx := context.Background()
  322. resp, err = ctclient.AddPreChain(ctx, prechain)
  323. if err != nil {
  324. return nil, cferr.Wrap(cferr.CTError, cferr.PrecertSubmissionFailed, err)
  325. }
  326. sctList = append(sctList, *resp)
  327. }
  328. var serializedSCTList []byte
  329. serializedSCTList, err = helpers.SerializeSCTList(sctList)
  330. if err != nil {
  331. return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, err)
  332. }
  333. // Serialize again as an octet string before embedding
  334. serializedSCTList, err = asn1.Marshal(serializedSCTList)
  335. if err != nil {
  336. return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, err)
  337. }
  338. var SCTListExtension = pkix.Extension{Id: signer.SCTListOID, Critical: false, Value: serializedSCTList}
  339. certTBS.ExtraExtensions = append(certTBS.ExtraExtensions, SCTListExtension)
  340. }
  341. var signedCert []byte
  342. signedCert, err = s.sign(&certTBS)
  343. if err != nil {
  344. return nil, err
  345. }
  346. // Get the AKI from signedCert. This is required to support Go 1.9+.
  347. // In prior versions of Go, x509.CreateCertificate updated the
  348. // AuthorityKeyId of certTBS.
  349. parsedCert, _ := helpers.ParseCertificatePEM(signedCert)
  350. if s.dbAccessor != nil {
  351. var certRecord = certdb.CertificateRecord{
  352. Serial: certTBS.SerialNumber.String(),
  353. // this relies on the specific behavior of x509.CreateCertificate
  354. // which sets the AuthorityKeyId from the signer's SubjectKeyId
  355. AKI: hex.EncodeToString(parsedCert.AuthorityKeyId),
  356. CALabel: req.Label,
  357. Status: "good",
  358. Expiry: certTBS.NotAfter,
  359. PEM: string(signedCert),
  360. }
  361. err = s.dbAccessor.InsertCertificate(certRecord)
  362. if err != nil {
  363. return nil, err
  364. }
  365. log.Debug("saved certificate with serial number ", certTBS.SerialNumber)
  366. }
  367. return signedCert, nil
  368. }
  369. // SignFromPrecert creates and signs a certificate from an existing precertificate
  370. // that was previously signed by Signer.ca and inserts the provided SCTs into the
  371. // new certificate. The resulting certificate will be a exact copy of the precert
  372. // except for the removal of the poison extension and the addition of the SCT list
  373. // extension. SignFromPrecert does not verify that the contents of the certificate
  374. // still match the signing profile of the signer, it only requires that the precert
  375. // was previously signed by the Signers CA.
  376. func (s *Signer) SignFromPrecert(precert *x509.Certificate, scts []ct.SignedCertificateTimestamp) ([]byte, error) {
  377. // Verify certificate was signed by s.ca
  378. if err := precert.CheckSignatureFrom(s.ca); err != nil {
  379. return nil, err
  380. }
  381. // Verify certificate is a precert
  382. isPrecert := false
  383. poisonIndex := 0
  384. for i, ext := range precert.Extensions {
  385. if ext.Id.Equal(signer.CTPoisonOID) {
  386. if !ext.Critical {
  387. return nil, cferr.New(cferr.CTError, cferr.PrecertInvalidPoison)
  388. }
  389. // Check extension contains ASN.1 NULL
  390. if bytes.Compare(ext.Value, []byte{0x05, 0x00}) != 0 {
  391. return nil, cferr.New(cferr.CTError, cferr.PrecertInvalidPoison)
  392. }
  393. isPrecert = true
  394. poisonIndex = i
  395. break
  396. }
  397. }
  398. if !isPrecert {
  399. return nil, cferr.New(cferr.CTError, cferr.PrecertMissingPoison)
  400. }
  401. // Serialize SCTs into list format and create extension
  402. serializedList, err := helpers.SerializeSCTList(scts)
  403. if err != nil {
  404. return nil, err
  405. }
  406. // Serialize again as an octet string before embedding
  407. serializedList, err = asn1.Marshal(serializedList)
  408. if err != nil {
  409. return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, err)
  410. }
  411. sctExt := pkix.Extension{Id: signer.SCTListOID, Critical: false, Value: serializedList}
  412. // Create the new tbsCert from precert. Do explicit copies of any slices so that we don't
  413. // use memory that may be altered by us or the caller at a later stage.
  414. tbsCert := x509.Certificate{
  415. SignatureAlgorithm: precert.SignatureAlgorithm,
  416. PublicKeyAlgorithm: precert.PublicKeyAlgorithm,
  417. PublicKey: precert.PublicKey,
  418. Version: precert.Version,
  419. SerialNumber: precert.SerialNumber,
  420. Issuer: precert.Issuer,
  421. Subject: precert.Subject,
  422. NotBefore: precert.NotBefore,
  423. NotAfter: precert.NotAfter,
  424. KeyUsage: precert.KeyUsage,
  425. BasicConstraintsValid: precert.BasicConstraintsValid,
  426. IsCA: precert.IsCA,
  427. MaxPathLen: precert.MaxPathLen,
  428. MaxPathLenZero: precert.MaxPathLenZero,
  429. PermittedDNSDomainsCritical: precert.PermittedDNSDomainsCritical,
  430. }
  431. if len(precert.Extensions) > 0 {
  432. tbsCert.ExtraExtensions = make([]pkix.Extension, len(precert.Extensions))
  433. copy(tbsCert.ExtraExtensions, precert.Extensions)
  434. }
  435. // Remove the poison extension from ExtraExtensions
  436. tbsCert.ExtraExtensions = append(tbsCert.ExtraExtensions[:poisonIndex], tbsCert.ExtraExtensions[poisonIndex+1:]...)
  437. // Insert the SCT list extension
  438. tbsCert.ExtraExtensions = append(tbsCert.ExtraExtensions, sctExt)
  439. // Sign the tbsCert
  440. return s.sign(&tbsCert)
  441. }
  442. // Info return a populated info.Resp struct or an error.
  443. func (s *Signer) Info(req info.Req) (resp *info.Resp, err error) {
  444. cert, err := s.Certificate(req.Label, req.Profile)
  445. if err != nil {
  446. return
  447. }
  448. profile, err := signer.Profile(s, req.Profile)
  449. if err != nil {
  450. return
  451. }
  452. resp = new(info.Resp)
  453. if cert.Raw != nil {
  454. resp.Certificate = string(bytes.TrimSpace(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})))
  455. }
  456. resp.Usage = profile.Usage
  457. resp.ExpiryString = profile.ExpiryString
  458. return
  459. }
  460. // SigAlgo returns the RSA signer's signature algorithm.
  461. func (s *Signer) SigAlgo() x509.SignatureAlgorithm {
  462. return s.sigAlgo
  463. }
  464. // Certificate returns the signer's certificate.
  465. func (s *Signer) Certificate(label, profile string) (*x509.Certificate, error) {
  466. cert := *s.ca
  467. return &cert, nil
  468. }
  469. // SetPolicy sets the signer's signature policy.
  470. func (s *Signer) SetPolicy(policy *config.Signing) {
  471. s.policy = policy
  472. }
  473. // SetDBAccessor sets the signers' cert db accessor
  474. func (s *Signer) SetDBAccessor(dba certdb.Accessor) {
  475. s.dbAccessor = dba
  476. }
  477. // GetDBAccessor returns the signers' cert db accessor
  478. func (s *Signer) GetDBAccessor() certdb.Accessor {
  479. return s.dbAccessor
  480. }
  481. // SetReqModifier does nothing for local
  482. func (s *Signer) SetReqModifier(func(*http.Request, []byte)) {
  483. // noop
  484. }
  485. // Policy returns the signer's policy.
  486. func (s *Signer) Policy() *config.Signing {
  487. return s.policy
  488. }