// verifyServerCertMatchesURI is used on tls connections dialed to a connect
// server to ensure that the certificate it presented has the correct identity.
973905
func verifyServerCertMatchesURI(certs []*x509.Certificate,
	expected connect.CertURI) error {
	expectedStr := expected.URI().String()

	gotURI, err := extractCertURI(certs)
	if err != nil {
		return errors.New("peer certificate mismatch")
	}

	// Override the hostname since we rely on x509 constraints to limit ability to
	// spoof the trust domain if needed (i.e. because a root is shared with other
	// PKI or Consul clusters). This allows for seamless migrations between trust
	// domains.
	expectURI := expected.URI()
	expectURI.Host = gotURI.Host
	if strings.ToLower(gotURI.String()) == strings.ToLower(expectURI.String()) {
		// OK!
		return nil
	}

	return fmt.Errorf("peer certificate mismatch got %s, want %s",
		gotURI.String(), expectedStr)
}
483981
func (r *CheckCertificateRPC) CheckCertificate(c context.Context, req *admin.CheckCertificateRequest) (*admin.CheckCertificateResponse, error) {
	// Deserialize the cert.
	der, err := utils.ParsePEM(req.CertPem, "CERTIFICATE")
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "can't parse 'cert_pem' - %s", err)
	}
	cert, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "can't parse 'cert-pem' - %s", err)
	}

	// Find a checker for the CA that signed the cert, check the certificate.
	checker, err := GetCertChecker(c, cert.Issuer.CommonName)
	if err == nil {
		_, err = checker.CheckCertificate(c, cert)
		if err == nil {
			return &admin.CheckCertificateResponse{
				IsValid: true,
			}, nil
		}
	}

	// Recognize error codes related to CA cert checking. Everything else is
	// transient errors.
	if details, ok := err.(Error); ok {
		return &admin.CheckCertificateResponse{
			IsValid:       false,
			InvalidReason: details.Error(),
		}, nil
	}
	return nil, status.Errorf(codes.Internal, "failed to check the certificate - %s", err)
}
489265
func ParseCertURIFromString(input string) (CertURI, error) {
	// Parse the certificate URI from the string
	uriRaw, err := url.Parse(input)
	if err != nil {
		return nil, err
	}
	return ParseCertURI(uriRaw)
}
96117
func (r *URIBuilder) ClientURI(s string) *URIBuilder {
	r.clientURI = s
	return r
}
650738
func doesPolicySignatureV4Match(formValues http.Header) APIErrorCode {
	// Server region.
	region := globalServerConfig.GetRegion()

	// Parse credential tag.
	credHeader, err := parseCredentialHeader("Credential="+formValues.Get("X-Amz-Credential"), region, serviceS3)
	if err != ErrNone {
		return ErrMissingFields
	}

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

	// Get signing key.
	signingKey := getSigningKey(cred.SecretKey, credHeader.scope.date, credHeader.scope.region, serviceS3)

	// Get signature.
	newSignature := getSignature(signingKey, formValues.Get("Policy"))

	// Verify signature.
	if !compareSignatureV4(newSignature, formValues.Get("X-Amz-Signature")) {
		return ErrSignatureDoesNotMatch
	}

	// Success.
	return ErrNone
}
1158176
func (db *SnapshotDB) fetchTrustedCerts(c context.Context) (certMap, error) {
	if db.tokenServiceURL == "" {
		logging.Warningf(
			c, "Delegation is not supported, the token server URL is not set by %s",
			db.AuthServiceURL)
		return certMap{}, nil
	}

	certs, err := signing.FetchCertificatesFromLUCIService(c, db.tokenServiceURL)
	if err != nil {
		return nil, err
	}
	if certs.ServiceAccountName == "" {
		return nil, fmt.Errorf("the token server %s didn't provide its service account name", db.tokenServiceURL)
	}

	id, err := identity.MakeIdentity("user:" + certs.ServiceAccountName)
	if err != nil {
		return nil, fmt.Errorf("invalid service_account_name %q in fetched certificates bundle - %s", certs.ServiceAccountName, err)
	}

	return certMap{id: certs}, nil
}
41152
func VerifyHostPort(netProto string, addr string) (verifiedAddr string, err error) {
	port, err := GetPortFromAddr(addr)
	if err != nil {
		return "", err
	}

	_, err = Verify(netProto, port)
	if err != nil {
		return "", err
	}

	return addr, nil
}
1118742
func CheckCertificate(c context.Context, cert *x509.Certificate) (*certconfig.CA, error) {
	checker, err := GetCertChecker(c, cert.Issuer.CommonName)
	if err != nil {
		return nil, err
	}
	return checker.CheckCertificate(c, cert)
}
1205002
func (c *CertChecker) CheckCert(principal string, cert *Certificate) error {
	if c.IsRevoked != nil && c.IsRevoked(cert) {
		return fmt.Errorf("ssh: certicate serial %d revoked", cert.Serial)
	}

	for opt, _ := range cert.CriticalOptions {
		// sourceAddressCriticalOption will be enforced by
		// serverAuthenticate
		if opt == sourceAddressCriticalOption {
			continue
		}

		found := false
		for _, supp := range c.SupportedCriticalOptions {
			if supp == opt {
				found = true
				break
			}
		}
		if !found {
			return fmt.Errorf("ssh: unsupported critical option %q in certificate", opt)
		}
	}

	if len(cert.ValidPrincipals) > 0 {
		// By default, certs are valid for all users/hosts.
		found := false
		for _, p := range cert.ValidPrincipals {
			if p == principal {
				found = true
				break
			}
		}
		if !found {
			return fmt.Errorf("ssh: principal %q not in the set of valid principals for given certificate: %q", principal, cert.ValidPrincipals)
		}
	}

	if !c.IsAuthority(cert.SignatureKey) {
		return fmt.Errorf("ssh: certificate signed by unrecognized authority")
	}

	clock := c.Clock
	if clock == nil {
		clock = time.Now
	}

	unixNow := clock().Unix()
	if after := int64(cert.ValidAfter); after < 0 || unixNow < int64(cert.ValidAfter) {
		return fmt.Errorf("ssh: cert is not yet valid")
	}
	if before := int64(cert.ValidBefore); cert.ValidBefore != uint64(CertTimeInfinity) && (unixNow >= before || before < 0) {
		return fmt.Errorf("ssh: cert has expired")
	}
	if err := cert.SignatureKey.Verify(cert.bytesForSigning(), cert.Signature); err != nil {
		return fmt.Errorf("ssh: certificate signature does not verify")
	}

	return nil
}
541736
func IsRequestURI(rawurl string) bool {
	_, err := url.ParseRequestURI(rawurl)
	return err == nil
}
477257
func (c *Configurator) verifyIncomingHTTPS() bool {
	c.RLock()
	defer c.RUnlock()
	return c.base.VerifyIncomingHTTPS
}
797926
func verifyChain(tlsCfg *tls.Config, rawCerts [][]byte, client bool) (*x509.Certificate, error) {

	// Fetch leaf and intermediates. This is based on code form tls handshake.
	if len(rawCerts) < 1 {
		return nil, errors.New("tls: no certificates from peer")
	}
	certs := make([]*x509.Certificate, len(rawCerts))
	for i, asn1Data := range rawCerts {
		cert, err := x509.ParseCertificate(asn1Data)
		if err != nil {
			return nil, errors.New("tls: failed to parse certificate from peer: " + err.Error())
		}
		certs[i] = cert
	}

	cas := tlsCfg.RootCAs
	if client {
		cas = tlsCfg.ClientCAs
	}

	opts := x509.VerifyOptions{
		Roots:         cas,
		Intermediates: x509.NewCertPool(),
	}
	if !client {
		// Server side only sets KeyUsages in tls. This defaults to ServerAuth in
		// x509 lib. See
		// https://github.com/golang/go/blob/ee7dd810f9ca4e63ecfc1d3044869591783b8b74/src/crypto/x509/verify.go#L866-L868
		opts.KeyUsages = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
	}

	// All but the first cert are intermediates
	for _, cert := range certs[1:] {
		opts.Intermediates.AddCert(cert)
	}
	_, err := certs[0].Verify(opts)
	return certs[0], err
}
121993
func (c *Client) GetCertAuthorities(caType services.CertAuthType, loadKeys bool, opts ...services.MarshalOption) ([]services.CertAuthority, error) {
	if err := caType.Check(); err != nil {
		return nil, trace.Wrap(err)
	}
	out, err := c.Get(c.Endpoint("authorities", string(caType)), url.Values{
		"load_keys": []string{fmt.Sprintf("%t", loadKeys)},
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	var items []json.RawMessage
	if err := json.Unmarshal(out.Bytes(), &items); err != nil {
		return nil, err
	}
	re := make([]services.CertAuthority, len(items))
	for i, raw := range items {
		ca, err := services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(raw, services.SkipValidation())
		if err != nil {
			return nil, trace.Wrap(err)
		}
		re[i] = ca
	}
	return re, nil
}
409055
func (m *MockRPCServer) CheckValidity(req *rpcwrapper.Request, secret string) bool {
	ret := m.ctrl.Call(m, "CheckValidity", req, secret)
	ret0, _ := ret[0].(bool)
	return ret0
}
715541
func (c *ClientContext) VerifySelectiveFlags(flags uint32) error {
	return c.sctxt.VerifySelectiveFlags(flags)
}
1183244
func (s *server) checkHostCert(logger *log.Entry, user string, clusterName string, cert *ssh.Certificate) error {
	if cert.CertType != ssh.HostCert {
		return trace.BadParameter("expected host cert, got wrong cert type: %d", cert.CertType)
	}

	// fetch keys of the certificate authority to check
	// if there is a match
	keys, err := s.getTrustedCAKeysByID(services.CertAuthID{
		Type:       services.HostCA,
		DomainName: clusterName,
	})
	if err != nil {
		return trace.Wrap(err)
	}

	// match key of the certificate authority with the signature key
	var match bool
	for _, k := range keys {
		if sshutils.KeysEqual(k, cert.SignatureKey) {
			match = true
			break
		}
	}
	if !match {
		return trace.NotFound("cluster %v has no matching CA keys", clusterName)
	}

	checker := utils.CertChecker{}
	if err := checker.CheckCert(user, cert); err != nil {
		return trace.BadParameter(err.Error())
	}

	return nil
}
1290391
func CheckCertificateSigningRequest(d Depot, name string) bool {
	return d.Check(CsrTag(name))
}