// ParseCertURI parses a the URI value from a TLS certificate.
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")
}
166923
func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
	var csr certificateRequest

	rest, err := asn1.Unmarshal(asn1Data, &csr)
	if err != nil {
		return nil, err
	} else if len(rest) != 0 {
		return nil, asn1.SyntaxError{Msg: "trailing data"}
	}

	return parseCertificateRequest(&csr)
}
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
}
1002913
func parseChromeSafari(l *lex) *UserAgent {
	ua := new()

	if !parseMozillaLike(l, ua) {
		return nil
	}
	if !l.match("AppleWebKit/") {
		return nil
	}
	if _, ok := l.span(" "); !ok {
		return nil
	}
	if !l.match("(KHTML, like Gecko) ") {
		return nil
	}
	if !parseNameVersion(l, ua) {
		return nil
	}
	if ua.Name == "CriOS" {
		ua.Name = "Chrome"
	} else if ua.Name == "FxiOS" {
		ua.Name = "Firefox"
	} else if ua.Name == "Version" {
		if l.match("Chrome/") {
			if !parseVersion(l, ua, " ") {
				return nil
			}
			ua.Name = "WebView"
			ua.Type = Library
		} else {
			if l.match("Mobile/") {
				if _, ok := l.span(" "); !ok {
					return nil
				}
			}
			if !l.match("Safari/") {
				return nil
			}
			ua.Name = "Safari"
		}
	} else if ua.Name == "Silk" {
		if l.match("like Chrome/") {
			if _, ok := l.span(" "); !ok {
				return nil
			}
		} else {
			return nil
		}
	}

	if l.match("Mobile") && !ua.Tablet {
		ua.Mobile = true
	}
	if ua.OS == OSAndroid && !ua.Mobile {
		ua.Tablet = true
	}

	// Identify non-Chrome browsers with Chromelike UAs:
	if _, ok := l.span("OPR/"); ok {
		if !parseVersion(l, ua, " ") {
			return nil
		}
		ua.Name = "Opera"
	}
	if _, ok := l.span("Edge/"); ok {
		if !parseVersion(l, ua, " ") {
			return nil
		}
		ua.Name = "Edge"
	}

	return ua
}
878045
func ParseURL(scheme, host, path string) *url.URL {
	u, err := url.Parse(fmt.Sprintf("%s://%s/%s", scheme, host, strings.TrimPrefix(path, "/")))
	if err != nil {
		u = &url.URL{
			Scheme: scheme,
			Host:   host,
			Path:   path,
		}
	}
	return u
}
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
}
89735
func (p *HttpStartStopProcessor) parseEventUri(uri string) string {

  hostname := ""

  //we first remove the scheme
  if strings.Contains(uri, "://") {
  	uri = strings.Split(uri, "://")[1]
  }

  //and then proceed with extracting the hostname
  hostname = strings.Split(uri, "/")[0]
  hostname = strings.Replace(hostname, ".", "_", -1)
  hostname = strings.Replace(hostname, ":", "_", -1)

	if !(len(hostname) > 0) {
		panic(errors.New("Hostname cannot be extracted from Event uri: " + uri))
	}

	return hostname
}
549744
func ParseCertificatePEM(certPEM []byte) (*x509.Certificate, error) {
	certPEM = bytes.TrimSpace(certPEM)
	cert, rest, err := ParseOneCertificateFromPEM(certPEM)
	if err != nil {
		// Log the actual parsing error but throw a default parse error message.
		log.Debugf("Certificate parsing error: %v", err)
		return nil, cferr.New(cferr.CertificateError, cferr.ParseFailed)
	} else if cert == nil {
		return nil, cferr.New(cferr.CertificateError, cferr.DecodeFailed)
	} else if len(rest) > 0 {
		return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("the PEM file should contain only one object"))
	} else if len(cert) > 1 {
		return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("the PKCS7 object in the PEM file should contain only one certificate"))
	}
	return cert[0], nil
}
447174
func ParseCertificate(cert *x509.Certificate) *Certificate {
	c := &Certificate{
		RawPEM:             string(helpers.EncodeCertificatePEM(cert)),
		SignatureAlgorithm: helpers.SignatureString(cert.SignatureAlgorithm),
		NotBefore:          cert.NotBefore,
		NotAfter:           cert.NotAfter,
		Subject:            ParseName(cert.Subject),
		Issuer:             ParseName(cert.Issuer),
		SANs:               cert.DNSNames,
		AKI:                formatKeyID(cert.AuthorityKeyId),
		SKI:                formatKeyID(cert.SubjectKeyId),
		SerialNumber:       cert.SerialNumber.String(),
	}
	for _, ip := range cert.IPAddresses {
		c.SANs = append(c.SANs, ip.String())
	}
	return c
}
565198
func (k RRSetKey) ProbesQueryURI(query string) string {
	uri := k.ProbesURI()
	if query != "" {
		uri = fmt.Sprintf("%s?sort=NAME&query=%s", uri, query)
	}
	return uri
}
330408
func TLSCerts(ca CertAuthority) [][]byte {
	pairs := ca.GetTLSKeyPairs()
	out := make([][]byte, len(pairs))
	for i, pair := range pairs {
		out[i] = append([]byte{}, pair.Cert...)
	}
	return out
}
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
}
254728
func (server *UnixServer) URI() string {
	if server.listener == nil {
		panic(ErrServerIsNotStarted)
	}
	return "unix:" + server.listener.Addr().String()
}
235402
func ParseCertsPEM(pemCerts []byte) ([]*x509.Certificate, error) {
	ok := false
	certs := []*x509.Certificate{}
	for len(pemCerts) > 0 {
		var block *pem.Block
		block, pemCerts = pem.Decode(pemCerts)
		if block == nil {
			break
		}
		// Only use PEM "CERTIFICATE" blocks without extra headers
		if block.Type != CertificateBlockType || len(block.Headers) != 0 {
			continue
		}

		cert, err := x509.ParseCertificate(block.Bytes)
		if err != nil {
			return certs, err
		}

		certs = append(certs, cert)
		ok = true
	}

	if !ok {
		return certs, errors.New("data does not contain any valid RSA or ECDSA certificates")
	}
	return certs, nil
}
1271995
func ParseCertificateRequest(s Signer, csrBytes []byte) (template *x509.Certificate, err error) {
	csrv, err := x509.ParseCertificateRequest(csrBytes)
	if err != nil {
		err = cferr.Wrap(cferr.CSRError, cferr.ParseFailed, err)
		return
	}

	err = csrv.CheckSignature()
	if err != nil {
		err = cferr.Wrap(cferr.CSRError, cferr.KeyMismatch, err)
		return
	}

	template = &x509.Certificate{
		Subject:            csrv.Subject,
		PublicKeyAlgorithm: csrv.PublicKeyAlgorithm,
		PublicKey:          csrv.PublicKey,
		SignatureAlgorithm: s.SigAlgo(),
		DNSNames:           csrv.DNSNames,
		IPAddresses:        csrv.IPAddresses,
		EmailAddresses:     csrv.EmailAddresses,
		URIs:               csrv.URIs,
	}

	for _, val := range csrv.Extensions {
		// Check the CSR for the X.509 BasicConstraints (RFC 5280, 4.2.1.9)
		// extension and append to template if necessary
		if val.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 19}) {
			var constraints csr.BasicConstraints
			var rest []byte

			if rest, err = asn1.Unmarshal(val.Value, &constraints); err != nil {
				return nil, cferr.Wrap(cferr.CSRError, cferr.ParseFailed, err)
			} else if len(rest) != 0 {
				return nil, cferr.Wrap(cferr.CSRError, cferr.ParseFailed, errors.New("x509: trailing data after X.509 BasicConstraints"))
			}

			template.BasicConstraintsValid = true
			template.IsCA = constraints.IsCA
			template.MaxPathLen = constraints.MaxPathLen
			template.MaxPathLenZero = template.MaxPathLen == 0
		}
	}

	return
}
446918
func ParseCertificateFile(certFile string) (*Certificate, error) {
	certPEM, err := ioutil.ReadFile(certFile)
	if err != nil {
		return nil, err
	}

	return ParseCertificatePEM(certPEM)
}
1105561
func ParseCSR(pemValue string) (*x509.CertificateRequest, error) {
	// The _ result below is not an error but the remaining PEM bytes.
	block, _ := pem.Decode([]byte(pemValue))
	if block == nil {
		return nil, fmt.Errorf("no PEM-encoded data found")
	}

	if block.Type != "CERTIFICATE REQUEST" {
		return nil, fmt.Errorf("first PEM-block should be CERTIFICATE REQUEST type")
	}

	return x509.ParseCertificateRequest(block.Bytes)
}