// CertPoolFromFile returns an x509.CertPool containing the certificates
// in the given PEM-encoded file.
// Returns an error if the file could not be read, a certificate could not
// be parsed, or if the file does not contain any certificates
960877
func CertPoolFromFile(filename string) (*x509.CertPool, error) {
	b, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, fmt.Errorf("can't read CA file: %v", filename)
	}
	cp := x509.NewCertPool()
	if !cp.AppendCertsFromPEM(b) {
		return nil, fmt.Errorf("failed to append certificates from file: %s", filename)
	}
	return cp, nil
}
218845
func LoadCAPath(path string) (*x509.CertPool, error) {
	result := x509.NewCertPool()

	// filepath.WalkFunc to traverse the directory structure, starting from input path
	// attempting to load certs into result in the process
	appendCerts := func(path string, info os.FileInfo, err error) error {
		// cascade errors to the end of the traversal,
		//  we fail early if there are files other than certs under path
		if err != nil {
			return err
		}

		// ignore dirs
		if info.IsDir() {
			return nil
		}

		// try and append certs from files
		if err := appendPEMCertsFromPath(result, path); err != nil {
			// fail if we can't append PEM certs or get no PEM certs from a file
			return err
		}

		return nil
	}

	// if we error while walking with appendCerts, don't return any certs
	if err := filepath.Walk(path, appendCerts); err != nil {
		return nil, err
	}

	return result, nil
}
1166174
func (rp RawProfile) TCPoolProfile() (TCPoolProfile, error) {
	var result TCPoolProfile
	c := rp.Context()
	if c != TCPoolSchema {
		return result, fmt.Errorf("incorrect JSON-LD @context for TCPoolProfile %s", c)
	}
	err := decodeProfile(rp, &result)
	return result, err
}
557036
func TempCertFile() (string, error) {
	f, err := ioutil.TempFile("", "zenoss_cert.")
	if err != nil {
		return "", err
	}
	defer f.Close()
	fmt.Fprint(f, InsecureCertPEM)
	return f.Name(), nil
}
750480
func TryLoadCertFromDisk(pkiPath, name string) (*x509.Certificate, error) {
	certificatePath := pathForCert(pkiPath, name)

	certs, err := certutil.CertsFromFile(certificatePath)
	if err != nil {
		return nil, errors.Wrapf(err, "couldn't load the certificate file %s", certificatePath)
	}

	// We are only putting one certificate in the certificate pem file, so it's safe to just pick the first one
	// TODO: Support multiple certs here in order to be able to rotate certs
	cert := certs[0]

	// Check so that the certificate is valid now
	now := time.Now()
	if now.Before(cert.NotBefore) {
		return nil, errors.New("the certificate is not valid yet")
	}
	if now.After(cert.NotAfter) {
		return nil, errors.New("the certificate has expired")
	}

	return cert, nil
}
1103289
func readKeyFromFile(localKeyFile string) ([]byte, error) {
	// Read in the cert file
	key, err := ioutil.ReadFile(localKeyFile)
	if err != nil {
		return nil, err
	}
	return key, nil
}
113877
func (p *Signing) SetRemoteCAsFromFile(caFile string) error {
	if caFile != "" {
		remoteCAs, err := helpers.LoadPEMCertPool(caFile)
		if err != nil {
			return err
		}
		p.SetRemoteCAs(remoteCAs)
	}
	return nil
}
1101957
func loadCAPool(path string) (*x509.CertPool, error) {
	caPool := x509.NewCertPool()
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	b, err := ioutil.ReadAll(f)
	if err != nil {
		return nil, err
	}

	if !caPool.AppendCertsFromPEM(b) {
		return nil, errors.New("CACertFile parsing failed")
	}

	return caPool, nil
}
875646
func LoadCAPath(caPath string) (*x509.CertPool, error) {
	pool := x509.NewCertPool()
	walkFn := func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if info.IsDir() {
			return nil
		}

		pem, err := ioutil.ReadFile(path)
		if err != nil {
			return fmt.Errorf("Error loading file from CAPath: %s", err)
		}

		ok := pool.AppendCertsFromPEM(pem)
		if !ok {
			return fmt.Errorf("Error loading CA Path: Couldn't parse PEM in: %s", path)
		}

		return nil
	}

	err := filepath.Walk(caPath, walkFn)
	if err != nil {
		return nil, err
	}

	return pool, nil
}
1072492
func GetCertFiles(certFile, keyFile string) (string, string) {

	// set the cert file if it doesn't exist
	if certFile == "" {
		var err error
		certFile, err = proxy.TempCertFile()
		if err != nil {
			plog.WithError(err).Fatal("Could not create temp cert file")
		}
	}

	// set the key file if it doesn't exist
	if keyFile == "" {
		var err error
		keyFile, err = proxy.TempKeyFile()
		if err != nil {
			plog.WithError(err).Fatal("Could not create temp key file")
		}
	}

	return certFile, keyFile
}
655232
func LoadAndVerifyCertificate(certPEM []byte, roots *x509.CertPool) (*x509.Certificate, error) {

	cert, err := LoadCertificate(certPEM)
	if err != nil {
		return nil, err
	}

	opts := x509.VerifyOptions{
		Roots: roots,
	}

	if _, err := cert.Verify(opts); err != nil {
		return nil, err
	}

	return cert, nil

}
556395
func LoadCert(filename string) (cert *x509.Certificate, err error) {
	certPEM, err := ioutil.ReadFile(filename)
	if err != nil {
		return
	}
	block, _ := pem.Decode(certPEM)
	if block == nil {
		return nil, fmt.Errorf("No data in cert PEM file %s", filename)
	}
	cert, err = x509.ParseCertificate(block.Bytes)
	return
}
247699
func tokenFromFile(say func(string), oauthCfg adal.OAuthConfig, tokenPath, clientID, resource string,
	callback adal.TokenRefreshCallback) (*adal.ServicePrincipalToken, error) {
	say(fmt.Sprintf("Loading auth token from file: %s", tokenPath))
	if _, err := os.Stat(tokenPath); err != nil {
		if os.IsNotExist(err) { // file not found
			return nil, nil
		}
		return nil, err
	}

	token, err := adal.LoadToken(tokenPath)
	if err != nil {
		return nil, fmt.Errorf("Failed to load token from file: %v", err)
	}

	spt, err := adal.NewServicePrincipalTokenFromManualToken(oauthCfg, clientID, resource, *token, callback)
	if err != nil {
		return nil, fmt.Errorf("Error constructing service principal token: %v", err)
	}
	return spt, nil
}
710605
func (fs *FSLocalKeyStore) GetCerts(proxy string) (*x509.CertPool, error) {
	dir, err := fs.dirFor(proxy, false)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	bytes, err := ioutil.ReadFile(filepath.Join(dir, fileNameTLSCerts))
	if err != nil {
		return nil, trace.ConvertSystemError(err)
	}
	pool := x509.NewCertPool()
	for len(bytes) > 0 {
		var block *pem.Block
		block, bytes = pem.Decode(bytes)
		if block == nil {
			break
		}
		if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
			fs.log.Debugf("Skipping PEM block type=%v headers=%v.", block.Type, block.Headers)
			continue
		}

		cert, err := x509.ParseCertificate(block.Bytes)
		if err != nil {
			return nil, trace.BadParameter("failed to parse certificate: %v", err)
		}
		fs.log.Debugf("Adding trusted cluster certificate authority %q to trusted pool.", cert.Issuer)
		pool.AddCert(cert)
	}
	return pool, nil
}
1089171
func ClientCertPool(client AccessCache, clusterName string) (*x509.CertPool, error) {
	pool := x509.NewCertPool()
	var authorities []services.CertAuthority
	if clusterName == "" {
		hostCAs, err := client.GetCertAuthorities(services.HostCA, false, services.SkipValidation())
		if err != nil {
			return nil, trace.Wrap(err)
		}
		userCAs, err := client.GetCertAuthorities(services.UserCA, false, services.SkipValidation())
		if err != nil {
			return nil, trace.Wrap(err)
		}
		authorities = append(authorities, hostCAs...)
		authorities = append(authorities, userCAs...)
	} else {
		hostCA, err := client.GetCertAuthority(
			services.CertAuthID{Type: services.HostCA, DomainName: clusterName},
			false, services.SkipValidation())
		if err != nil {
			return nil, trace.Wrap(err)
		}
		userCA, err := client.GetCertAuthority(
			services.CertAuthID{Type: services.UserCA, DomainName: clusterName},
			false, services.SkipValidation())
		if err != nil {
			return nil, trace.Wrap(err)
		}
		authorities = append(authorities, hostCA)
		authorities = append(authorities, userCA)
	}

	for _, auth := range authorities {
		for _, keyPair := range auth.GetTLSKeyPairs() {
			cert, err := tlsca.ParseCertificatePEM(keyPair.Cert)
			if err != nil {
				return nil, trace.Wrap(err)
			}
			log.Debugf("ClientCertPool -> %v", CertInfo(cert))
			pool.AddCert(cert)
		}
	}
	return pool, nil
}
479492
func (c *ClientsetCAStore) FindCertificatePool(name string) (*CertificatePool, error) {
	keyset, err := c.loadKeyset(name)
	if err != nil {
		return nil, err
	}

	pool := &CertificatePool{}

	if keyset != nil {
		if keyset.primary != nil {
			pool.Primary = keyset.primary.certificate
		}

		for id, item := range keyset.items {
			if id == keyset.primary.id {
				continue
			}
			pool.Secondary = append(pool.Secondary, item.certificate)
		}
	}
	return pool, nil
}
1159753
func NewCertificateFromPEM(data []byte) (c *Certificate, err error) {
	pemBlock, _ := pem.Decode(data)
	if pemBlock == nil {
		err = errors.New("cannot find the next PEM formatted block")
		return
	}
	if pemBlock.Type != certificatePEMBlockType || len(pemBlock.Headers) != 0 {
		err = errors.New("unmatched type or headers")
		return
	}
	c = &Certificate{derBytes: pemBlock.Bytes}
	return
}