| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package x509tools |
| 18 | |
| 19 | import ( |
| 20 | "bytes" |
| 21 | "crypto" |
| 22 | "crypto/ecdsa" |
| 23 | "crypto/ed25519" |
| 24 | "crypto/rand" |
| 25 | "crypto/rsa" |
| 26 | "crypto/x509" |
| 27 | "crypto/x509/pkix" |
| 28 | "encoding/pem" |
| 29 | "errors" |
| 30 | "fmt" |
| 31 | "io" |
| 32 | "math/big" |
| 33 | "os" |
| 34 | "strings" |
| 35 | "time" |
| 36 | |
| 37 | "github.com/spf13/cobra" |
| 38 | "golang.org/x/term" |
| 39 | ) |
| 40 | |
| 41 | var ( |
| 42 | ArgCountry string |
| 43 | ArgOrganization string |
| 44 | ArgOrganizationalUnit string |
| 45 | ArgLocality string |
| 46 | ArgProvince string |
| 47 | ArgCommonName string |
| 48 | ArgDNSNames string |
| 49 | ArgEmailNames string |
| 50 | ArgKeyUsage string |
| 51 | ArgExpireDays uint |
| 52 | ArgCertAuthority bool |
| 53 | ArgSerial string |
| 54 | ArgInteractive bool |
| 55 | ArgRSAPSS bool |
| 56 | ) |
| 57 | |
| 58 | // Add flags associated with X509 requests to the given command |
| 59 | func AddRequestFlags(cmd *cobra.Command) { |
| 60 | cmd.Flags().StringVar(&ArgCountry, "countryName", "", "Subject name") |
| 61 | cmd.Flags().StringVar(&ArgProvince, "stateOrProvinceName", "", "Subject name") |
| 62 | cmd.Flags().StringVar(&ArgLocality, "localityName", "", "Subject name") |
| 63 | cmd.Flags().StringVar(&ArgOrganization, "organizationName", "", "Subject name") |
| 64 | cmd.Flags().StringVar(&ArgOrganizationalUnit, "organizationalUnitName", "", "Subject name") |
| 65 | cmd.Flags().StringVarP(&ArgCommonName, "commonName", "n", "", "Subject commonName") |
| 66 | cmd.Flags().StringVar(&ArgDNSNames, "alternate-dns", "", "DNS subject alternate name (comma or space separated)") |
| 67 | cmd.Flags().StringVar(&ArgEmailNames, "alternate-email", "", "Email subject alternate name (comma or space separated)") |
| 68 | cmd.Flags().BoolVarP(&ArgInteractive, "interactive", "i", false, "Prompt before signing certificate") |
| 69 | cmd.Flags().BoolVar(&ArgRSAPSS, "rsa-pss", false, "Use RSA-PSS signature") |
| 70 | } |
| 71 | |
| 72 | // Add flags associated with X509 certificate creation to the given command |
| 73 | func AddCertFlags(cmd *cobra.Command) { |
| 74 | AddRequestFlags(cmd) |
| 75 | cmd.Flags().BoolVar(&ArgCertAuthority, "cert-authority", false, "If this certificate is an authority") |
| 76 | cmd.Flags().StringVarP(&ArgKeyUsage, "key-usage", "U", "", "Key usage, one of: serverAuth clientAuth codeSigning emailProtection keyCertSign") |
| 77 | cmd.Flags().UintVarP(&ArgExpireDays, "expire-days", "e", 36523, "Number of days before certificate expires") |
| 78 | cmd.Flags().StringVar(&ArgSerial, "serial", "", "Set the serial number of the certificate. Random if not specified.") |
| 79 | } |
| 80 | |
| 81 | // Split a space- and/or comma-seperated string |
| 82 | func splitAndTrim(s string) []string { |
| 83 | if s == "" { |
| 84 | return nil |
| 85 | } |
| 86 | s = strings.ReplaceAll(s, ",", " ") |
| 87 | pieces := strings.Split(s, " ") |
| 88 | ret := make([]string, 0, len(pieces)) |
| 89 | for _, p := range pieces { |
| 90 | p = strings.Trim(p, " ") |
| 91 | if p != "" { |
| 92 | ret = append(ret, p) |
| 93 | } |
| 94 | } |
| 95 | return ret |
| 96 | } |
| 97 | |
| 98 | // Build a subject name from command-line arguments |
| 99 | func subjName() (name pkix.Name) { |
| 100 | if ArgCountry != "" { |
| 101 | name.Country = []string{ArgCountry} |
| 102 | } |
| 103 | if ArgProvince != "" { |
| 104 | name.Province = []string{ArgProvince} |
| 105 | } |
| 106 | if ArgLocality != "" { |
| 107 | name.Locality = []string{ArgLocality} |
| 108 | } |
| 109 | if ArgOrganization != "" { |
| 110 | name.Organization = []string{ArgOrganization} |
| 111 | } |
| 112 | if ArgOrganizationalUnit != "" { |
| 113 | name.OrganizationalUnit = []string{ArgOrganizationalUnit} |
| 114 | } |
| 115 | name.CommonName = ArgCommonName |
| 116 | return |
| 117 | } |
| 118 | |
| 119 | // Set both basic and extended key usage |
| 120 | func setUsage(template *x509.Certificate) error { |
| 121 | usage := x509.KeyUsageDigitalSignature |
| 122 | var extended []x509.ExtKeyUsage |
| 123 | switch strings.ToLower(ArgKeyUsage) { |
| 124 | case "serverauth": |
| 125 | usage |= x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement |
| 126 | extended = append(extended, x509.ExtKeyUsageServerAuth) |
| 127 | case "clientauth": |
| 128 | usage |= x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement |
| 129 | extended = append(extended, x509.ExtKeyUsageClientAuth) |
| 130 | case "codesigning": |
| 131 | extended = append(extended, x509.ExtKeyUsageCodeSigning) |
| 132 | case "emailprotection": |
| 133 | usage |= x509.KeyUsageContentCommitment | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement |
| 134 | extended = append(extended, x509.ExtKeyUsageEmailProtection) |
| 135 | case "keycertsign": |
| 136 | usage |= x509.KeyUsageCertSign | x509.KeyUsageCRLSign |
| 137 | case "": |
| 138 | return nil |
| 139 | default: |
| 140 | return errors.New("invalid key-usage") |
| 141 | } |
| 142 | template.KeyUsage = usage |
| 143 | template.ExtKeyUsage = extended |
| 144 | return nil |
| 145 | } |
| 146 | |
| 147 | func fillCertFields(template *x509.Certificate, subjectPub, issuerPub crypto.PublicKey) error { |
| 148 | if ArgSerial != "" { |
| 149 | serial, ok := new(big.Int).SetString(ArgSerial, 0) |
| 150 | if !ok { |
| 151 | return errors.New("invalid serial number, must be decimal or hexadecimal format") |
| 152 | } |
| 153 | template.SerialNumber = serial |
| 154 | } else if template.SerialNumber == nil { |
| 155 | template.SerialNumber = MakeSerial() |
| 156 | if template.SerialNumber == nil { |
| 157 | return errors.New("Failed to generate a serial number") |
| 158 | } |
| 159 | } |
| 160 | if ArgCommonName != "" { |
| 161 | template.Subject = subjName() |
| 162 | } |
| 163 | if ArgDNSNames != "" { |
| 164 | template.DNSNames = splitAndTrim(ArgDNSNames) |
| 165 | } |
| 166 | if ArgEmailNames != "" { |
| 167 | template.EmailAddresses = splitAndTrim(ArgEmailNames) |
| 168 | } |
| 169 | template.SignatureAlgorithm = X509SignatureAlgorithm(issuerPub) |
| 170 | template.NotBefore = time.Now().Add(time.Hour * -24) |
| 171 | template.NotAfter = time.Now().Add(time.Hour * 24 * time.Duration(ArgExpireDays)) |
| 172 | template.IsCA = ArgCertAuthority |
| 173 | template.BasicConstraintsValid = true |
| 174 | ski, err := SubjectKeyID(subjectPub) |
| 175 | if err != nil { |
| 176 | return err |
| 177 | } |
| 178 | template.SubjectKeyId = ski |
| 179 | return setUsage(template) |
| 180 | } |
| 181 | |
| 182 | func toPemString(der []byte, pemType string) string { |
| 183 | block := &pem.Block{Type: pemType, Bytes: der} |
| 184 | return string(pem.EncodeToMemory(block)) |
| 185 | } |
| 186 | |
| 187 | // Make a X509 certificate request using command-line arguments and return the |
| 188 | // PEM string |
| 189 | func MakeRequest(rand io.Reader, key crypto.Signer) (string, error) { |
| 190 | var template x509.CertificateRequest |
| 191 | template.Subject = subjName() |
| 192 | template.DNSNames = splitAndTrim(ArgDNSNames) |
| 193 | template.EmailAddresses = splitAndTrim(ArgEmailNames) |
| 194 | template.SignatureAlgorithm = X509SignatureAlgorithm(key.Public()) |
| 195 | csr, err := x509.CreateCertificateRequest(rand, &template, key) |
| 196 | if err != nil { |
| 197 | return "", err |
| 198 | } |
| 199 | return toPemString(csr, "CERTIFICATE REQUEST"), nil |
| 200 | } |
| 201 | |
| 202 | // Make a self-signed X509 certificate using command-line arguments and return |
| 203 | // the PEM string |
| 204 | func MakeCertificate(rand io.Reader, key crypto.Signer) (string, error) { |
| 205 | var template x509.Certificate |
| 206 | if err := fillCertFields(&template, key.Public(), key.Public()); err != nil { |
| 207 | return "", err |
| 208 | } |
| 209 | template.Issuer = template.Subject |
| 210 | cert, err := confirmAndCreate(&template, &template, key.Public(), key) |
| 211 | if err != nil { |
| 212 | return "", err |
| 213 | } |
| 214 | return toPemString(cert, "CERTIFICATE"), nil |
| 215 | } |
| 216 | |
| 217 | // SignCSR takes a PKCS#10 signing request in PEM or DER format as input and |
| 218 | // produces a signed certificate in PEM format. Any command-line flags set will |
| 219 | // override the CSR contents. |
| 220 | func SignCSR(csrBytes []byte, rand io.Reader, key crypto.Signer, cacert *x509.Certificate, copyExtensions bool) (string, error) { |
| 221 | // parse and validate CSR |
| 222 | csrBytes, err := parseMaybePEM(csrBytes, "CERTIFICATE REQUEST") |
| 223 | if err != nil { |
| 224 | return "", err |
| 225 | } |
| 226 | csr, err := x509.ParseCertificateRequest(csrBytes) |
| 227 | if err != nil { |
| 228 | return "", fmt.Errorf("parsing CSR: %w", err) |
| 229 | } |
| 230 | if err := csr.CheckSignature(); err != nil { |
| 231 | return "", fmt.Errorf("validating CSR: %w", err) |
| 232 | } |
| 233 | // update fields |
| 234 | template := &x509.Certificate{Subject: csr.Subject} |
| 235 | if copyExtensions { |
| 236 | // drop CSR extensions that are overridden or merged with our args |
| 237 | for _, ex := range csr.Extensions { |
| 238 | switch { |
| 239 | case ArgCertAuthority && ex.Id.Equal(oidExtensionBasicConstraints): |
| 240 | // arg has set CA constraint |
| 241 | case ArgKeyUsage != "" && (ex.Id.Equal(oidExtensionKeyUsage) || ex.Id.Equal(oidExtensionExtendedKeyUsage)): |
| 242 | // arg has set key usage |
| 243 | case ex.Id.Equal(oidExtensionSubjectKeyId) || ex.Id.Equal(oidExtensionAuthorityKeyId): |
| 244 | // we always set this |
| 245 | case ex.Id.Equal(oidExtensionSubjectAltName): |
| 246 | // these are copied piecemeal below |
| 247 | default: |
| 248 | // copy the extension as-is |
| 249 | template.ExtraExtensions = append(template.ExtraExtensions, ex) |
| 250 | } |
| 251 | } |
| 252 | template.DNSNames = csr.DNSNames |
| 253 | template.EmailAddresses = csr.EmailAddresses |
| 254 | template.IPAddresses = csr.IPAddresses |
| 255 | template.URIs = csr.URIs |
| 256 | } |
| 257 | if err := fillCertFields(template, csr.PublicKey, key.Public()); err != nil { |
| 258 | return "", err |
| 259 | } |
| 260 | certDer, err := confirmAndCreate(template, cacert, csr.PublicKey, key) |
| 261 | if err != nil { |
| 262 | return "", err |
| 263 | } |
| 264 | return toPemString(certDer, "CERTIFICATE"), nil |
| 265 | } |
| 266 | |
| 267 | // CrossSign takes a certificate as input and re-signs it using the given key. |
| 268 | // Any command-line flags set will override the CSR contents. |
| 269 | func CrossSign(certBytes []byte, rand io.Reader, key crypto.Signer, cacert *x509.Certificate) (string, error) { |
| 270 | certBytes, err := parseMaybePEM(certBytes, "CERTIFICATE") |
| 271 | if err != nil { |
| 272 | return "", err |
| 273 | } |
| 274 | template, err := x509.ParseCertificate(certBytes) |
| 275 | if err != nil { |
| 276 | return "", fmt.Errorf("parsing certificate: %w", err) |
| 277 | } |
| 278 | if err := fillCertFields(template, template.PublicKey, key.Public()); err != nil { |
| 279 | return "", err |
| 280 | } |
| 281 | newCert, err := confirmAndCreate(template, cacert, template.PublicKey, key) |
| 282 | if err != nil { |
| 283 | return "", err |
| 284 | } |
| 285 | return toPemString(newCert, "CERTIFICATE"), nil |
| 286 | } |
| 287 | |
| 288 | func confirmAndCreate(template, parent *x509.Certificate, leafPub crypto.PublicKey, issuerPriv crypto.PrivateKey) ([]byte, error) { |
| 289 | if ArgInteractive { |
| 290 | origSigner, ok := issuerPriv.(crypto.Signer) |
| 291 | if !ok { |
| 292 | return nil, errors.New("private key must satisfy crypto.Signer") |
| 293 | } |
| 294 | ok, err := confirmCertificate(template, parent, leafPub, origSigner.Public()) |
| 295 | if err != nil { |
| 296 | return nil, fmt.Errorf("mocking cert for interactive confirmation: %w", err) |
| 297 | } else if !ok { |
| 298 | fmt.Fprintln(os.Stderr, "operation canceled") |
| 299 | os.Exit(2) |
| 300 | } |
| 301 | } |
| 302 | return x509.CreateCertificate(rand.Reader, template, parent, leafPub, issuerPriv) |
| 303 | } |
| 304 | |
| 305 | func confirmCertificate(template, parent *x509.Certificate, leafPub, origSigner crypto.PublicKey) (bool, error) { |
| 306 | // generate a key with the same parameters as the real signer |
| 307 | fakePriv, err := generateAlike(origSigner) |
| 308 | if err != nil { |
| 309 | return false, err |
| 310 | } |
| 311 | // mangle parent cert |
| 312 | fakeParent := new(x509.Certificate) |
| 313 | *fakeParent = *parent |
| 314 | fakeParent.PublicKey = fakePriv.Public() |
| 315 | // call CreateCertificate with a fake signer to get what the final cert will look like |
| 316 | der, err := x509.CreateCertificate(rand.Reader, template, fakeParent, leafPub, fakePriv) |
| 317 | if err != nil { |
| 318 | return false, err |
| 319 | } |
| 320 | cert, err := x509.ParseCertificate(der) |
| 321 | if err != nil { |
| 322 | return false, err |
| 323 | } |
| 324 | fmt.Fprintln(os.Stderr, "Signing certificate:") |
| 325 | fmt.Fprintln(os.Stderr) |
| 326 | FprintCertificate(os.Stderr, cert) |
| 327 | fmt.Fprintln(os.Stderr) |
| 328 | return promptYN("Sign this cert? [Y/n] "), nil |
| 329 | } |
| 330 | |
| 331 | func generateAlike(pub crypto.PublicKey) (crypto.Signer, error) { |
| 332 | // generate a dummy key of the same type as pub |
| 333 | switch pub := pub.(type) { |
| 334 | case *rsa.PublicKey: |
| 335 | return rsa.GenerateKey(rand.Reader, 1024) |
| 336 | case *ecdsa.PublicKey: |
| 337 | return ecdsa.GenerateKey(pub.Curve, rand.Reader) |
| 338 | case ed25519.PublicKey: |
| 339 | _, priv, err := ed25519.GenerateKey(rand.Reader) |
| 340 | return priv, err |
| 341 | default: |
| 342 | return nil, fmt.Errorf("unrecognized key type %T", pub) |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | func promptYN(prompt string) bool { |
| 347 | fmt.Fprint(os.Stderr, prompt) |
| 348 | if !term.IsTerminal(0) { |
| 349 | fmt.Fprintln(os.Stderr, "input is not a terminal, assuming true") |
| 350 | return true |
| 351 | } |
| 352 | state, err := term.MakeRaw(0) |
| 353 | if err == nil { |
| 354 | defer fmt.Fprintln(os.Stderr) |
| 355 | defer func() { _ = term.Restore(0, state) }() |
| 356 | } |
| 357 | var d [1]byte |
| 358 | if _, err := os.Stdin.Read(d[:]); err != nil { |
| 359 | return false |
| 360 | } |
| 361 | if d[0] == 'Y' || d[0] == 'y' { |
| 362 | return true |
| 363 | } |
| 364 | return false |
| 365 | } |
| 366 | |
| 367 | func parseMaybePEM(blob []byte, pemType string) ([]byte, error) { |
| 368 | if bytes.Contains(blob, []byte("-----BEGIN")) { |
| 369 | for { |
| 370 | var block *pem.Block |
| 371 | block, blob = pem.Decode(blob) |
| 372 | if block == nil { |
| 373 | break |
| 374 | } else if block.Type == pemType { |
| 375 | return block.Bytes, nil |
| 376 | } |
| 377 | } |
| 378 | } else if len(blob) > 0 && blob[0] == 0x30 { |
| 379 | return blob, nil |
| 380 | } |
| 381 | return nil, fmt.Errorf("expected a %s in PEM or DER format", strings.ToLower(pemType)) |
| 382 | } |