// ParseCertificateDomain parses the certificate served by the given domain.
425995
func ParseCertificateDomain(domain string) (cert *Certificate, err error) {
	var host, port string
	if host, port, err = net.SplitHostPort(domain); err != nil {
		host = domain
		port = "443"
	}

	var conn *tls.Conn
	conn, err = tls.DialWithDialer(&net.Dialer{Timeout: 10 * time.Second}, "tcp", net.JoinHostPort(host, port), &tls.Config{InsecureSkipVerify: true})
	if err != nil {
		return
	}
	defer conn.Close()

	if len(conn.ConnectionState().PeerCertificates) == 0 {
		return nil, errors.New("received no server certificates")
	}

	cert = ParseCertificate(conn.ConnectionState().PeerCertificates[0])
	return
}
1165838
func validateDomain(s string) bool {
	// Throw a protocol in front because the parser wants one.
	proto := "http"
	u, err := url.Parse(proto + "://" + s)
	if err != nil {
		return false
	}

	// The final group must include a non-numeric character.
	// To disallow the likes of "8.8.8.8."
	dotsplit := strings.Split(strings.TrimSuffix(u.Host, "."), ".")
	if len(dotsplit) > 0 {
		group := dotsplit[len(dotsplit)-1]
		if !hasalpha.MatchString(group) {
			return false
		}
	}

	ok := (u.IsAbs()) &&
		(u.Scheme == proto) &&
		(u.User == nil) &&
		(u.Path == "") &&
		(u.RawPath == "") &&
		(u.RawQuery == "") &&
		(u.Fragment == "") &&
		// Disallow colons. So no port, and no ipv6.
		(!strings.Contains(u.Host, ":")) &&
		// Disallow any valid ip addresses.
		(net.ParseIP(u.Host) == nil)
	return ok
}
1307891
func (s *RegistrarService) RegisterDomain(accountID string, domainName string, request *DomainRegisterRequest) (*domainRegistrationResponse, error) {
	path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/registrations", accountID, domainName))
	registrationResponse := &domainRegistrationResponse{}

	// TODO: validate mandatory attributes RegistrantID

	resp, err := s.client.post(path, request, registrationResponse)
	if err != nil {
		return nil, err
	}

	registrationResponse.HttpResponse = resp
	return registrationResponse, nil
}
1193104
func (api *Client) DeleteDomain(id string) error {
	_, _, err := api.makeRequest(http.MethodDelete, fmt.Sprintf("%s/%s", api.concatUserPath(domainsPath), id))
	return err
}
1127311
func ParseDomains(rule string) ([]string, error) {
	parser, err := newParser()
	if err != nil {
		return nil, err
	}

	parse, err := parser.Parse(rule)
	if err != nil {
		return nil, err
	}

	buildTree, ok := parse.(treeBuilder)
	if !ok {
		return nil, errors.New("cannot parse")
	}

	return lower(parseDomain(buildTree())), nil
}
1183147
func (p *ProxyLBCertificates) ParseServerCertificate() (*x509.Certificate, error) {
	cert, e := p.parseCertificate(p.ServerCertificate)
	if e != nil {
		return nil, e
	}
	return cert, nil
}
915225
func (m HostCertificateManager) GenerateCertificateSigningRequestByDn(ctx context.Context, distinguishedName string) (string, error) {
	req := types.GenerateCertificateSigningRequestByDn{
		This:              m.Reference(),
		DistinguishedName: distinguishedName,
	}

	res, err := methods.GenerateCertificateSigningRequestByDn(ctx, m.Client(), &req)
	if err != nil {
		return "", err
	}

	return res.Returnval, nil
}
612466
func (c *Client) RetrieveDomain(name string) (DomainResponse, error) {
	req, err := c.NewRequest(map[string]string{}, "GET", fmt.Sprintf("/domains/%s", name))

	if err != nil {
		return DomainResponse{}, err
	}

	resp, err := checkResp(c.Http.Do(req))
	if err != nil {
		return DomainResponse{}, fmt.Errorf("Error destroying domain: %s", err)
	}

	domainresp := new(DomainResponse)

	err = decodeBody(resp, domainresp)

	if err != nil {
		return DomainResponse{}, fmt.Errorf("Error decoding domain response: %s", err)
	}

	// The request was successful
	return *domainresp, nil
}
828531
func ParseCSR(obj *CertificateSigningRequest) (*x509.CertificateRequest, error) {
	// extract PEM from request object
	pemBytes := obj.Spec.Request
	block, _ := pem.Decode(pemBytes)
	if block == nil || block.Type != "CERTIFICATE REQUEST" {
		return nil, errors.New("PEM block type must be CERTIFICATE REQUEST")
	}
	csr, err := x509.ParseCertificateRequest(block.Bytes)
	if err != nil {
		return nil, err
	}
	return csr, nil
}
34711
func parseAddrSpec(addr, domain string) *addrSpec {
	const postmaster string = "postmaster"

	if addr == "" || addr == "@" {
		return &addrSpec{postmaster, domain}
	}

	var l, d string
	i := strings.LastIndexByte(addr, '@')
	if i < 0 || i == len(addr)-1 { // local[@]
		d = domain
	} else {
		d = addr[i+1:]
	}
	if i == 0 { // @domain
		l = postmaster
	} else {
		l = addr[:i]
	}

	return &addrSpec{l, d}
}
624801
func parseCertAndKey(cert, key []byte) (c *x509.Certificate, k *rsa.PrivateKey, err error) {
	pc, _ := pem.Decode(cert)
	if c, err = x509.ParseCertificate(pc.Bytes); err != nil {
		err = fmt.Errorf("Failed to parse private key with error: %v", err)
		return
	}

	pk, _ := pem.Decode(key)
	if k, err = x509.ParsePKCS1PrivateKey(pk.Bytes); err != nil {
		err = fmt.Errorf("Failed to parse certificate with error: %v", err)
		return
	}

	return
}
1097924
func (s *CertificatesService) GetCertificate(accountID, domainIdentifier string, certificateID int64) (*certificateResponse, error) {
	path := versioned(certificatePath(accountID, domainIdentifier, certificateID))
	certificateResponse := &certificateResponse{}

	resp, err := s.client.get(path, certificateResponse)
	if err != nil {
		return nil, err
	}

	certificateResponse.HttpResponse = resp
	return certificateResponse, nil
}
1120727
func (s *CA) GetCertAuthority(id services.CertAuthID, loadSigningKeys bool, opts ...services.MarshalOption) (services.CertAuthority, error) {
	if err := id.Check(); err != nil {
		return nil, trace.Wrap(err)
	}
	item, err := s.Get(context.TODO(), backend.Key(authoritiesPrefix, string(id.Type), id.DomainName))
	if err != nil {
		return nil, trace.Wrap(err)
	}
	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)
	return ca, nil
}
1235602
func parseCredentialHeader(credElement string, region string, stype serviceType) (ch credentialHeader, aec APIErrorCode) {
	creds := strings.SplitN(strings.TrimSpace(credElement), "=", 2)
	if len(creds) != 2 {
		return ch, ErrMissingFields
	}
	if creds[0] != "Credential" {
		return ch, ErrMissingCredTag
	}
	credElements := strings.Split(strings.TrimSpace(creds[1]), "/")
	if len(credElements) < 5 {
		return ch, ErrCredMalformed
	}
	accessKey := strings.Join(credElements[:len(credElements)-4], "/") // The access key may contain one or more `/`
	if !auth.IsAccessKeyValid(accessKey) {
		return ch, ErrInvalidAccessKeyID
	}
	// Save access key id.
	cred := credentialHeader{
		accessKey: accessKey,
	}
	credElements = credElements[len(credElements)-4:]
	var e error
	cred.scope.date, e = time.Parse(yyyymmdd, credElements[0])
	if e != nil {
		return ch, ErrMalformedCredentialDate
	}

	cred.scope.region = credElements[1]
	// Verify if region is valid.
	sRegion := cred.scope.region
	// Region is set to be empty, we use whatever was sent by the
	// request and proceed further. This is a work-around to address
	// an important problem for ListBuckets() getting signed with
	// different regions.
	if region == "" {
		region = sRegion
	}
	// Should validate region, only if region is set.
	if !isValidRegion(sRegion, region) {
		return ch, ErrAuthorizationHeaderMalformed

	}
	if credElements[2] != string(stype) {
		return ch, ErrInvalidService
	}
	cred.scope.service = credElements[2]
	if credElements[3] != "aws4_request" {
		return ch, ErrInvalidRequestVersion
	}
	cred.scope.request = credElements[3]
	return cred, ErrNone
}
875535
func getCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
	if len(cfgCerts.Certificates) == 0 {
		return nil, fmt.Errorf("tls: no certificates configured")
	}

	if len(cfgCerts.Certificates) == 1 || cfgCerts.NameToCertificate == nil {
		// There's only one choice, so no point doing any work.
		return &cfgCerts.Certificates[0], nil
	}

	name := strings.ToLower(clientHello.ServerName)
	for len(name) > 0 && name[len(name)-1] == '.' {
		name = name[:len(name)-1]
	}

	if cert, ok := cfgCerts.NameToCertificate[name]; ok {
		return cert, nil
	}

	// try replacing labels in the name with wildcards until we get a
	// match.
	labels := strings.Split(name, ".")
	for i := range labels {
		labels[i] = "*"
		candidate := strings.Join(labels, ".")
		if cert, ok := cfgCerts.NameToCertificate[candidate]; ok {
			return cert, nil
		}
	}

	// If nothing matches, return the first certificate.
	return &cfgCerts.Certificates[0], 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
}
326390
func ParseCertURI(input *url.URL) (CertURI, error) {
	if input.Scheme != "spiffe" {
		return nil, fmt.Errorf("SPIFFE ID must have 'spiffe' scheme")
	}

	// Path is the raw value of the path without url decoding values.
	// RawPath is empty if there were no encoded values so we must
	// check both.
	path := input.Path
	if input.RawPath != "" {
		path = input.RawPath
	}

	// Test for service IDs
	if v := spiffeIDServiceRegexp.FindStringSubmatch(path); v != nil {
		// Determine the values. We assume they're sane to save cycles,
		// but if the raw path is not empty that means that something is
		// URL encoded so we go to the slow path.
		ns := v[1]
		dc := v[2]
		service := v[3]
		if input.RawPath != "" {
			var err error
			if ns, err = url.PathUnescape(v[1]); err != nil {
				return nil, fmt.Errorf("Invalid namespace: %s", err)
			}
			if dc, err = url.PathUnescape(v[2]); err != nil {
				return nil, fmt.Errorf("Invalid datacenter: %s", err)
			}
			if service, err = url.PathUnescape(v[3]); err != nil {
				return nil, fmt.Errorf("Invalid service: %s", err)
			}
		}

		return &SpiffeIDService{
			Host:       input.Host,
			Namespace:  ns,
			Datacenter: dc,
			Service:    service,
		}, nil
	}

	// Test for signing ID
	if input.Path == "" {
		idx := strings.Index(input.Host, ".")
		if idx > 0 {
			return &SpiffeIDSigning{
				ClusterID: input.Host[:idx],
				Domain:    input.Host[idx+1:],
			}, nil
		}
	}

	return nil, fmt.Errorf("SPIFFE ID is not in the expected format")
}