示例#1
0
文件: api.go 项目: denkhaus/lecert
func (p *Api) SignCSR(csrFile string) error {
	l := log.WithField("csr", csrFile)
	if !fileExists(csrFile) {
		return errors.Errorf("csr file %q does not exist", csrFile)
	}

	l.Debug("read sign request")
	data, err := ioutil.ReadFile(csrFile)
	if err != nil {
		return errors.Annotate(err, "read csr file")
	}

	b, _ := pem.Decode(data)
	var csr *x509.CertificateRequest
	if b == nil {
		csr, err = x509.ParseCertificateRequest(data)
	} else {
		csr, err = x509.ParseCertificateRequest(b.Bytes)
	}
	if err != nil {
		return errors.Annotate(err, "parse csr")
	}

	l = l.WithField("domain", csr.Subject.CommonName)
	certFile := filepath.Join(p.cnf.OutputDir, csr.Subject.CommonName+".crt.pem")
	if fileExists(certFile) {
		return errors.Errorf("cert already exists for %q", csr.Subject.CommonName)
	}

	l.Debug("fulfill sign request")
	cert, err := p.cli.FulfillCSR(csr)
	if err != nil {
		return errors.Annotate(err, "fulfil csr")
	}

	data = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
	if p.cnf.Chain {
		l.Debug("request chain data")
		data = append(data, p.cli.Chain()...)
	}

	l.Debug("write certificate")
	err = ioutil.WriteFile(certFile, data, 0600)
	if err != nil {
		return errors.Annotate(err, "write crt file")
	}

	l.Infoln("Sign csr successfull")
	return nil
}
func TestRejectValidityTooLong(t *testing.T) {
	testCtx := setup(t)
	ca, err := NewCertificateAuthorityImpl(
		testCtx.caConfig,
		testCtx.fc,
		testCtx.stats,
		testCtx.issuers,
		testCtx.keyPolicy)
	test.AssertNotError(t, err, "Failed to create CA")
	ca.Publisher = &mocks.Publisher{}
	ca.PA = testCtx.pa
	ca.SA = &mockSA{}

	// This time is a few minutes before the notAfter in testdata/ca_cert.pem
	future, err := time.Parse(time.RFC3339, "2025-02-10T00:30:00Z")

	test.AssertNotError(t, err, "Failed to parse time")
	testCtx.fc.Set(future)
	// Test that the CA rejects CSRs that would expire after the intermediate cert
	csr, _ := x509.ParseCertificateRequest(NoCNCSR)
	_, err = ca.IssueCertificate(ctx, *csr, 1)
	test.AssertError(t, err, "Cannot issue a certificate that expires after the intermediate certificate")
	_, ok := err.(core.InternalServerError)
	test.Assert(t, ok, "Incorrect error type returned")
}
func TestDeduplication(t *testing.T) {
	testCtx := setup(t)
	ca, err := NewCertificateAuthorityImpl(
		testCtx.caConfig,
		testCtx.fc,
		testCtx.stats,
		testCtx.issuers,
		testCtx.keyPolicy)
	test.AssertNotError(t, err, "Failed to create CA")
	ca.Publisher = &mocks.Publisher{}
	ca.PA = testCtx.pa
	ca.SA = &mockSA{}

	// Test that the CA collapses duplicate names
	csr, _ := x509.ParseCertificateRequest(DupeNameCSR)
	cert, err := ca.IssueCertificate(ctx, *csr, 1001)
	test.AssertNotError(t, err, "Failed to gracefully handle a CSR with duplicate names")

	parsedCert, err := x509.ParseCertificate(cert.DER)
	test.AssertNotError(t, err, "Error parsing certificate produced by CA")

	correctName := "a.not-example.com"
	correctNames := len(parsedCert.DNSNames) == 1 &&
		parsedCert.DNSNames[0] == correctName
	test.Assert(t, correctNames, "Incorrect set of names in deduplicated certificate")
}
func TestDeduplication(t *testing.T) {
	cadb, storageAuthority, caConfig := setup(t)
	ca, err := NewCertificateAuthorityImpl(cadb, caConfig, caCertFile)
	test.AssertNotError(t, err, "Failed to create CA")
	ca.SA = storageAuthority
	ca.MaxKeySize = 4096

	// Test that the CA collapses duplicate names
	csrDER, _ := hex.DecodeString(DupeNameCSRhex)
	csr, _ := x509.ParseCertificateRequest(csrDER)
	cert, err := ca.IssueCertificate(*csr, 1, FarFuture)
	test.AssertNotError(t, err, "Failed to gracefully handle a CSR with duplicate names")
	if err != nil {
		return
	}

	parsedCert, err := x509.ParseCertificate(cert.DER)
	test.AssertNotError(t, err, "Error parsing certificate produced by CA")
	if err != nil {
		return
	}

	correctName := "a.not-example.com"
	correctNames := len(parsedCert.DNSNames) == 1 &&
		parsedCert.DNSNames[0] == correctName &&
		parsedCert.Subject.CommonName == correctName
	test.Assert(t, correctNames, "Incorrect set of names in deduplicated certificate")
}
示例#5
0
func readCSRFile(filename string) (*x509.CertificateRequest, error) {
	bytes, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	raw := bytes

	// see if we can find a PEM-encoded CSR
	var p *pem.Block
	rest := bytes
	for {
		// decode a PEM block
		p, rest = pem.Decode(rest)

		// did we fail?
		if p == nil {
			break
		}

		// did we get a CSR?
		if p.Type == "CERTIFICATE REQUEST" {
			raw = p.Bytes
		}
	}

	// no PEM-encoded CSR
	// assume we were given a DER-encoded ASN.1 CSR
	// (if this assumption is wrong, parsing these bytes will fail)
	return x509.ParseCertificateRequest(raw)
}
func TestRevoke(t *testing.T) {
	ctx := setup(t)
	defer ctx.cleanUp()
	ca, err := NewCertificateAuthorityImpl(ctx.caDB, ctx.caConfig, caCertFile)
	test.AssertNotError(t, err, "Failed to create CA")
	if err != nil {
		return
	}
	ca.SA = ctx.sa
	ca.MaxKeySize = 4096

	csrDER, _ := hex.DecodeString(CNandSANCSRhex)
	csr, _ := x509.ParseCertificateRequest(csrDER)
	certObj, err := ca.IssueCertificate(*csr, ctx.reg.ID, FarFuture)
	test.AssertNotError(t, err, "Failed to sign certificate")
	if err != nil {
		return
	}
	cert, err := x509.ParseCertificate(certObj.DER)
	test.AssertNotError(t, err, "Certificate failed to parse")
	serialString := core.SerialToString(cert.SerialNumber)
	err = ca.RevokeCertificate(serialString, 0)
	test.AssertNotError(t, err, "Revocation failed")

	status, err := ctx.sa.GetCertificateStatus(serialString)
	test.AssertNotError(t, err, "Failed to get cert status")

	test.AssertEquals(t, status.Status, core.OCSPStatusRevoked)
	secondAgo := time.Now().Add(-time.Second)
	test.Assert(t, status.OCSPLastUpdated.After(secondAgo),
		fmt.Sprintf("OCSP LastUpdated was more than a second old: %v", status.OCSPLastUpdated))
}
func TestCapitalizedLetters(t *testing.T) {
	testCtx := setup(t)
	testCtx.caConfig.MaxNames = 3
	ca, err := NewCertificateAuthorityImpl(
		testCtx.caConfig,
		testCtx.fc,
		testCtx.stats,
		testCtx.issuers,
		testCtx.keyPolicy)
	ca.Publisher = &mocks.Publisher{}
	ca.PA = testCtx.pa
	ca.SA = &mockSA{}

	csr, _ := x509.ParseCertificateRequest(CapitalizedCSR)
	cert, err := ca.IssueCertificate(ctx, *csr, 1001)
	test.AssertNotError(t, err, "Failed to gracefully handle a CSR with capitalized names")

	parsedCert, err := x509.ParseCertificate(cert.DER)
	test.AssertNotError(t, err, "Error parsing certificate produced by CA")
	test.AssertEquals(t, "capitalizedletters.com", parsedCert.Subject.CommonName)
	sort.Strings(parsedCert.DNSNames)
	expected := []string{"capitalizedletters.com", "evenmorecaps.com", "morecaps.com"}
	test.AssertDeepEquals(t, expected, parsedCert.DNSNames)
	t.Logf("subject serial number %#v", parsedCert.Subject.SerialNumber)
}
func TestRevoke(t *testing.T) {
	cadb, storageAuthority, caConfig := setup(t)
	ca, err := NewCertificateAuthorityImpl(cadb, caConfig, caCertFile)
	test.AssertNotError(t, err, "Failed to create CA")
	if err != nil {
		return
	}
	ca.SA = storageAuthority
	ca.MaxKeySize = 4096

	csrDER, _ := hex.DecodeString(CNandSANCSRhex)
	csr, _ := x509.ParseCertificateRequest(csrDER)
	certObj, err := ca.IssueCertificate(*csr, 1, FarFuture)
	test.AssertNotError(t, err, "Failed to sign certificate")
	if err != nil {
		return
	}
	cert, err := x509.ParseCertificate(certObj.DER)
	test.AssertNotError(t, err, "Certificate failed to parse")
	serialString := core.SerialToString(cert.SerialNumber)
	err = ca.RevokeCertificate(serialString, 0)
	test.AssertNotError(t, err, "Revocation failed")

	status, err := storageAuthority.GetCertificateStatus(serialString)
	test.AssertNotError(t, err, "Failed to get cert status")

	test.AssertEquals(t, status.Status, core.OCSPStatusRevoked)
	test.Assert(t, time.Now().Sub(status.OCSPLastUpdated) > time.Second,
		fmt.Sprintf("OCSP LastUpdated was wrong: %v", status.OCSPLastUpdated))
}
示例#9
0
func computeSum(in []byte) (sum Sum, err error) {
	var data []byte
	p, _ := pem.Decode(in)
	if p == nil {
		err = errors.NewBadRequestString("not a CSR or certificate")
		return
	}

	switch p.Type {
	case "CERTIFICATE REQUEST":
		var req *x509.CertificateRequest
		req, err = x509.ParseCertificateRequest(p.Bytes)
		if err != nil {
			return
		}
		data = req.Raw
	case "CERTIFICATE":
		var cert *x509.Certificate
		cert, err = x509.ParseCertificate(p.Bytes)
		if err != nil {
			return
		}
		data = cert.Raw
	default:
		err = errors.NewBadRequestString("not a CSR or certificate")
		return
	}

	md5Sum := md5.Sum(data)
	sha1Sum := sha1.Sum(data)
	sum.MD5 = fmt.Sprintf("%X", md5Sum[:])
	sum.SHA1 = fmt.Sprintf("%X", sha1Sum[:])
	return
}
示例#10
0
文件: signer.go 项目: nathany/cfssl
// SignCSR submits a PKCS #10 certificate signing request to a CA for
// signing.
func (lca *CA) SignCSR(csrPEM []byte) ([]byte, error) {
	if lca == nil || lca.s == nil {
		return nil, errNotSetup
	}

	if lca.disabled {
		return nil, errDisabled
	}

	p, _ := pem.Decode(csrPEM)
	if p == nil || p.Type != "CERTIFICATE REQUEST" {
		return nil, errors.New("transport: invalid PEM-encoded certificate signing request")
	}

	csr, err := x509.ParseCertificateRequest(p.Bytes)
	if err != nil {
		return nil, err
	}

	hosts := make([]string, 0, len(csr.DNSNames)+len(csr.IPAddresses))
	copy(hosts, csr.DNSNames)

	for i := range csr.IPAddresses {
		hosts = append(hosts, csr.IPAddresses[i].String())
	}

	sreq := signer.SignRequest{
		Hosts:   hosts,
		Request: string(csrPEM),
		Profile: lca.Profile,
		Label:   lca.Label,
	}

	return lca.s.Sign(sreq)
}
示例#11
0
文件: signer.go 项目: mclem/cfssl
// ParseCertificateRequest takes an incoming certificate request and
// builds a certificate template from it.
func ParseCertificateRequest(s Signer, csrBytes []byte) (template *x509.Certificate, err error) {
	csr, err := x509.ParseCertificateRequest(csrBytes)
	if err != nil {
		err = cferr.Wrap(cferr.CSRError, cferr.ParseFailed, err)
		return
	}

	err = helpers.CheckSignature(csr, csr.SignatureAlgorithm, csr.RawTBSCertificateRequest, csr.Signature)
	if err != nil {
		err = cferr.Wrap(cferr.CSRError, cferr.KeyMismatch, err)
		return
	}

	template = &x509.Certificate{
		Subject:            csr.Subject,
		PublicKeyAlgorithm: csr.PublicKeyAlgorithm,
		PublicKey:          csr.PublicKey,
		SignatureAlgorithm: s.SigAlgo(),
		DNSNames:           csr.DNSNames,
		IPAddresses:        csr.IPAddresses,
		EmailAddresses:     csr.EmailAddresses,
	}

	return
}
示例#12
0
func TestDeduplication(t *testing.T) {
	ctx := setup(t)
	defer ctx.cleanUp()
	ca, err := NewCertificateAuthorityImpl(ctx.caDB, ctx.caConfig, ctx.fc, caCertFile)
	test.AssertNotError(t, err, "Failed to create CA")
	ca.PA = ctx.pa
	ca.SA = ctx.sa

	// Test that the CA collapses duplicate names
	csr, _ := x509.ParseCertificateRequest(DupeNameCSR)
	cert, err := ca.IssueCertificate(*csr, ctx.reg.ID)
	test.AssertNotError(t, err, "Failed to gracefully handle a CSR with duplicate names")
	if err != nil {
		return
	}

	parsedCert, err := x509.ParseCertificate(cert.DER)
	test.AssertNotError(t, err, "Error parsing certificate produced by CA")
	if err != nil {
		return
	}

	correctName := "a.not-example.com"
	correctNames := len(parsedCert.DNSNames) == 1 &&
		parsedCert.DNSNames[0] == correctName &&
		parsedCert.Subject.CommonName == correctName
	test.Assert(t, correctNames, "Incorrect set of names in deduplicated certificate")
}
示例#13
0
文件: helper.go 项目: denkhaus/lecert
func newCSR(domain string, bits int) (*x509.CertificateRequest, *rsa.PrivateKey, error) {
	l := log.WithField("domain", domain)

	l.Infof("Generating %d-bit RSA key", bits)
	certKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return nil, nil, err
	}

	template := &x509.CertificateRequest{
		SignatureAlgorithm: x509.SHA256WithRSA,
		PublicKeyAlgorithm: x509.RSA,
		PublicKey:          &certKey.PublicKey,
		Subject:            pkix.Name{CommonName: domain},
		DNSNames:           []string{domain},
	}

	l.Debugln("Generating CSR")
	csrDER, err := x509.CreateCertificateRequest(rand.Reader, template, certKey)
	if err != nil {
		return nil, nil, err
	}

	csr, err := x509.ParseCertificateRequest(csrDER)
	if err != nil {
		return nil, nil, err
	}
	return csr, certKey, nil
}
func TestCertificateKeyNotEqualAccountKey(t *testing.T) {
	_, _, sa, ra, cleanUp := initAuthorities(t)
	defer cleanUp()
	authz := core.Authorization{}
	authz, _ = sa.NewPendingAuthorization(authz)
	authz.Identifier = core.AcmeIdentifier{
		Type:  core.IdentifierDNS,
		Value: "www.example.com",
	}
	csr := x509.CertificateRequest{
		SignatureAlgorithm: x509.SHA256WithRSA,
		PublicKey:          AccountKeyA.Key,
		DNSNames:           []string{"www.example.com"},
	}
	csrBytes, err := x509.CreateCertificateRequest(rand.Reader, &csr, AccountPrivateKey.Key)
	test.AssertNotError(t, err, "Failed to sign CSR")
	parsedCSR, err := x509.ParseCertificateRequest(csrBytes)
	test.AssertNotError(t, err, "Failed to parse CSR")
	sa.UpdatePendingAuthorization(authz)
	sa.FinalizeAuthorization(authz)
	certRequest := core.CertificateRequest{
		CSR: parsedCSR,
	}

	// Registration id 1 has key == AccountKeyA
	_, err = ra.NewCertificate(certRequest, 1)
	test.AssertError(t, err, "Should have rejected cert with key = account key")
	test.AssertEquals(t, err.Error(), "Certificate public key must be different than account key")

	t.Log("DONE TestCertificateKeyNotEqualAccountKey")
}
func TestProfileSelection(t *testing.T) {
	ctx := setup(t)
	defer ctx.cleanUp()
	ctx.caConfig.MaxNames = 3
	ca, _ := NewCertificateAuthorityImpl(ctx.caConfig, ctx.fc, ctx.stats, caCert, caKey, ctx.keyPolicy)
	ca.Publisher = &mocks.Publisher{}
	ca.PA = ctx.pa
	ca.SA = ctx.sa

	testCases := []struct {
		CSR              []byte
		ExpectedKeyUsage x509.KeyUsage
	}{
		{CNandSANCSR, x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment},
		{ECDSACSR, x509.KeyUsageDigitalSignature},
	}

	for _, testCase := range testCases {
		csr, err := x509.ParseCertificateRequest(testCase.CSR)
		test.AssertNotError(t, err, "Cannot parse CSR")

		// Sign CSR
		issuedCert, err := ca.IssueCertificate(*csr, ctx.reg.ID)
		test.AssertNotError(t, err, "Failed to sign certificate")

		// Verify cert contents
		cert, err := x509.ParseCertificate(issuedCert.DER)
		test.AssertNotError(t, err, "Certificate failed to parse")

		t.Logf("expected key usage %v, got %v", testCase.ExpectedKeyUsage, cert.KeyUsage)
		test.AssertEquals(t, cert.KeyUsage, testCase.ExpectedKeyUsage)
	}
}
示例#16
0
文件: rootca.go 项目: nonovc/goproxy
func (c *RootCA) issue(commonName string, vaildFor time.Duration, rsaBits int) error {
	certFile := c.toFilename(commonName, ".crt")

	csrTemplate := &x509.CertificateRequest{
		Signature: []byte(commonName),
		Subject: pkix.Name{
			Country:            []string{"CN"},
			Organization:       []string{commonName},
			OrganizationalUnit: []string{c.name},
			CommonName:         commonName,
		},
		SignatureAlgorithm: x509.SHA256WithRSA,
	}

	priv, err := rsa.GenerateKey(rand.Reader, rsaBits)
	if err != nil {
		return err
	}

	csrBytes, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, priv)
	if err != nil {
		return err
	}

	csr, err := x509.ParseCertificateRequest(csrBytes)
	if err != nil {
		return err
	}

	certTemplate := &x509.Certificate{
		Subject:            csr.Subject,
		PublicKeyAlgorithm: csr.PublicKeyAlgorithm,
		PublicKey:          csr.PublicKey,
		SerialNumber:       big.NewInt(time.Now().UnixNano()),
		SignatureAlgorithm: x509.SHA256WithRSA,
		NotBefore:          time.Now().Add(-time.Duration(10 * time.Minute)).UTC(),
		NotAfter:           time.Now().Add(vaildFor),
		KeyUsage:           x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		ExtKeyUsage: []x509.ExtKeyUsage{
			x509.ExtKeyUsageServerAuth,
			x509.ExtKeyUsageClientAuth,
		},
	}

	certBytes, err := x509.CreateCertificate(rand.Reader, certTemplate, c.ca, csr.PublicKey, c.priv)
	if err != nil {
		return err
	}

	outFile, err := os.Create(certFile)
	defer outFile.Close()
	if err != nil {
		return err
	}
	pem.Encode(outFile, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})
	pem.Encode(outFile, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})

	return nil
}
示例#17
0
文件: local_test.go 项目: 40a/cfssl
func TestOverrideSubject(t *testing.T) {
	csrPEM, err := ioutil.ReadFile(fullSubjectCSR)
	if err != nil {
		t.Fatalf("%v", err)
	}

	req := &signer.Subject{
		Names: []csr.Name{
			{O: "example.net"},
		},
	}

	s := newCustomSigner(t, testECDSACaFile, testECDSACaKeyFile)

	request := signer.SignRequest{
		Hosts:   []string{"127.0.0.1", "localhost", "*****@*****.**"},
		Request: string(csrPEM),
		Subject: req,
	}

	certPEM, err := s.Sign(request)

	if err != nil {
		t.Fatalf("%v", err)
	}

	cert, err := helpers.ParseCertificatePEM(certPEM)
	if err != nil {
		t.Fatalf("%v", err)
	}

	block, _ := pem.Decode(csrPEM)
	template, err := x509.ParseCertificateRequest(block.Bytes)
	if err != nil {
		t.Fatal(err.Error())
	}
	if cert.Subject.Organization[0] != "example.net" {
		t.Fatalf("Failed to override subject: want example.net but have %s", cert.Subject.Organization[0])
	}

	if cert.Subject.Country[0] != template.Subject.Country[0] {
		t.Fatal("Failed to override Country")
	}

	if cert.Subject.Locality[0] != template.Subject.Locality[0] {
		t.Fatal("Failed to override Locality")
	}

	if cert.Subject.Organization[0] == template.Subject.Organization[0] {
		t.Fatal("Shouldn't have overrode Organization")
	}

	if cert.Subject.OrganizationalUnit[0] != template.Subject.OrganizationalUnit[0] {
		t.Fatal("Failed to override OrganizationalUnit")
	}

	log.Info("Overrode subject info")
}
// TestParseRequestCA ensures that a valid CA certificate request does not
// error and the resulting CSR includes the BasicConstraint extension
func TestParseRequestCA(t *testing.T) {
	var cr = &CertificateRequest{
		CN: "Test Common Name",
		Names: []Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "CloudFlare, Inc.",
				OU: "Systems Engineering",
			},
			{
				C:  "GB",
				ST: "London",
				L:  "London",
				O:  "CloudFlare, Inc",
				OU: "Systems Engineering",
			},
		},
		CA: &CAConfig{
			PathLength:  0,
			PathLenZero: true,
		},
		KeyRequest: NewBasicKeyRequest(),
	}

	csrBytes, _, err := ParseRequest(cr)
	if err != nil {
		t.Fatalf("%v", err)
	}

	block, _ := pem.Decode(csrBytes)
	if block == nil {
		t.Fatalf("%v", err)
	}

	if block.Type != "CERTIFICATE REQUEST" {
		t.Fatalf("Incorrect block type: %s", block.Type)
	}

	csr, err := x509.ParseCertificateRequest(block.Bytes)
	if err != nil {
		t.Fatalf("%v", err)
	}

	found := false
	for _, ext := range csr.Extensions {
		if ext.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 19}) {
			found = true
			break
		}
	}

	if !found {
		t.Fatalf("CSR did not include BasicConstraint Extension")
	}
}
示例#19
0
func TestVerifyCSR(t *testing.T) {
	for _, csrHex := range CSRs {
		csrDER, _ := hex.DecodeString(csrHex)
		csr, _ := x509.ParseCertificateRequest(csrDER)
		err := VerifyCSR(csr)
		if err != nil {
			t.Errorf("Error verifying CSR: %v", err)
		}
	}
}
func TestRejectValidityTooLong(t *testing.T) {
	ctx := setup(t)
	defer ctx.cleanUp()
	ca, err := NewCertificateAuthorityImpl(ctx.caDB, ctx.caConfig, ctx.fc, caCertFile)
	test.AssertNotError(t, err, "Failed to create CA")
	ca.PA = ctx.pa
	ca.SA = ctx.sa

	// Test that the CA rejects CSRs that would expire after the intermediate cert
	csr, _ := x509.ParseCertificateRequest(NoCNCSR)
	_, err = ca.IssueCertificate(*csr, ctx.reg.ID, FarPast)
	test.Assert(t, err == nil, "Can issue a certificate that expires after the underlying authorization.")

	// Test that the CA rejects CSRs that would expire after the intermediate cert
	csr, _ = x509.ParseCertificateRequest(NoCNCSR)
	ca.NotAfter = ctx.fc.Now()
	_, err = ca.IssueCertificate(*csr, 1, FarFuture)
	test.AssertEquals(t, err.Error(), "Cannot issue a certificate that expires after the intermediate certificate.")
}
示例#21
0
func parseCsr(csrfile *string) (*x509.CertificateRequest, error) {
	csrbytes, err := ioutil.ReadFile(*csrfile)
	if err != nil {
		return nil, err
	}
	csrblock, _ := pem.Decode(csrbytes)
	if csrblock == nil {
		return nil, fmt.Errorf("PEM encoded data not found in %s", *csrfile)
	}
	return x509.ParseCertificateRequest(csrblock.Bytes)
}
示例#22
0
func (cas *CertificateAuthorityServerWrapper) IssueCertificate(ctx context.Context, request *caPB.IssueCertificateRequest) (*corepb.Certificate, error) {
	csr, err := x509.ParseCertificateRequest(request.Csr)
	if err != nil {
		return nil, err
	}
	cert, err := cas.inner.IssueCertificate(ctx, *csr, *request.RegistrationID)
	if err != nil {
		return nil, err
	}
	return certToPB(cert), nil
}
示例#23
0
// ParseCSRPEM parses a PEM-encoded certificiate signing request.
// It does not check the signature. This is useful for dumping data from a CSR
// locally.
func ParseCSRPEM(csrPEM []byte) (*x509.CertificateRequest, error) {
	block, _ := pem.Decode([]byte(csrPEM))
	der := block.Bytes
	csrObject, err := x509.ParseCertificateRequest(der)

	if err != nil {
		return nil, err
	}

	return csrObject, nil
}
func TestRejectValidityTooLong(t *testing.T) {
	cadb, storageAuthority, caConfig := setup(t)
	ca, err := NewCertificateAuthorityImpl(cadb, caConfig, caCertFile)
	test.AssertNotError(t, err, "Failed to create CA")
	ca.SA = storageAuthority
	ca.MaxKeySize = 4096

	// Test that the CA rejects CSRs that would expire after the intermediate cert
	csrDER, _ := hex.DecodeString(NoCNCSRhex)
	csr, _ := x509.ParseCertificateRequest(csrDER)
	_, err = ca.IssueCertificate(*csr, 1, FarPast)
	test.Assert(t, err == nil, "Can issue a certificate that expires after the underlying authorization.")

	// Test that the CA rejects CSRs that would expire after the intermediate cert
	csrDER, _ = hex.DecodeString(NoCNCSRhex)
	csr, _ = x509.ParseCertificateRequest(csrDER)
	ca.NotAfter = time.Now()
	_, err = ca.IssueCertificate(*csr, 1, FarFuture)
	test.AssertEquals(t, err.Error(), "Cannot issue a certificate that expires after the intermediate certificate.")
}
示例#25
0
func TestRejectBadAlgorithm(t *testing.T) {
	ctx := setup(t)
	defer ctx.cleanUp()
	ca, err := NewCertificateAuthorityImpl(ctx.caDB, ctx.caConfig, ctx.fc, caCertFile)
	ca.PA = ctx.pa
	ca.SA = ctx.sa

	// Test that the CA rejects CSRs that would expire after the intermediate cert
	csr, _ := x509.ParseCertificateRequest(BadAlgorithmCSR)
	_, err = ca.IssueCertificate(*csr, ctx.reg.ID)
	test.Assert(t, err != nil, "Issued a certificate based on a CSR with a weak algorithm.")
}
func TestRejectBadAlgorithm(t *testing.T) {
	cadb, storageAuthority, caConfig := setup(t)
	ca, err := NewCertificateAuthorityImpl(cadb, caConfig, caCertFile)
	ca.SA = storageAuthority
	ca.MaxKeySize = 4096

	// Test that the CA rejects CSRs that would expire after the intermediate cert
	csrDER, _ := hex.DecodeString(BadAlgorithmCSRhex)
	csr, _ := x509.ParseCertificateRequest(csrDER)
	_, err = ca.IssueCertificate(*csr, 1, FarFuture)
	test.Assert(t, err != nil, "Issued a certificate based on a CSR with a weak algorithm.")
}
示例#27
0
// build cr field if needed
func (c *CertificateSigningRequest) buildPKCS10CertificateSigningRequest() error {
	if c.cr != nil {
		return nil
	}

	var err error
	c.cr, err = x509.ParseCertificateRequest(c.derBytes)
	if err != nil {
		return err
	}
	return nil
}
func TestRejectTooManyNames(t *testing.T) {
	cadb, storageAuthority, caConfig := setup(t)
	ca, err := NewCertificateAuthorityImpl(cadb, caConfig, caCertFile)
	test.AssertNotError(t, err, "Failed to create CA")
	ca.SA = storageAuthority

	// Test that the CA rejects a CSR with too many names
	csrDER, _ := hex.DecodeString(TooManyNameCSRhex)
	csr, _ := x509.ParseCertificateRequest(csrDER)
	_, err = ca.IssueCertificate(*csr, 1, FarFuture)
	test.Assert(t, err != nil, "Issued certificate with too many names")
}
示例#29
0
func pemDecodeTox509CSR(pem []byte) (*x509.CertificateRequest, error) {
	pemBlock, err := pemDecode(pem)
	if pemBlock == nil {
		return nil, err
	}

	if pemBlock.Type != "CERTIFICATE REQUEST" {
		return nil, fmt.Errorf("PEM block is not a certificate request")
	}

	return x509.ParseCertificateRequest(pemBlock.Bytes)
}
示例#30
0
func TestShortKey(t *testing.T) {
	ctx := setup(t)
	defer ctx.cleanUp()
	ca, err := NewCertificateAuthorityImpl(ctx.caDB, ctx.caConfig, ctx.fc, caCertFile)
	ca.PA = ctx.pa
	ca.SA = ctx.sa

	// Test that the CA rejects CSRs that would expire after the intermediate cert
	csr, _ := x509.ParseCertificateRequest(ShortKeyCSR)
	_, err = ca.IssueCertificate(*csr, ctx.reg.ID)
	test.Assert(t, err != nil, "Issued a certificate with too short a key.")
}