Exemple #1
0
// NewSignerFromFile reads the issuer cert, the responder cert and the responder key
// from PEM files, and takes an interval in seconds
func NewSignerFromFile(issuerFile, responderFile, keyFile string, interval time.Duration) (Signer, error) {
	log.Debug("Loading issuer cert: ", issuerFile)
	issuerBytes, err := ioutil.ReadFile(issuerFile)
	if err != nil {
		return nil, err
	}
	log.Debug("Loading responder cert: ", responderFile)
	responderBytes, err := ioutil.ReadFile(responderFile)
	if err != nil {
		return nil, err
	}
	log.Debug("Loading responder key: ", keyFile)
	keyBytes, err := ioutil.ReadFile(keyFile)
	if err != nil {
		return nil, cferr.Wrap(cferr.CertificateError, cferr.ReadFailed, err)
	}

	issuerCert, err := helpers.ParseCertificatePEM(issuerBytes)
	if err != nil {
		return nil, err
	}

	responderCert, err := helpers.ParseCertificatePEM(responderBytes)
	if err != nil {
		return nil, err
	}

	key, err := helpers.ParsePrivateKeyPEM(keyBytes)
	if err != nil {
		log.Debug("Malformed private key %v", err)
		return nil, err
	}

	return NewSigner(issuerCert, responderCert, key, interval)
}
Exemple #2
0
// NewSignerFromFile generates a new local signer from a caFile
// and a caKey file, both PEM encoded.
func NewSignerFromFile(caFile, caKeyFile string, policy *config.Signing) (*Signer, error) {
	log.Debug("Loading CA: ", caFile)
	ca, err := ioutil.ReadFile(caFile)
	if err != nil {
		return nil, err
	}
	log.Debug("Loading CA key: ", caKeyFile)
	cakey, err := ioutil.ReadFile(caKeyFile)
	if err != nil {
		return nil, cferr.Wrap(cferr.CertificateError, cferr.ReadFailed, err)
	}

	parsedCa, err := helpers.ParseCertificatePEM(ca)
	if err != nil {
		return nil, err
	}

	strPassword := os.Getenv("CFSSL_CA_PK_PASSWORD")
	password := []byte(strPassword)
	if strPassword == "" {
		password = nil
	}

	priv, err := helpers.ParsePrivateKeyPEMWithPassword(cakey, password)
	if err != nil {
		log.Debug("Malformed private key %v", err)
		return nil, err
	}

	return NewSigner(priv, parsedCa, signer.DefaultSigAlgo(priv), policy)
}
Exemple #3
0
// NewBundlerFromPEM creates a new Bundler from PEM-encoded root certificates and
// intermediate certificates.
func NewBundlerFromPEM(caBundlePEM, intBundlePEM []byte) (*Bundler, error) {
	b := &Bundler{
		RootPool:         x509.NewCertPool(),
		IntermediatePool: x509.NewCertPool(),
		KnownIssuers:     map[string]bool{},
	}

	log.Debug("parsing root certificates from PEM")
	roots, err := helpers.ParseCertificatesPEM(caBundlePEM)
	if err != nil {
		log.Errorf("failed to parse root bundle: %v", err)
		return nil, errors.New(errors.RootError, errors.ParseFailed)
	}

	log.Debug("parse intermediate certificates from PEM")
	var intermediates []*x509.Certificate
	if intermediates, err = helpers.ParseCertificatesPEM(intBundlePEM); err != nil {
		log.Errorf("failed to parse intermediate bundle: %v", err)
		return nil, errors.New(errors.IntermediatesError, errors.ParseFailed)
	}

	log.Debug("building certificate pools")
	for _, c := range roots {
		b.RootPool.AddCert(c)
		b.KnownIssuers[string(c.Signature)] = true
	}

	for _, c := range intermediates {
		b.IntermediatePool.AddCert(c)
		b.KnownIssuers[string(c.Signature)] = true
	}

	log.Debug("bundler set up")
	return b, nil
}
// AutoUpdate will automatically update the listener. If a non-nil
// certUpdates chan is provided, it will receive timestamps for
// reissued certificates. If errChan is non-nil, any errors that occur
// in the updater will be passed along.
func (l *Listener) AutoUpdate(certUpdates chan<- time.Time, errChan chan<- error) {
	defer func() {
		if r := recover(); r != nil {
			log.Criticalf("AutoUpdate panicked: %v", r)
		}
	}()

	for {
		// Wait until it's time to update the certificate.
		target := time.Now().Add(l.Lifespan())
		if PollInterval == 0 {
			<-time.After(l.Lifespan())
		} else {
			pollWait(target)
		}

		// Keep trying to update the certificate until it's
		// ready.
		for {
			log.Debug("refreshing certificate")
			err := l.RefreshKeys()
			if err == nil {
				break
			}

			delay := l.Transport.Backoff.Duration()
			log.Debugf("failed to update certificate, will try again in %s", delay)
			if errChan != nil {
				errChan <- err
			}

			<-time.After(delay)
		}

		if certUpdates != nil {
			certUpdates <- time.Now()
		}

		config, err := l.getConfig()
		if err != nil {
			log.Debug("immediately after getting a new certificate, the Transport is reporting errors: %v", err)
			if errChan != nil {
				errChan <- err
			}
		}

		address := l.Listener.Addr().String()
		lnet := l.Listener.Addr().Network()
		l.Listener, err = tls.Listen(lnet, address, config)
		if err != nil {
			log.Debug("immediately after getting a new certificate, the Transport is reporting errors: %v", err)
			if errChan != nil {
				errChan <- err
			}
		}

		log.Debug("listener: auto update of certificate complete")
		l.Transport.Backoff.Reset()
	}
}
Exemple #5
0
func (c *Client) lookupIPs(host string) (ips []net.IP, err error) {
	m := new(dns.Msg)
	for _, resolver := range c.Resolvers {
		m.SetQuestion(dns.Fqdn(host), dns.TypeA)
		if in, err := dns.Exchange(m, resolver); err == nil {
			for _, rr := range in.Answer {
				if a, ok := rr.(*dns.A); ok {
					ips = append(ips, a.A)
				}
			}
		} else {
			log.Debug(err)
		}

		m.SetQuestion(dns.Fqdn(host), dns.TypeAAAA)
		if in, err := dns.Exchange(m, resolver); err == nil {
			for _, rr := range in.Answer {
				if aaaa, ok := rr.(*dns.AAAA); ok {
					ips = append(ips, aaaa.AAAA)
				}
			}
		} else {
			log.Debug(err)
		}
	}
	if len(ips) != 0 {
		return ips, nil
	}

	return net.LookupIP(host)
}
Exemple #6
0
// Handle accepts client information requests, and uses the label to
// look up the signer whose public certificate should be retrieved. If
// the label is empty, the default label is used.
func (h *MultiHandler) Handle(w http.ResponseWriter, r *http.Request) error {
	req := new(info.Req)
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Warningf("failed to read request body: %v", err)
		return errors.NewBadRequest(err)
	}
	err = json.Unmarshal(body, req)
	if err != nil {
		log.Warningf("failed to unmarshal request: %v", err)
		return errors.NewBadRequest(err)
	}

	log.Debug("checking label")
	if req.Label == "" {
		req.Label = h.defaultLabel
	}

	if _, ok := h.signers[req.Label]; !ok {
		log.Warningf("request for invalid endpoint")
		return errors.NewBadRequestString("bad label")
	}

	log.Debug("getting info")
	resp, err := h.signers[req.Label].Info(*req)
	if err != nil {
		log.Infof("error getting certificate: %v", err)
		return err
	}

	response := api.NewSuccessResponse(resp)
	w.Header().Set("Content-Type", "application/json")
	enc := json.NewEncoder(w)
	return enc.Encode(response)
}
Exemple #7
0
// NewSignerFromFile generates a new local signer from a caFile
// and a caKey file, both PEM encoded.
func NewSignerFromFile(caFile, caKeyFile string, policy *config.Signing) (*Signer, error) {
	log.Debug("Loading CA: ", caFile)
	ca, err := ioutil.ReadFile(caFile)
	if err != nil {
		return nil, err
	}
	log.Debug("Loading CA key: ", caKeyFile)
	cakey, err := ioutil.ReadFile(caKeyFile)
	if err != nil {
		return nil, cferr.Wrap(cferr.CertificateError, cferr.ReadFailed, err)
	}

	parsedCa, err := helpers.ParseCertificatePEM(ca)
	if err != nil {
		return nil, err
	}

	priv, err := helpers.ParsePrivateKeyPEM(cakey)
	if err != nil {
		log.Debug("Malformed private key %v", err)
		return nil, err
	}

	return NewSigner(priv, parsedCa, signer.DefaultSigAlgo(priv), policy)
}
Exemple #8
0
// NewBundler creates a new Bundler from the files passed in; these
// files should contain a list of valid root certificates and a list
// of valid intermediate certificates, respectively.
func NewBundler(caBundleFile, intBundleFile string) (*Bundler, error) {
	log.Debug("Loading CA bundle: ", caBundleFile)
	caBundle, err := ioutil.ReadFile(caBundleFile)
	if err != nil {
		log.Errorf("root bundle failed to load: %v", err)
		return nil, errors.Wrap(errors.RootError, errors.ReadFailed, err)
	}

	log.Debug("Loading Intermediate bundle: ", intBundleFile)
	intBundle, err := ioutil.ReadFile(intBundleFile)
	if err != nil {
		log.Errorf("intermediate bundle failed to load: %v", err)
		return nil, errors.Wrap(errors.IntermediatesError, errors.ReadFailed, err)
	}

	if _, err := os.Stat(IntermediateStash); err != nil && os.IsNotExist(err) {
		log.Infof("intermediate stash directory %s doesn't exist, creating", IntermediateStash)
		err = os.MkdirAll(IntermediateStash, 0755)
		if err != nil {
			log.Errorf("failed to create intermediate stash directory %s: %v",
				IntermediateStash, err)
			return nil, err
		}
		log.Infof("intermediate stash directory %s created", IntermediateStash)
	}
	return NewBundlerFromPEM(caBundle, intBundle)

}
Exemple #9
0
// RefreshKeys will make sure the Transport has loaded keys and has a
// valid certificate. It will handle any persistence, check that the
// certificate is valid (i.e. that its expiry date is within the
// Before date), and handle certificate reissuance as needed.
func (tr *Transport) RefreshKeys() (err error) {
	if !tr.Provider.Ready() {
		log.Debug("key and certificate aren't ready, loading")
		err = tr.Provider.Load()
		if err != nil && err != kp.ErrCertificateUnavailable {
			log.Debugf("failed to load keypair: %v", err)
			kr := tr.Identity.Request.KeyRequest
			if kr == nil {
				kr = csr.NewBasicKeyRequest()
			}

			err = tr.Provider.Generate(kr.Algo(), kr.Size())
			if err != nil {
				log.Debugf("failed to generate key: %v", err)
				return
			}
		}
	}

	lifespan := tr.Lifespan()
	if lifespan < tr.Before {
		log.Debugf("transport's certificate is out of date (lifespan %s)", lifespan)
		req, err := tr.Provider.CertificateRequest(tr.Identity.Request)
		if err != nil {
			log.Debugf("couldn't get a CSR: %v", err)
			return err
		}

		log.Debug("requesting certificate from CA")
		cert, err := tr.CA.SignCSR(req)
		if err != nil {
			log.Debugf("failed to get the certificate signed: %v", err)
			return err
		}

		log.Debug("giving the certificate to the provider")
		err = tr.Provider.SetCertificatePEM(cert)
		if err != nil {
			log.Debugf("failed to set the provider's certificate: %v", err)
			return err
		}

		log.Debug("storing the certificate")
		err = tr.Provider.Store()
		if err != nil {
			log.Debugf("the provider failed to store the certificate: %v", err)
			return err
		}
	}

	return nil
}
Exemple #10
0
func (keys *defaultKeystore) Get(op *gokeyless.Operation) (priv crypto.Signer, ok bool) {
	keys.RLock()
	defer keys.RUnlock()

	ski := op.SKI
	if ski.Valid() {
		priv, ok = keys.skis[ski]
	} else {
		if !ok {
			log.Debug("Couldn't look up key based on SKI, trying Digest.")
			if ski, ok = keys.digests[op.Digest]; ok {
				priv, ok = keys.skis[ski]
			}
		}

		if !ok {
			log.Debug("Couldn't look up key based on Digest, trying SNI.")
			if ski, ok = keys.snis[op.SNI]; ok {
				priv, ok = keys.skis[ski]
			}
		}

		if !ok {
			if op.ServerIP != nil {
				log.Debug("Couldn't look up key based on SNI, trying Server IP.")
				if ski, ok = keys.serverIPs[op.ServerIP.String()]; ok {
					priv, ok = keys.skis[ski]
				}
			}
		}

		if !ok {
			if op.ClientIP != nil {
				log.Debug("Couldn't look up key based on Server IP, trying Client IP.")
				if ski, ok = keys.clientIPs[op.ClientIP.String()]; ok {
					priv, ok = keys.skis[ski]
				}
			}
		}
	}

	if !ok {
		log.Infof("Couldn't look up key for %s.", op)
	} else if len(keys.validAKIs[ski]) > 0 && !keys.validAKIs[ski].Contains(op.AKI) {
		log.Warningf("Attempt to access key with invalid AKI: %s", op.AKI)
		return nil, false
	}

	return
}
Exemple #11
0
func (b *Bundler) verifyChain(chain []*fetchedIntermediate) bool {
	// This process will verify if the root of the (partial) chain is in our root pool,
	// and will fail otherwise.
	log.Debugf("verifying chain")
	for vchain := chain[:]; len(vchain) > 0; vchain = vchain[1:] {
		cert := vchain[0]
		// If this is a certificate in one of the pools, skip it.
		if b.KnownIssuers[string(cert.Cert.Signature)] {
			log.Debugf("certificate is known")
			continue
		}

		_, err := cert.Cert.Verify(b.VerifyOptions())
		if err != nil {
			log.Debugf("certificate failed verification: %v", err)
			return false
		} else if len(chain) == len(vchain) && isChainRootNode(cert.Cert) {
			// The first certificate in the chain is a root; it shouldn't be stored.
			log.Debug("looking at root certificate, will not store")
			continue
		}

		// leaf cert has an empty name, don't store leaf cert.
		if cert.Name == "" {
			continue
		}

		log.Debug("add certificate to intermediate pool:", cert.Name)
		b.IntermediatePool.AddCert(cert.Cert)
		b.KnownIssuers[string(cert.Cert.Signature)] = true

		if IntermediateStash != "" {
			fileName := filepath.Join(IntermediateStash, cert.Name)

			var block = pem.Block{Type: "CERTIFICATE", Bytes: cert.Cert.Raw}

			log.Debugf("write intermediate to stash directory: %s", fileName)
			// If the write fails, verification should not fail.
			err = ioutil.WriteFile(fileName, pem.EncodeToMemory(&block), 0644)
			if err != nil {
				log.Errorf("failed to write new intermediate: %v", err)
			} else {
				log.Info("stashed new intermediate ", cert.Name)
			}
		}
	}
	return true
}
Exemple #12
0
// LoadPlatforms reads the file content as a json object array and convert it
// to Platforms.
func LoadPlatforms(filename string) error {
	relativePath := filepath.Dir(filename)
	// Attempt to load root certificate metadata
	log.Debug("Loading platform metadata: ", filename)
	bytes, err := ioutil.ReadFile(filename)
	if err != nil {
		return fmt.Errorf("platform metadata failed to load: %v", err)
	}
	var rawPlatforms []Platform
	if bytes != nil {
		err = json.Unmarshal(bytes, &rawPlatforms)
		if err != nil {
			return fmt.Errorf("platform metadata failed to parse: %v", err)
		}
	}

	for _, platform := range rawPlatforms {
		if platform.KeyStoreFile != "" {
			platform.KeyStoreFile = path.Join(relativePath, platform.KeyStoreFile)
		}
		ok := platform.ParseAndLoad()
		if !ok {
			// erase all loaded platforms
			Platforms = nil
			return fmt.Errorf("fail to finalize the parsing of platform metadata: %v", platform)
		}

		log.Infof("Platform metadata is loaded: %v %v", platform.Name, len(platform.KeyStore))
		Platforms = append(Platforms, platform)
	}

	return nil
}
Exemple #13
0
// LoadPlatforms reads the file content as a json object array and convert it
// to Platforms.
func LoadPlatforms(filename string) {
	// Attempt to load root certificate metadata
	log.Debug("Loading platform metadata: ", filename)
	bytes, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Errorf("platform metadata failed to load: %v", err)
	}
	var rawPlatforms []Platform
	if bytes != nil {
		err = json.Unmarshal(bytes, &rawPlatforms)
		if err != nil {
			log.Errorf("platform metadata failed to parse: %v", err)
		}
	}

	for _, platform := range rawPlatforms {
		ok := platform.ParseAndLoad()
		if !ok {
			log.Errorf("fail to finalize the parsing of platform metadata:", err)
		} else {
			log.Infof("Platform metadata is loaded: %v %v", platform.Name, len(platform.KeyStore))
			Platforms = append(Platforms, platform)
		}
	}
}
Exemple #14
0
// post connects to the remote server and returns a Response struct
func (srv *server) post(url string, jsonData []byte) (*api.Response, error) {
	buf := bytes.NewBuffer(jsonData)
	resp, err := http.Post(url, "application/json", buf)
	if err != nil {
		return nil, errors.Wrap(errors.APIClientError, errors.ClientHTTPError, err)
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, errors.Wrap(errors.APIClientError, errors.IOError, err)
	}
	resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, errors.Wrap(errors.APIClientError, errors.ClientHTTPError, stderr.New(string(body)))
	}

	var response api.Response
	err = json.Unmarshal(body, &response)
	if err != nil {
		log.Debug("Unable to parse response body:", string(body))
		return nil, errors.Wrap(errors.APIClientError, errors.JSONError, err)
	}

	if !response.Success || response.Result == nil {
		if len(response.Errors) > 0 {
			return nil, errors.Wrap(errors.APIClientError, errors.ServerRequestFailed, stderr.New(response.Errors[0].Message))
		}
		return nil, errors.New(errors.APIClientError, errors.ServerRequestFailed)
	}

	return &response, nil
}
Exemple #15
0
// CreateGenericCRL is a helper function that takes in all of the information above, and then calls the createCRL
// function. This outputs the bytes of the created CRL.
func CreateGenericCRL(certList []pkix.RevokedCertificate, key crypto.Signer, issuingCert *x509.Certificate, expiryTime time.Time) ([]byte, error) {
	crlBytes, err := issuingCert.CreateCRL(rand.Reader, key, certList, time.Now(), expiryTime)
	if err != nil {
		log.Debug("error creating CRL: %s", err)
	}

	return crlBytes, err

}
Exemple #16
0
// NewBundlerFromPEM creates a new Bundler from PEM-encoded root certificates and
// intermediate certificates.
// If caBundlePEM is nil, the resulting Bundler can only do "Force" bundle.
func NewBundlerFromPEM(caBundlePEM, intBundlePEM []byte) (*Bundler, error) {
	log.Debug("parsing root certificates from PEM")
	roots, err := helpers.ParseCertificatesPEM(caBundlePEM)
	if err != nil {
		log.Errorf("failed to parse root bundle: %v", err)
		return nil, errors.New(errors.RootError, errors.ParseFailed)
	}

	log.Debug("parse intermediate certificates from PEM")
	intermediates, err := helpers.ParseCertificatesPEM(intBundlePEM)
	if err != nil {
		log.Errorf("failed to parse intermediate bundle: %v", err)
		return nil, errors.New(errors.IntermediatesError, errors.ParseFailed)
	}

	b := &Bundler{
		KnownIssuers:     map[string]bool{},
		IntermediatePool: x509.NewCertPool(),
	}

	log.Debug("building certificate pools")

	// RootPool will be nil if caBundlePEM is nil, also
	// that translates to caBundleFile is "".
	// Systems root store will be used.
	if caBundlePEM != nil {
		b.RootPool = x509.NewCertPool()
	}

	for _, c := range roots {
		b.RootPool.AddCert(c)
		b.KnownIssuers[string(c.Signature)] = true
	}

	for _, c := range intermediates {
		b.IntermediatePool.AddCert(c)
		b.KnownIssuers[string(c.Signature)] = true
	}

	log.Debug("bundler set up")
	return b, nil
}
Exemple #17
0
// NewCRLFromFile takes in a list of serial numbers, one per line, as well as the issuing certificate
// of the CRL, and the private key. This function is then used to parse the list and generate a CRL
func NewCRLFromFile(serialList, issuerFile, keyFile []byte, expiryTime string) ([]byte, error) {

	var revokedCerts []pkix.RevokedCertificate
	var oneWeek = time.Duration(604800) * time.Second

	expiryInt, err := strconv.ParseInt(expiryTime, 0, 32)
	if err != nil {
		return nil, err
	}
	newDurationFromInt := time.Duration(expiryInt) * time.Second
	newExpiryTime := time.Now().Add(newDurationFromInt)
	if expiryInt == 0 {
		newExpiryTime = time.Now().Add(oneWeek)
	}

	// Parse the PEM encoded certificate
	issuerCert, err := helpers.ParseCertificatePEM(issuerFile)
	if err != nil {
		return nil, err
	}

	// Split input file by new lines
	individualCerts := strings.Split(string(serialList), "\n")

	// For every new line, create a new revokedCertificate and add it to slice
	for _, value := range individualCerts {
		if len(strings.TrimSpace(value)) == 0 {
			continue
		}

		tempBigInt := new(big.Int)
		tempBigInt.SetString(value, 10)
		tempCert := pkix.RevokedCertificate{
			SerialNumber:   tempBigInt,
			RevocationTime: time.Now(),
		}
		revokedCerts = append(revokedCerts, tempCert)
	}

	strPassword := os.Getenv("CFSSL_CA_PK_PASSWORD")
	password := []byte(strPassword)
	if strPassword == "" {
		password = nil
	}

	// Parse the key given
	key, err := helpers.ParsePrivateKeyPEMWithPassword(keyFile, password)
	if err != nil {
		log.Debug("Malformed private key %v", err)
		return nil, err
	}

	return CreateGenericCRL(revokedCerts, key, issuerCert, newExpiryTime)
}
Exemple #18
0
// LoadClientCertificate load key/certificate from pem files
func LoadClientCertificate(certFile string, keyFile string) (*tls.Certificate, error) {
	if certFile != "" && keyFile != "" {
		cert, err := tls.LoadX509KeyPair(certFile, keyFile)
		if err != nil {
			log.Critical("Unable to read client certificate from file: %s or key from file: %s", certFile, keyFile)
			return nil, err
		}
		log.Debug("Client certificate loaded ")
		return &cert, nil
	}
	return nil, nil
}
func testListen(t *testing.T) {
	log.Debug("listener waiting for connection")
	conn, err := l.Accept()
	if err != nil {
		t.Fatalf("%v", err)
	}

	log.Debugf("client has connected")
	conn.Write([]byte("hello"))

	conn.Close()
}
Exemple #20
0
func (keys *defaultKeystore) Get(op *gokeyless.Operation) (priv crypto.Signer, ok bool) {
	keys.RLock()
	defer keys.RUnlock()

	ski := op.SKI
	if priv, ok = keys.skis[ski]; ok {
		return
	}

	log.Debug("Couldn't look up key based on SKI, trying Digest.")
	if ski, ok = keys.digests[op.Digest]; ok {
		priv, ok = keys.skis[ski]
		return
	}

	log.Debug("Couldn't look up key based on Digest, trying SNI.")
	if ski, ok = keys.snis[op.SNI]; ok {
		priv, ok = keys.skis[ski]
		return
	}

	if op.ServerIP != nil {
		log.Debug("Couldn't look up key based on SNI, trying Server IP.")
		if ski, ok = keys.serverIPs[op.ServerIP.String()]; ok {
			priv, ok = keys.skis[ski]
			return
		}
	}

	if op.ClientIP != nil {
		log.Debug("Couldn't look up key based on Server IP, trying Client IP.")
		if ski, ok = keys.clientIPs[op.ClientIP.String()]; ok {
			priv, ok = keys.skis[ski]
			return
		}
	}

	log.Infof("Couldn't look up key for %s.", op)
	return
}
func TestListener(t *testing.T) {
	var before = 55 * time.Second

	trl, err := New(before, testLIdentity)
	if err != nil {
		t.Fatalf("failed to set up transport: %v", err)
	}

	trl.Identity.Request.CN = "localhost test server"

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

	l, err = Listen("127.0.0.1:8765", trl)
	if err != nil {
		t.Fatalf("%v", err)
	}

	errChan := make(chan error, 0)
	go func() {
		err := <-errChan
		if err != nil {
			t.Fatalf("listener auto update failed: %v", err)
		}
	}()

	cert := trl.Provider.Certificate()
	before = cert.NotAfter.Sub(time.Now())
	before -= 5 * time.Second

	trl.Before = before
	go l.AutoUpdate(nil, errChan)
	go testListen(t)

	<-time.After(1 * time.Second)
	log.Debug("dialer making connection")
	conn, err := Dial("127.0.0.1:8765", tr)
	if err != nil {
		log.Debugf("certificate time: %s-%s / %s",
			trl.Provider.Certificate().NotBefore,
			trl.Provider.Certificate().NotAfter,
			time.Now().UTC())
		log.Debugf("%#v", trl.Provider.Certificate())
		t.Fatalf("%v", err)
	}
	log.Debugf("client connected to server")

	conn.Close()
}
Exemple #22
0
// BundleFromFile takes a set of files containing the PEM-encoded leaf certificate
// (optionally along with some intermediate certs), the PEM-encoded private key
// and returns the bundle built from that key and the certificate(s).
func (b *Bundler) BundleFromFile(bundleFile, keyFile string, flavor BundleFlavor, password string) (*Bundle, error) {
	log.Debug("Loading Certificate: ", bundleFile)
	certsRaw, err := ioutil.ReadFile(bundleFile)
	if err != nil {
		return nil, errors.Wrap(errors.CertificateError, errors.ReadFailed, err)
	}

	var keyPEM []byte
	// Load private key PEM only if a file is given
	if keyFile != "" {
		log.Debug("Loading private key: ", keyFile)
		keyPEM, err = ioutil.ReadFile(keyFile)
		if err != nil {
			log.Debugf("failed to read private key: ", err)
			return nil, errors.Wrap(errors.PrivateKeyError, errors.ReadFailed, err)
		}
		if len(keyPEM) == 0 {
			log.Debug("key is empty")
			return nil, errors.Wrap(errors.PrivateKeyError, errors.DecodeFailed, err)
		}
	}

	return b.BundleFromPEMorDER(certsRaw, keyPEM, flavor, password)
}
Exemple #23
0
// NewSigner generates a new certificate signer using the certificate
// authority certificate and private key and Signing config for signing. caFile should
// contain the CA's certificate, and the cakeyFile should contain the
// private key. Both must be PEM-encoded.
func NewSigner(caFile, cakeyFile string, policy *config.Signing) (*Signer, error) {
	if policy == nil {
		policy = &config.Signing{
			Profiles: map[string]*config.SigningProfile{},
			Default:  config.DefaultConfig(),
		}
	}

	if !policy.Valid() {
		return nil, cferr.New(cferr.PolicyError, cferr.InvalidPolicy, errors.New("invalid policy"))
	}

	log.Debug("Loading CA: ", caFile)
	ca, err := ioutil.ReadFile(caFile)
	if err != nil {
		return nil, err
	}
	log.Debug("Loading CA key: ", cakeyFile)
	cakey, err := ioutil.ReadFile(cakeyFile)
	if err != nil {
		return nil, err
	}

	parsedCa, err := helpers.ParseCertificatePEM(ca)
	if err != nil {
		return nil, err
	}

	priv, err := helpers.ParsePrivateKeyPEM(cakey)
	if err != nil {

		return nil, err
	}

	return &Signer{parsedCa, priv, policy, DefaultSigAlgo(priv)}, nil
}
Exemple #24
0
// post connects to the remote server and returns a Response struct
func (srv *server) post(url string, jsonData []byte) (*api.Response, error) {
	var resp *http.Response
	var err error
	client := &http.Client{}
	if srv.TLSConfig != nil {
		client.Transport = srv.createTLSTransport()
	}
	req, err := http.NewRequest("POST", url, bytes.NewReader(jsonData))
	if err != nil {
		err = fmt.Errorf("failed POST to %s: %v", url, err)
		return nil, errors.Wrap(errors.APIClientError, errors.ClientHTTPError, err)
	}
	req.Header.Set("content-type", "application/json")
	if srv.reqModifier != nil {
		srv.reqModifier(req, jsonData)
	}
	resp, err = client.Do(req)
	if err != nil {
		err = fmt.Errorf("failed POST to %s: %v", url, err)
		return nil, errors.Wrap(errors.APIClientError, errors.ClientHTTPError, err)
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, errors.Wrap(errors.APIClientError, errors.IOError, err)
	}
	resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		log.Errorf("http error with %s", url)
		return nil, errors.Wrap(errors.APIClientError, errors.ClientHTTPError, stderr.New(string(body)))
	}

	var response api.Response
	err = json.Unmarshal(body, &response)
	if err != nil {
		log.Debug("Unable to parse response body:", string(body))
		return nil, errors.Wrap(errors.APIClientError, errors.JSONError, err)
	}

	if !response.Success || response.Result == nil {
		if len(response.Errors) > 0 {
			return nil, errors.Wrap(errors.APIClientError, errors.ServerRequestFailed, stderr.New(response.Errors[0].Message))
		}
		return nil, errors.New(errors.APIClientError, errors.ServerRequestFailed)
	}

	return &response, nil
}
Exemple #25
0
func (tr *Transport) getCertificate() (cert tls.Certificate, err error) {
	if !tr.Provider.Ready() {
		log.Debug("transport isn't ready; attempting to refresh keypair")
		err = tr.RefreshKeys()
		if err != nil {
			log.Debugf("transport couldn't get a certificate: %v", err)
			return
		}
	}

	cert, err = tr.Provider.X509KeyPair()
	if err != nil {
		log.Debugf("couldn't generate an X.509 keypair: %v", err)
	}

	return
}
Exemple #26
0
// post connects to the remote server and returns a Response struct
func (srv *server) post(url string, jsonData []byte) (*api.Response, error) {
	buf := bytes.NewBuffer(jsonData)
	var resp *http.Response
	var err error
	if srv.TLSConfig != nil {
		transport := srv.createTransport()
		client := &http.Client{Transport: transport}
		resp, err = client.Post(url, "application/json", buf)
	} else {
		resp, err = http.Post(url, "application/json", buf)
	}
	if err != nil {
		err = fmt.Errorf("failed POST to %s: %v", url, err)
		return nil, errors.Wrap(errors.APIClientError, errors.ClientHTTPError, err)
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, errors.Wrap(errors.APIClientError, errors.IOError, err)
	}
	resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		log.Errorf("http error with %s", url)
		return nil, errors.Wrap(errors.APIClientError, errors.ClientHTTPError, stderr.New(string(body)))
	}

	var response api.Response
	err = json.Unmarshal(body, &response)
	if err != nil {
		log.Debug("Unable to parse response body:", string(body))
		return nil, errors.Wrap(errors.APIClientError, errors.JSONError, err)
	}

	if !response.Success || response.Result == nil {
		if len(response.Errors) > 0 {
			return nil, errors.Wrap(errors.APIClientError, errors.ServerRequestFailed, stderr.New(response.Errors[0].Message))
		}
		return nil, errors.New(errors.APIClientError, errors.ServerRequestFailed)
	}

	return &response, nil
}
func cfsslIsAvailable() bool {
	defaultRemote := client.NewServer(testRemote)

	infoReq := info.Req{
		Profile: testProfile,
		Label:   testLabel,
	}

	out, err := json.Marshal(infoReq)
	if err != nil {
		return false
	}

	_, err = defaultRemote.Info(out)
	if err != nil {
		log.Debug("CFSSL remote is unavailable, skipping tests")
		return false
	}

	return true
}
Exemple #28
0
// signerMain is the main CLI of signer functionality.
// [TODO: zi] Decide whether to drop the argument list and only use flags to specify all the inputs.
func signerMain(args []string) (err error) {
	// Grab values through args only if corresponding flags are absent
	if Config.hostname == "" {
		Config.hostname, args, err = popFirstArgument(args)
		if err != nil {
			return
		}
	}
	if Config.certFile == "" {
		Config.certFile, args, err = popFirstArgument(args)
		if err != nil {
			return
		}
	}

	// Read the certificate and sign it with CA files
	log.Debug("Loading Client certificate: ", Config.certFile)
	clientCert, err := ioutil.ReadFile(Config.certFile)
	if err != nil {
		return
	}

	var policy *config.Signing
	// If there is a config, use its signing policy. Otherwise, leave policy == nil
	// and NewSigner will use DefaultConfig().
	if Config.cfg != nil {
		policy = Config.cfg.Signing
	}

	signer, err := signer.NewSigner(Config.caFile, Config.caKeyFile, policy)
	if err != nil {
		return
	}
	cert, err := signer.Sign(Config.hostname, clientCert, Config.profile)
	if err != nil {
		return
	}
	fmt.Printf("%s", cert)
	return
}
Exemple #29
0
// BundleFromPEMorDER builds a certificate bundle from the set of byte
// slices containing the PEM or DER-encoded certificate(s), private key.
func (b *Bundler) BundleFromPEMorDER(certsRaw, keyPEM []byte, flavor BundleFlavor, password string) (*Bundle, error) {
	log.Debug("bundling from PEM files")
	var key crypto.Signer
	var err error
	if len(keyPEM) != 0 {
		key, err = helpers.ParsePrivateKeyPEM(keyPEM)
		if err != nil {
			log.Debugf("failed to parse private key: %v", err)
			return nil, err
		}
	}

	certs, err := helpers.ParseCertificatesPEM(certsRaw)
	if err != nil {
		// If PEM doesn't work try DER
		var keyDER crypto.Signer
		var errDER error
		certs, keyDER, errDER = helpers.ParseCertificatesDER(certsRaw, password)
		// Only use DER key if no key read from file
		if key == nil && keyDER != nil {
			key = keyDER
		}
		if errDER != nil {
			log.Debugf("failed to parse certificates: %v", err)
			// If neither parser works pass along PEM error
			return nil, err
		}

	}
	if len(certs) == 0 {
		log.Debugf("no certificates found")
		return nil, errors.New(errors.CertificateError, errors.DecodeFailed)
	}

	log.Debugf("bundle ready")
	return b.Bundle(certs, key, flavor)
}
Exemple #30
0
// BundleFromPEM builds a certificate bundle from the set of byte
// slices containing the PEM-encoded certificate(s), private key.
func (b *Bundler) BundleFromPEM(certsPEM, keyPEM []byte, flavor BundleFlavor) (*Bundle, error) {
	log.Debug("bundling from PEM files")
	var key interface{}
	var err error
	if len(keyPEM) != 0 {
		key, err = helpers.ParsePrivateKeyPEM(keyPEM)
		log.Debugf("failed to parse private key: %v", err)
		if err != nil {
			return nil, err
		}
	}

	certs, err := helpers.ParseCertificatesPEM(certsPEM)
	if err != nil {
		log.Debugf("failed to parse certificates: %v", err)
		return nil, err
	} else if len(certs) == 0 {
		log.Debugf("no certificates found")
		return nil, errors.New(errors.CertificateError, errors.DecodeFailed, nil)
	}

	log.Debugf("bundle ready")
	return b.Bundle(certs, key, flavor)
}