// GetRootCerts returns a byte array with the appropriate root certs
// for the given host:port string.
162874
func GetRootCerts(serverAddr string,
	certGetter func(host string) (certsBundle []byte, ok bool)) []byte {
	// Use the environment variable, if set.
	envTestRootCert := os.Getenv(EnvTestRootCertPEM)
	if len(envTestRootCert) != 0 {
		return []byte(envTestRootCert)
	}

	if host, _, err := net.SplitHostPort(serverAddr); err == nil {
		if rootCA, ok := certGetter(host); ok {
			return rootCA
		}
	}

	// Fall back to the test cert.
	return []byte(TestRootCert)
}
1315381
func getCachedCerts(c context.Context) (*signing.PublicCertificates, error) {
	v, err := certCache.Fetch(c, func(interface{}) (interface{}, time.Duration, error) {
		aeCerts, err := info.PublicCertificates(c)
		if err != nil {
			return nil, 0, err
		}
		certs := make([]signing.Certificate, len(aeCerts))
		for i, ac := range aeCerts {
			certs[i] = signing.Certificate{
				KeyName:            ac.KeyName,
				X509CertificatePEM: string(ac.Data),
			}
		}
		inf, err := getCachedInfo(c)
		if err != nil {
			return nil, 0, err
		}
		return &signing.PublicCertificates{
			AppID:              inf.AppID,
			ServiceAccountName: inf.ServiceAccountName,
			Certificates:       certs,
			Timestamp:          signing.JSONTime(clock.Now(c)),
		}, time.Hour, nil
	})
	if err != nil {
		return nil, err
	}
	return v.(*signing.PublicCertificates), nil
}
644910
func GetRemoteSignedCertificate(ctx context.Context, csr []byte, rootCAPool *x509.CertPool, config CertificateRequestConfig) ([]byte, error) {
	if rootCAPool == nil {
		return nil, errors.New("valid root CA pool required")
	}
	creds := config.Credentials

	if creds == nil {
		// This is our only non-MTLS request, and it happens when we are boostraping our TLS certs
		// We're using CARole as server name, so an external CA doesn't also have to have ManagerRole in the cert SANs
		creds = credentials.NewTLS(&tls.Config{ServerName: CARole, RootCAs: rootCAPool})
	}

	conn, err := getGRPCConnection(creds, config.ConnBroker, config.ForceRemote)
	if err != nil {
		return nil, err
	}

	// Create a CAClient to retrieve a new Certificate
	caClient := api.NewNodeCAClient(conn.ClientConn)

	issueCtx, issueCancel := context.WithTimeout(ctx, 5*time.Second)
	defer issueCancel()

	// Send the Request and retrieve the request token
	issueRequest := &api.IssueNodeCertificateRequest{CSR: csr, Token: config.Token, Availability: config.Availability}
	issueResponse, err := caClient.IssueNodeCertificate(issueCtx, issueRequest)
	if err != nil {
		conn.Close(false)
		return nil, err
	}

	statusRequest := &api.NodeCertificateStatusRequest{NodeID: issueResponse.NodeID}
	expBackoff := events.NewExponentialBackoff(events.ExponentialBackoffConfig{
		Base:   time.Second,
		Factor: time.Second,
		Max:    30 * time.Second,
	})

	// Exponential backoff with Max of 30 seconds to wait for a new retry
	for {
		timeout := 5 * time.Second
		if config.NodeCertificateStatusRequestTimeout > 0 {
			timeout = config.NodeCertificateStatusRequestTimeout
		}
		// Send the Request and retrieve the certificate
		stateCtx, cancel := context.WithTimeout(ctx, timeout)
		defer cancel()
		statusResponse, err := caClient.NodeCertificateStatus(stateCtx, statusRequest)
		s, _ := status.FromError(err)
		switch {
		case err != nil && s.Code() != codes.DeadlineExceeded:
			conn.Close(false)
			// Because IssueNodeCertificate succeeded, if this call failed likely it is due to an issue with this
			// particular connection, so we need to get another.  We should try a remote connection - the local node
			// may be a manager that was demoted, so the local connection (which is preferred) may not work.
			config.ForceRemote = true
			conn, err = getGRPCConnection(creds, config.ConnBroker, config.ForceRemote)
			if err != nil {
				return nil, err
			}
			caClient = api.NewNodeCAClient(conn.ClientConn)

		// If there was no deadline exceeded error, and the certificate was issued, return
		case err == nil && (statusResponse.Status.State == api.IssuanceStateIssued || statusResponse.Status.State == api.IssuanceStateRotate):
			if statusResponse.Certificate == nil {
				conn.Close(false)
				return nil, errors.New("no certificate in CertificateStatus response")
			}

			// The certificate in the response must match the CSR
			// we submitted. If we are getting a response for a
			// certificate that was previously issued, we need to
			// retry until the certificate gets updated per our
			// current request.
			if bytes.Equal(statusResponse.Certificate.CSR, csr) {
				conn.Close(true)
				return statusResponse.Certificate.Certificate, nil
			}
		}

		// If NodeCertificateStatus timed out, we're still pending, the issuance failed, or
		// the state is unknown let's continue trying after an exponential backoff
		expBackoff.Failure(nil, nil)
		select {
		case <-ctx.Done():
			conn.Close(true)
			return nil, err
		case <-time.After(expBackoff.Proceed(nil)):
		}
	}
}
1242655
func (m *Mounter) GetRootPath(mountPath string) (string, error) {
	m.Lock()
	defer m.Unlock()

	for _, v := range m.mounts {
		for _, p := range v.Mountpoint {
			if p.Path == mountPath {
				return p.Root, nil
			}
		}
	}
	return "", ErrEnoent
}
1103336
func DownloadRootCA(ctx context.Context, paths CertPaths, token string, connBroker *connectionbroker.Broker) (RootCA, error) {
	var rootCA RootCA
	// Get a digest for the optional CA hash string that we've been provided
	// If we were provided a non-empty string, and it is an invalid hash, return
	// otherwise, allow the invalid digest through.
	var (
		d   digest.Digest
		err error
	)
	if token != "" {
		parsed, err := ParseJoinToken(token)
		if err != nil {
			return RootCA{}, err
		}
		d = parsed.RootDigest
	}
	// Get the remote CA certificate, verify integrity with the
	// hash provided. Retry up to 5 times, in case the manager we
	// first try to contact is not responding properly (it may have
	// just been demoted, for example).

	for i := 0; i != 5; i++ {
		rootCA, err = GetRemoteCA(ctx, d, connBroker)
		if err == nil {
			break
		}
		log.G(ctx).WithError(err).Errorf("failed to retrieve remote root CA certificate")

		select {
		case <-time.After(GetCertRetryInterval):
		case <-ctx.Done():
			return RootCA{}, ctx.Err()
		}
	}
	if err != nil {
		return RootCA{}, err
	}

	// Save root CA certificate to disk
	if err = SaveRootCA(rootCA, paths); err != nil {
		return RootCA{}, err
	}

	log.G(ctx).Debugf("retrieved remote CA certificate: %s", paths.Cert)
	return rootCA, nil
}
1030564
func (s *CA) GetCertAuthorities(caType services.CertAuthType, loadSigningKeys bool, opts ...services.MarshalOption) ([]services.CertAuthority, error) {
	if err := caType.Check(); err != nil {
		return nil, trace.Wrap(err)
	}

	// Get all items in the bucket.
	startKey := backend.Key(authoritiesPrefix, string(caType))
	result, err := s.GetRange(context.TODO(), startKey, backend.RangeEnd(startKey), backend.NoLimit)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// Marshal values into a []services.CertAuthority slice.
	cas := make([]services.CertAuthority, len(result.Items))
	for i, item := range result.Items {
		ca, err := services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(
			item.Value, services.AddOptions(opts,
				services.WithResourceID(item.ID),
				services.WithExpires(item.Expires))...)
		if err != nil {
			return nil, trace.Wrap(err)
		}
		if err := ca.Check(); err != nil {
			return nil, trace.Wrap(err)
		}
		setSigningKeys(ca, loadSigningKeys)
		cas[i] = ca
	}

	return cas, nil
}
1035701
func (r Network_LoadBalancer_Global_Account) GetHosts() (resp []datatypes.Network_LoadBalancer_Global_Host, err error) {
	err = r.Session.DoRequest("SoftLayer_Network_LoadBalancer_Global_Account", "getHosts", nil, &r.Options, &resp)
	return
}
337007
func importRootCert(certFilePath string) ([]data.PublicKey, error) {
	publicKeys := make([]data.PublicKey, 0, 1)

	if certFilePath == "" {
		return publicKeys, nil
	}

	// read certificate from file
	certPEM, err := ioutil.ReadFile(certFilePath)
	if err != nil {
		return nil, fmt.Errorf("error reading certificate file: %v", err)
	}
	block, _ := pem.Decode([]byte(certPEM))
	if block == nil {
		return nil, fmt.Errorf("the provided file does not contain a valid PEM certificate %v", err)
	}

	// convert the file to data.PublicKey
	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		return nil, fmt.Errorf("Parsing certificate PEM bytes to x509 certificate: %v", err)
	}
	publicKeys = append(publicKeys, tufutils.CertToKey(cert))

	return publicKeys, nil
}
617499
func (_class HostClass) GetHostCPUs(sessionID SessionRef, self HostRef) (_retval []HostCPURef, _err error) {
	_method := "host.get_host_CPUs"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertHostRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertHostCPURefSetToGo(_method + " -> ", _result.Value)
	return
}
22981
func getOldRootPublicKeys(root *data.SignedRoot) data.KeyList {
	rootRole, err := root.BuildBaseRole(data.CanonicalRootRole)
	if err != nil {
		return nil
	}
	return rootRole.ListKeys()
}
877981
func (ts *TrustStore) Certificates() []*x509.Certificate {
	var roots = make([]*x509.Certificate, 0, len(ts.roots))
	for _, cert := range ts.roots {
		roots = append(roots, cert)
	}
	return roots
}
1267231
func (cas *CASupport) GetClientRootCAs() (appRootCAs, ordererRootCAs [][]byte) {
	cas.RLock()
	defer cas.RUnlock()

	appRootCAs = [][]byte{}
	ordererRootCAs = [][]byte{}

	for _, appRootCA := range cas.AppRootCAsByChain {
		appRootCAs = append(appRootCAs, appRootCA...)
	}

	for _, ordererRootCA := range cas.OrdererRootCAsByChain {
		ordererRootCAs = append(ordererRootCAs, ordererRootCA...)
	}

	// also need to append statically configured root certs
	appRootCAs = append(appRootCAs, cas.ClientRootCAs...)
	return appRootCAs, ordererRootCAs
}
1284801
func (cfg *dynamicTLSConfig) Roots() *x509.CertPool {
	cfg.RLock()
	defer cfg.RUnlock()
	return cfg.roots
}
144824
func RootCAs(file ...string) Option {
	return func(o *Options) error {
		pool := x509.NewCertPool()
		for _, f := range file {
			rootPEM, err := ioutil.ReadFile(f)
			if err != nil || rootPEM == nil {
				return fmt.Errorf("nats: error loading or parsing rootCA file: %v", err)
			}
			ok := pool.AppendCertsFromPEM(rootPEM)
			if !ok {
				return fmt.Errorf("nats: failed to parse root certificate from %q", f)
			}
		}
		if o.TLSConfig == nil {
			o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
		}
		o.TLSConfig.RootCAs = pool
		o.Secure = true
		return nil
	}
}
1123588
func (api *ProxyLBAPI) GetCertificates(id int64) (*sacloud.ProxyLBCertificates, error) {
	var (
		method = "GET"
		uri    = fmt.Sprintf("%s/%d/proxylb/sslcertificate", api.getResourceURL(), id)
		res    = &proxyLBCertificateResponse{}
	)
	err := api.baseAPI.request(method, uri, nil, res)
	if err != nil {
		return nil, err
	}
	if res.ProxyLB == nil {
		return nil, nil
	}
	return res.ProxyLB, nil
}
595500
func parseAllCerts(signedRoot *data.SignedRoot) (map[string]*x509.Certificate, map[string][]*x509.Certificate) {
	if signedRoot == nil {
		return nil, nil
	}

	leafCerts := make(map[string]*x509.Certificate)
	intCerts := make(map[string][]*x509.Certificate)

	// Before we loop through all root keys available, make sure any exist
	rootRoles, ok := signedRoot.Signed.Roles[data.CanonicalRootRole]
	if !ok {
		logrus.Debugf("tried to parse certificates from invalid root signed data")
		return nil, nil
	}

	logrus.Debugf("found the following root keys: %v", rootRoles.KeyIDs)
	// Iterate over every keyID for the root role inside of roots.json
	for _, keyID := range rootRoles.KeyIDs {
		// check that the key exists in the signed root keys map
		key, ok := signedRoot.Signed.Keys[keyID]
		if !ok {
			logrus.Debugf("error while getting data for keyID: %s", keyID)
			continue
		}

		// Decode all the x509 certificates that were bundled with this
		// Specific root key
		decodedCerts, err := utils.LoadCertBundleFromPEM(key.Public())
		if err != nil {
			logrus.Debugf("error while parsing root certificate with keyID: %s, %v", keyID, err)
			continue
		}

		// Get all non-CA certificates in the decoded certificates
		leafCertList := utils.GetLeafCerts(decodedCerts)

		// If we got no leaf certificates or we got more than one, fail
		if len(leafCertList) != 1 {
			logrus.Debugf("invalid chain due to leaf certificate missing or too many leaf certificates for keyID: %s", keyID)
			continue
		}
		// If we found a leaf certificate, assert that the cert bundle started with a leaf
		if decodedCerts[0].IsCA {
			logrus.Debugf("invalid chain due to leaf certificate not being first certificate for keyID: %s", keyID)
			continue
		}

		// Get the ID of the leaf certificate
		leafCert := leafCertList[0]

		// Store the leaf cert in the map
		leafCerts[key.ID()] = leafCert

		// Get all the remainder certificates marked as a CA to be used as intermediates
		intermediateCerts := utils.GetIntermediateCerts(decodedCerts)
		intCerts[key.ID()] = intermediateCerts
	}

	return leafCerts, intCerts
}
744553
func GetLocalRootCA(paths CertPaths) (RootCA, error) {
	// Check if we have a Certificate file
	cert, err := ioutil.ReadFile(paths.Cert)
	if err != nil {
		if os.IsNotExist(err) {
			err = ErrNoLocalRootCA
		}

		return RootCA{}, err
	}
	signingCert := cert

	key, err := ioutil.ReadFile(paths.Key)
	if err != nil {
		if !os.IsNotExist(err) {
			return RootCA{}, err
		}
		// There may not be a local key. It's okay to pass in a nil
		// key. We'll get a root CA without a signer.
		key = nil
		signingCert = nil
	}

	return NewRootCA(cert, signingCert, key, DefaultNodeCertExpiration, nil)
}