// determines whether an api.RootCA, api.RootRotation, or api.CAConfig has a signing key (local signer)
422958
func hasSigningKey(a interface{}) bool {
	switch b := a.(type) {
	case *api.RootCA:
		return len(b.CAKey) > 0
	case *api.RootRotation:
		return b != nil && len(b.CAKey) > 0
	case *api.CAConfig:
		return len(b.SigningCACert) > 0 && len(b.SigningCAKey) > 0
	default:
		panic("needsExternalCAs should be called something of type *api.RootCA, *api.RootRotation, or *api.CAConfig")
	}
}
740182
func signingKey(clientSecret string, timestamp string) []byte {
	h := hmac.New(sha256.New, []byte(clientSecret))
	h.Write([]byte(timestamp))
	key := make([]byte, base64.StdEncoding.EncodedLen(32))
	base64.StdEncoding.Encode(key, h.Sum(nil))
	return key
}
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
	}
}
590606
func makeRootMetadataSigned(sigInfo, writerSigInfo kbfscrypto.SignatureInfo,
	md RootMetadata) (*RootMetadataSigned, error) {
	rmds := &RootMetadataSigned{
		MD:            md,
		SigInfo:       sigInfo,
		WriterSigInfo: writerSigInfo,
	}
	err := checkWriterSig(rmds)
	if err != nil {
		return nil, err
	}
	return rmds, nil
}
670771
func (md *RootMetadata) HasKeyForUser(user keybase1.UID) (
	bool, error) {
	writers, readers, err := md.bareMd.GetUserDevicePublicKeys(md.extra)
	if err != nil {
		return false, err
	}
	return len(writers[user]) > 0 || len(readers[user]) > 0, nil
}
453343
func (rca *RootCA) IssueAndSaveNewCertificates(kw KeyWriter, cn, ou, org string) (*tls.Certificate, *IssuerInfo, error) {
	csr, key, err := GenerateNewCSR()
	if err != nil {
		return nil, nil, errors.Wrap(err, "error when generating new node certs")
	}

	// Obtain a signed Certificate
	certChain, err := rca.ParseValidateAndSignCSR(csr, cn, ou, org)
	if err != nil {
		return nil, nil, errors.Wrap(err, "failed to sign node certificate")
	}
	signer, err := rca.Signer()
	if err != nil { // should never happen, since if ParseValidateAndSignCSR did not fail this root CA must have a signer
		return nil, nil, err
	}

	// Create a valid TLSKeyPair out of the PEM encoded private key and certificate
	tlsKeyPair, err := tls.X509KeyPair(certChain, key)
	if err != nil {
		return nil, nil, err
	}

	if err := kw.Write(NormalizePEMs(certChain), key, nil); err != nil {
		return nil, nil, err
	}

	return &tlsKeyPair, &IssuerInfo{
		PublicKey: signer.parsedCert.RawSubjectPublicKeyInfo,
		Subject:   signer.parsedCert.RawSubject,
	}, nil
}
1169375
func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
	// RFC 5280, 4.2.1.9:
	// "If the basic constraints extension is not present in a version 3
	// certificate, or the extension is present but the cA boolean is not
	// asserted, then the certified public key MUST NOT be used to verify
	// certificate signatures."
	// (except for Entrust, see comment above entrustBrokenSPKI)
	if (parent.Version == 3 && !parent.BasicConstraintsValid ||
		parent.BasicConstraintsValid && !parent.IsCA) &&
		!bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
		return ConstraintViolationError{}
	}

	if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
		return ConstraintViolationError{}
	}

	if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
		return ErrUnsupportedAlgorithm
	}

	// TODO(agl): don't ignore the path length constraint.

	return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
}
263593
func doesSignatureMatch(hashedPayload string, r *http.Request, region string, stype serviceType) APIErrorCode {
	// Copy request.
	req := *r

	// Save authorization header.
	v4Auth := req.Header.Get("Authorization")

	// Parse signature version '4' header.
	signV4Values, err := parseSignV4(v4Auth, region, stype)
	if err != ErrNone {
		return err
	}

	// Extract all the signed headers along with its values.
	extractedSignedHeaders, errCode := extractSignedHeaders(signV4Values.SignedHeaders, r)
	if errCode != ErrNone {
		return errCode
	}

	cred, _, s3Err := checkKeyValid(signV4Values.Credential.accessKey)
	if s3Err != ErrNone {
		return s3Err
	}

	// Extract date, if not present throw error.
	var date string
	if date = req.Header.Get(http.CanonicalHeaderKey("x-amz-date")); date == "" {
		if date = r.Header.Get("Date"); date == "" {
			return ErrMissingDateHeader
		}
	}

	// Parse date header.
	t, e := time.Parse(iso8601Format, date)
	if e != nil {
		return ErrMalformedDate
	}

	// Query string.
	queryStr := req.URL.Query().Encode()

	// Get canonical request.
	canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, queryStr, req.URL.Path, req.Method)

	// Get string to sign from canonical request.
	stringToSign := getStringToSign(canonicalRequest, t, signV4Values.Credential.getScope())

	// Get hmac signing key.
	signingKey := getSigningKey(cred.SecretKey, signV4Values.Credential.scope.date,
		signV4Values.Credential.scope.region, stype)

	// Calculate signature.
	newSignature := getSignature(signingKey, stringToSign)

	// Verify if signature match.
	if !compareSignatureV4(newSignature, signV4Values.Signature) {
		return ErrSignatureDoesNotMatch
	}

	// Return error none.
	return ErrNone
}
963105
func (ctx *signingCtx) isRequestSigned() bool {
	if ctx.isPresign && ctx.Query.Get("X-Amz-Signature") != "" {
		return true
	}
	if ctx.Request.Header.Get("Authorization") != "" {
		return true
	}

	return false
}
554415
func (e *Signer) signConfigMap() {
	origCM := e.getConfigMap()

	if origCM == nil {
		return
	}

	var needUpdate = false

	newCM := origCM.DeepCopy()

	// First capture the config we are signing
	content, ok := newCM.Data[bootstrapapi.KubeConfigKey]
	if !ok {
		klog.V(3).Infof("No %s key in %s/%s ConfigMap", bootstrapapi.KubeConfigKey, origCM.Namespace, origCM.Name)
		return
	}

	// Next remove and save all existing signatures
	sigs := map[string]string{}
	for key, value := range newCM.Data {
		if strings.HasPrefix(key, bootstrapapi.JWSSignatureKeyPrefix) {
			tokenID := strings.TrimPrefix(key, bootstrapapi.JWSSignatureKeyPrefix)
			sigs[tokenID] = value
			delete(newCM.Data, key)
		}
	}

	// Now recompute signatures and store them on the new map
	tokens := e.getTokens()
	for tokenID, tokenValue := range tokens {
		sig, err := computeDetachedSig(content, tokenID, tokenValue)
		if err != nil {
			utilruntime.HandleError(err)
		}

		// Check to see if this signature is changed or new.
		oldSig, _ := sigs[tokenID]
		if sig != oldSig {
			needUpdate = true
		}
		delete(sigs, tokenID)

		newCM.Data[bootstrapapi.JWSSignatureKeyPrefix+tokenID] = sig
	}

	// If we have signatures left over we know that some signatures were
	// removed.  We now need to update the ConfigMap
	if len(sigs) != 0 {
		needUpdate = true
	}

	if needUpdate {
		e.updateConfigMap(newCM)
	}
}
1093352
func IsAuthenticationError(err error) bool {
	cause := errors.Cause(err)
	if kvErr, ok := cause.(KeyValueError); ok && kvErr.KVError() {
		return kvErr.StatusCode() == int(gocbcore.StatusAuthError)
	}

	return false
}
1330272
func (p *SigningProfile) hasLocalConfig() bool {
	if p.Usage != nil ||
		p.IssuerURL != nil ||
		p.OCSP != "" ||
		p.ExpiryString != "" ||
		p.BackdateString != "" ||
		p.CAConstraint.IsCA != false ||
		!p.NotBefore.IsZero() ||
		!p.NotAfter.IsZero() ||
		p.NameWhitelistString != "" ||
		len(p.CTLogServers) != 0 {
		return true
	}
	return false
}
602373
func (arc *ConfigFactory) GetConfigurationByKeyAndDimensionInfo(dimensionInfo, key string) interface{} {
	if arc.initSuccess == false {
		return nil
	}

	return arc.configMgr.GetConfigurationsByKeyAndDimensionInfo(dimensionInfo, key)
}
1273932
func (d *discoveryDoc) signingKeys(c context.Context) (*JSONWebKeySet, error) {
	fetcher := func() (interface{}, time.Duration, error) {
		raw := &JSONWebKeySetStruct{}
		req := internal.Request{
			Method: "GET",
			URL:    d.JwksURI,
			Out:    raw,
		}
		if err := req.Do(c); err != nil {
			return nil, 0, err
		}
		keys, err := NewJSONWebKeySet(raw)
		if err != nil {
			return nil, 0, err
		}
		return keys, time.Hour * 6, nil
	}

	cached, err := signingKeysCache.LRU(c).GetOrCreate(c, d.JwksURI, fetcher)
	if err != nil {
		return nil, err
	}
	return cached.(*JSONWebKeySet), nil
}
1094704
func httpClientForRootCAs(rootCAs string) (*http.Client, error) {
	tlsConfig := tls.Config{RootCAs: x509.NewCertPool()}
	rootCABytes, err := ioutil.ReadFile(rootCAs)
	if err != nil {
		return nil, fmt.Errorf("failed to read root-ca: %v", err)
	}
	if !tlsConfig.RootCAs.AppendCertsFromPEM(rootCABytes) {
		return nil, fmt.Errorf("no certs found in root CA file %q", rootCAs)
	}
	return &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tlsConfig,
			Proxy:           http.ProxyFromEnvironment,
			Dial: (&net.Dialer{
				Timeout:   30 * time.Second,
				KeepAlive: 30 * time.Second,
			}).Dial,
			TLSHandshakeTimeout:   10 * time.Second,
			ExpectContinueTimeout: 1 * time.Second,
		},
	}, nil
}
1337346
func RootFromSigned(s *Signed) (*SignedRoot, error) {
	r := Root{}
	if s.Signed == nil {
		return nil, ErrInvalidMetadata{
			role: CanonicalRootRole,
			msg:  "root file contained an empty payload",
		}
	}
	if err := defaultSerializer.Unmarshal(*s.Signed, &r); err != nil {
		return nil, err
	}
	if err := isValidRootStructure(r); err != nil {
		return nil, err
	}
	sigs := make([]Signature, len(s.Signatures))
	copy(sigs, s.Signatures)
	return &SignedRoot{
		Signatures: sigs,
		Signed:     r,
	}, nil
}
422544
func (ks *Keystore) TrustedKeyPrefixExists(prefix string) (bool, error) {
	acidentifier, err := types.NewACIdentifier(prefix)
	if err != nil {
		return false, err
	}

	pathNamesPrefix := []string{
		// example: /etc/rkt/trustedkeys/prefix.d/coreos.com/etcd
		path.Join(ks.LocalPrefixPath, acidentifier.String()),
		// example: /usr/lib/rkt/trustedkeys/prefix.d/coreos.com/etcd
		path.Join(ks.SystemPrefixPath, acidentifier.String()),
	}

	for _, p := range pathNamesPrefix {
		_, err := os.Stat(p)
		if os.IsNotExist(err) {
			continue
		}
		if err != nil {
			return false, errwrap.Wrap(fmt.Errorf("cannot check dir %q", p), err)
		}
		files, err := ioutil.ReadDir(p)
		if err != nil {
			return false, errwrap.Wrap(fmt.Errorf("cannot list files in dir %q", p), err)
		}
		for _, f := range files {
			if !f.IsDir() && f.Size() > 0 {
				return true, nil
			}
		}
	}

	parentPrefix, _ := path.Split(prefix)
	parentPrefix = strings.Trim(parentPrefix, "/")

	if parentPrefix != "" {
		return ks.TrustedKeyPrefixExists(parentPrefix)
	}

	return false, nil
}