// ReplaceCACertificatesAndCRLs replaces the trusted CA certificates and CRL used by the host system.
// These determine whether the server can verify the identity of an external entity.
14934
func (m HostCertificateManager) ReplaceCACertificatesAndCRLs(ctx context.Context, caCert []string, caCrl []string) error {
	req := types.ReplaceCACertificatesAndCRLs{
		This:   m.Reference(),
		CaCert: caCert,
		CaCrl:  caCrl,
	}

	_, err := methods.ReplaceCACertificatesAndCRLs(ctx, m.Client(), &req)
	return err
}
400535
func (gServer *GRPCServer) removeClientRootCA(clientRoot []byte) error {

	errMsg := "Failed to remove client root certificate(s): %s"
	//convert to x509
	certs, subjects, err := pemToX509Certs(clientRoot)
	if err != nil {
		return fmt.Errorf(errMsg, err.Error())
	}

	if len(certs) < 1 {
		return fmt.Errorf(errMsg, "No client root certificates found")
	}

	for i, subject := range subjects {
		//remove it from our clientRootCAs map using subject as key
		//check to see if we have match
		if certs[i].Equal(gServer.clientRootCAs[subject]) {
			delete(gServer.clientRootCAs, subject)
		}
	}
	return nil
}
1345829
func (s *PendingModifiedValues) SetCACertificateIdentifier(v string) *PendingModifiedValues {
	s.CACertificateIdentifier = &v
	return s
}
632206
func (p *PUPolicy) ServiceCertificates() (string, string, string) {
	p.Lock()
	defer p.Unlock()

	return p.servicesCertificate, p.servicesPrivateKey, p.servicesCA
}
180762
func (s *ModifyClusterInput) SetHsmClientCertificateIdentifier(v string) *ModifyClusterInput {
	s.HsmClientCertificateIdentifier = &v
	return s
}
178099
func (rca *RootCA) CrossSignCACertificate(otherCAPEM []byte) ([]byte, error) {
	signer, err := rca.Signer()
	if err != nil {
		return nil, err
	}

	// create a new cert with exactly the same parameters, including the public key and exact NotBefore and NotAfter
	template, err := helpers.ParseCertificatePEM(otherCAPEM)
	if err != nil {
		return nil, errors.New("could not parse new CA certificate")
	}

	if !template.IsCA {
		return nil, errors.New("certificate not a CA")
	}

	template.SignatureAlgorithm = signer.parsedCert.SignatureAlgorithm // make sure we can sign with the signer key
	derBytes, err := x509.CreateCertificate(cryptorand.Reader, template, signer.parsedCert, template.PublicKey, signer.cryptoSigner)
	if err != nil {
		return nil, errors.Wrap(err, "could not cross-sign new CA certificate using old CA material")
	}

	return pem.EncodeToMemory(&pem.Block{
		Type:  "CERTIFICATE",
		Bytes: derBytes,
	}), nil
}
276729
func NewCFSSL(metadata map[string]string) ([]*x509.Certificate, error) {
	host, ok := metadata["host"]
	if !ok {
		return nil, errors.New("transport: CFSSL root provider requires a host")
	}

	label := metadata["label"]
	profile := metadata["profile"]
	cert, err := helpers.LoadClientCertificate(metadata["mutual-tls-cert"], metadata["mutual-tls-key"])
	if err != nil {
		return nil, err
	}
	remoteCAs, err := helpers.LoadPEMCertPool(metadata["tls-remote-ca"])
	if err != nil {
		return nil, err
	}
	srv := client.NewServerTLS(host, helpers.CreateTLSConfig(remoteCAs, cert))
	data, err := json.Marshal(info.Req{Label: label, Profile: profile})
	if err != nil {
		return nil, err
	}

	resp, err := srv.Info(data)
	if err != nil {
		return nil, err
	}

	return helpers.ParseCertificatesPEM([]byte(resp.Certificate))
}
996132
func replaceCustomError(m metaContext, state scriptState, spec *errorT, err1 libkb.ProofError) libkb.ProofError {
	if err1 == nil {
		return err1
	}

	// Don't rewrite invalid_pvl errors
	if err1.GetProofStatus() == keybase1.ProofStatus_INVALID_PVL {
		return err1
	}

	if spec == nil {
		return err1
	}

	if (spec.Status != err1.GetProofStatus()) || (spec.Description != err1.GetDesc()) {
		newDesc := spec.Description
		subbedDesc, subErr := substituteExact(spec.Description, state)
		if subErr == nil {
			newDesc = subbedDesc
		}
		err2 := libkb.NewProofError(spec.Status, newDesc)
		debugWithState(m, state, "Replacing error with custom error")
		debugWithStateError(m, state, err2)

		return err2
	}
	return err1
}
146996
func PutCertificateRevocationList(d Depot, name string, crl *pkix.CertificateRevocationList) error {
	b, err := crl.Export()
	if err != nil {
		return err
	}
	return d.Put(CrlTag(name), b)
}
214911
func (rootCA *RootCA) NewClientTLSCredentials(cert *tls.Certificate, serverName string) (*MutableTLSCreds, error) {
	tlsConfig, err := NewClientTLSConfig([]tls.Certificate{*cert}, rootCA.Pool, serverName)
	if err != nil {
		return nil, err
	}

	mtls, err := NewMutableTLS(tlsConfig)

	return mtls, err
}
616145
func (c *ClientsetSecretStore) ReplaceSecret(name string, secret *fi.Secret) (*fi.Secret, error) {
	_, err := c.createSecret(secret, name, true)
	if err != nil {
		return nil, fmt.Errorf("unable to write secret: %v", err)
	}

	// Confirm the secret exists
	s, err := c.loadSecret(name)
	if err != nil {
		return nil, fmt.Errorf("unable to load secret immediately after creation: %v", err)
	}
	return s, nil
}
943474
func (c *CertAuthorityV2) TLSCA() (*tlsca.CertAuthority, error) {
	if len(c.Spec.TLSKeyPairs) == 0 {
		return nil, trace.BadParameter("no TLS key pairs found for certificate authority")
	}
	return tlsca.New(c.Spec.TLSKeyPairs[0].Cert, c.Spec.TLSKeyPairs[0].Key)
}
1027049
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
}
550019
func (c *IdentityConfig) CAConfig(org string) (*msp.CAConfig, bool) {
	caConfigs, ok := c.caConfigsByOrg[strings.ToLower(org)]
	if ok {
		//for now, we're only loading the first Cert Authority by default.
		return caConfigs[0], true
	}
	return nil, false
}
1057066
func (a *AuthServer) RotateExternalCertAuthority(ca services.CertAuthority) error {
	if ca == nil {
		return trace.BadParameter("missing certificate authority")
	}
	clusterName, err := a.GetClusterName()
	if err != nil {
		return trace.Wrap(err)
	}

	// this is just an extra precaution against local admins,
	// because this is additionally enforced by RBAC as well
	if ca.GetClusterName() == clusterName.GetClusterName() {
		return trace.BadParameter("can not rotate local certificate authority")
	}

	existing, err := a.Trust.GetCertAuthority(services.CertAuthID{
		Type:       ca.GetType(),
		DomainName: ca.GetClusterName(),
	}, false)
	if err != nil {
		return trace.Wrap(err)
	}

	updated := existing.Clone()
	updated.SetCheckingKeys(ca.GetCheckingKeys())
	updated.SetTLSKeyPairs(ca.GetTLSKeyPairs())
	updated.SetRotation(ca.GetRotation())

	// use compare and swap to protect from concurrent updates
	// by trusted cluster API
	if err := a.CompareAndSwapCertAuthority(updated, existing); err != nil {
		return trace.Wrap(err)
	}

	return nil
}
300220
func filterExternalCAURLS(ctx context.Context, desiredCert, defaultCert []byte, apiExternalCAs []*api.ExternalCA) (urls []string) {
	desiredCert = NormalizePEMs(desiredCert)

	// TODO(aaronl): In the future, this will be abstracted with an ExternalCA interface that has different
	// implementations for different CA types. At the moment, only CFSSL is supported.
	for i, extCA := range apiExternalCAs {
		// We want to support old external CA specifications which did not have a CA cert.  If there is no cert specified,
		// we assume it's the old cert
		certForExtCA := extCA.CACert
		if len(certForExtCA) == 0 {
			certForExtCA = defaultCert
		}
		certForExtCA = NormalizePEMs(certForExtCA)
		if extCA.Protocol != api.ExternalCA_CAProtocolCFSSL {
			log.G(ctx).Debugf("skipping external CA %d (url: %s) due to unknown protocol type", i, extCA.URL)
			continue
		}
		if !bytes.Equal(certForExtCA, desiredCert) {
			log.G(ctx).Debugf("skipping external CA %d (url: %s) because it has the wrong CA cert", i, extCA.URL)
			continue
		}
		urls = append(urls, extCA.URL)
	}
	return
}
1002402
func LoadCertificates(path string) ([]*x509.Certificate, error) {
	in, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	return ReadCertificates(in)
}