// parseKnownHosts parses keys in known_hosts format and returns a
// services.CertAuthority.
175226
func parseKnownHosts(bytes []byte, allowedLogins []string) (services.CertAuthority, services.Role, error) {
	marker, options, pubKey, comment, _, err := ssh.ParseKnownHosts(bytes)
	if marker != "cert-authority" {
		return nil, nil, trace.BadParameter("invalid file format. expected '@cert-authority` marker")
	}
	if err != nil {
		return nil, nil, trace.BadParameter("invalid public key")
	}
	teleportOpts, err := url.ParseQuery(comment)
	if err != nil {
		return nil, nil, trace.BadParameter("invalid key comment: '%s'", comment)
	}
	authType := services.CertAuthType(teleportOpts.Get("type"))
	if authType != services.HostCA && authType != services.UserCA {
		return nil, nil, trace.BadParameter("unsupported CA type: '%s'", authType)
	}
	if len(options) == 0 {
		return nil, nil, trace.BadParameter("key without cluster_name")
	}
	const prefix = "*."
	domainName := strings.TrimPrefix(options[0], prefix)

	v1 := &services.CertAuthorityV1{
		AllowedLogins: utils.CopyStrings(allowedLogins),
		DomainName:    domainName,
		Type:          authType,
		CheckingKeys:  [][]byte{ssh.MarshalAuthorizedKey(pubKey)},
	}
	ca, role := services.ConvertV1CertAuthority(v1)
	return ca, role, nil
}
728656
func (c *SSHClient) parseHost(host string) error {
	c.host = host

	// Remove extra "ssh://" schema
	if len(c.host) > 6 && c.host[:6] == "ssh://" {
		c.host = c.host[6:]
	}

	if at := strings.Index(c.host, "@"); at != -1 {
		c.user = c.host[:at]
		c.host = c.host[at+1:]
	}

	// Add default user, if not set
	if c.user == "" {
		u, err := user.Current()
		if err != nil {
			return err
		}
		c.user = u.Username
	}

	if strings.Index(c.host, "/") != -1 {
		return ErrConnect{c.user, c.host, "unexpected slash in the host URL"}
	}

	// Add default port, if not set
	if strings.Index(c.host, ":") == -1 {
		c.host += ":22"
	}

	return nil
}
1202205
func ParsePGPKeys(keyfiles []string) ([]string, error) {
	keys := make([]string, len(keyfiles))

	keybaseMap, err := FetchKeybasePubkeys(keyfiles)
	if err != nil {
		return nil, err
	}

	for i, keyfile := range keyfiles {
		keyfile = strings.TrimSpace(keyfile)

		if strings.HasPrefix(keyfile, kbPrefix) {
			key, ok := keybaseMap[keyfile]
			if !ok || key == "" {
				return nil, fmt.Errorf("keybase user %q not found", strings.TrimPrefix(keyfile, kbPrefix))
			}
			keys[i] = key
			continue
		}

		pgpStr, err := ReadPGPFile(keyfile)
		if err != nil {
			return nil, err
		}
		keys[i] = pgpStr
	}

	return keys, nil
}
312717
func (k *Kademlia) knowNeighbours(addrs [][]byte) (got bool, n int, missing [][]byte) {
	pm := make(map[string]bool)
	depth := depthForPot(k.conns, k.NeighbourhoodSize, k.base)
	// create a map with all peers at depth and deeper known in the kademlia
	k.eachAddr(nil, 255, func(p *BzzAddr, po int) bool {
		// in order deepest to shallowest compared to the kademlia base address
		// all bins (except self) are included (0 <= bin <= 255)
		if po < depth {
			return false
		}
		pk := common.Bytes2Hex(p.Address())
		pm[pk] = true
		return true
	})

	// iterate through nearest neighbors in the peerpot map
	// if we can't find the neighbor in the map we created above
	// then we don't know all our neighbors
	// (which sadly is all too common in modern society)
	var gots int
	var culprits [][]byte
	for _, p := range addrs {
		pk := common.Bytes2Hex(p)
		if pm[pk] {
			gots++
		} else {
			log.Trace(fmt.Sprintf("%08x: known nearest neighbour %s not found", k.base, pk))
			culprits = append(culprits, p)
		}
	}
	return gots == len(addrs), gots, culprits
}
305854
func (c *Client) SetHost(h string) *Client {
	c.Host = h
	return c
}
596114
func (r *Request) SetHost(host string) {
	r.context.Request.SetHost(host)
}
898818
func ParseHost(s string) (*Host, error) {
	isValidHost := func(host string) bool {
		if host == "" {
			return false
		}

		if ip := net.ParseIP(host); ip != nil {
			return true
		}

		// host is not a valid IPv4 or IPv6 address
		// host may be a hostname
		// refer https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
		// why checks are done like below
		if len(host) < 1 || len(host) > 253 {
			return false
		}

		for _, label := range strings.Split(host, ".") {
			if len(label) < 1 || len(label) > 63 {
				return false
			}

			if !hostLabelRegexp.MatchString(label) {
				return false
			}
		}

		return true
	}

	var port Port
	var isPortSet bool
	host, portStr, err := net.SplitHostPort(s)
	if err != nil {
		if !strings.Contains(err.Error(), "missing port in address") {
			return nil, err
		}

		host = s
		portStr = ""
	} else {
		if port, err = ParsePort(portStr); err != nil {
			return nil, err
		}

		isPortSet = true
	}

	if i := strings.Index(host, "%"); i > -1 {
		host = host[:i]
	}

	if !isValidHost(host) {
		return nil, errors.New("invalid hostname")
	}

	return &Host{
		Name:      host,
		Port:      port,
		IsPortSet: isPortSet,
	}, nil
}
11014
func (fs *FSLocalKeyStore) AddKnownHostKeys(hostname string, hostKeys []ssh.PublicKey) error {
	fp, err := os.OpenFile(filepath.Join(fs.KeyDir, fileNameKnownHosts), os.O_CREATE|os.O_RDWR, 0640)
	if err != nil {
		return trace.Wrap(err)
	}
	defer fp.Sync()
	defer fp.Close()
	// read all existing entries into a map (this removes any pre-existing dupes)
	entries := make(map[string]int)
	output := make([]string, 0)
	scanner := bufio.NewScanner(fp)
	for scanner.Scan() {
		line := scanner.Text()
		if _, exists := entries[line]; !exists {
			output = append(output, line)
			entries[line] = 1
		}
	}
	// add every host key to the list of entries
	for i := range hostKeys {
		fs.log.Debugf("Adding known host %s with key: %v", hostname, sshutils.Fingerprint(hostKeys[i]))
		bytes := ssh.MarshalAuthorizedKey(hostKeys[i])
		line := strings.TrimSpace(fmt.Sprintf("%s %s", hostname, bytes))
		if _, exists := entries[line]; !exists {
			output = append(output, line)
		}
	}
	// re-create the file:
	_, err = fp.Seek(0, 0)
	if err != nil {
		return trace.Wrap(err)
	}
	if err = fp.Truncate(0); err != nil {
		return trace.Wrap(err)
	}
	for _, line := range output {
		fmt.Fprintf(fp, "%s\n", line)
	}
	return nil
}
751221
func (r *runtimeOCI) libcontainerStats(ctr *Container) (*libcontainer.Stats, error) {
	factory, err := loadFactory(r.root)
	if err != nil {
		return nil, err
	}
	container, err := factory.Load(ctr.ID())
	if err != nil {
		return nil, err
	}
	return container.Stats()
}
917503
func (s *OriginationRoute) SetHost(v string) *OriginationRoute {
	s.Host = &v
	return s
}
875015
func (s *InstanceAccessDetails) SetHostKeys(v []*HostKeyAttributes) *InstanceAccessDetails {
	s.HostKeys = v
	return s
}
99530
func parseCARoot(pemValue, provider, clusterID string) (*structs.CARoot, error) {
	id, err := connect.CalculateCertFingerprint(pemValue)
	if err != nil {
		return nil, fmt.Errorf("error parsing root fingerprint: %v", err)
	}
	rootCert, err := connect.ParseCert(pemValue)
	if err != nil {
		return nil, fmt.Errorf("error parsing root cert: %v", err)
	}
	return &structs.CARoot{
		ID:                  id,
		Name:                fmt.Sprintf("%s CA Root Cert", strings.Title(provider)),
		SerialNumber:        rootCert.SerialNumber.Uint64(),
		SigningKeyID:        connect.HexString(rootCert.AuthorityKeyId),
		ExternalTrustDomain: clusterID,
		NotBefore:           rootCert.NotBefore,
		NotAfter:            rootCert.NotAfter,
		RootCert:            pemValue,
		Active:              true,
	}, nil
}
12839
func parseEncryptionKeys(sseKeys string) (encMap map[string][]prefixSSEPair, err *probe.Error) {
	encMap = make(map[string][]prefixSSEPair)
	if sseKeys == "" {
		return
	}
	prefix := ""
	index := 0 // start index of prefix
	vs := 0    // start index of sse-c key
	sseKeyLen := 32
	delim := 1
	k := len(sseKeys)
	for index < k {
		i := strings.Index(sseKeys[index:], "=")
		if i == -1 {
			return nil, probe.NewError(errors.New("SSE-C prefix should be of the form prefix1=key1,... "))
		}
		prefix = sseKeys[index : index+i]
		alias, _ := url2Alias(prefix)
		vs = i + 1 + index
		if vs+32 > k {
			return nil, probe.NewError(errors.New("SSE-C key should be 32 bytes long"))
		}
		if (vs+sseKeyLen < k) && sseKeys[vs+sseKeyLen] != ',' {
			return nil, probe.NewError(errors.New("SSE-C prefix=secret should be delimited by , and secret should be 32 bytes long"))
		}
		sseKey := sseKeys[vs : vs+sseKeyLen]
		if _, ok := encMap[alias]; !ok {
			encMap[alias] = make([]prefixSSEPair, 0)
		}
		sse, e := encrypt.NewSSEC([]byte(sseKey))
		if e != nil {
			return nil, probe.NewError(e)
		}
		encMap[alias] = append(encMap[alias], prefixSSEPair{
			Prefix: prefix,
			SSE:    sse,
		})
		// advance index sseKeyLen + delim bytes for the next key start
		index = vs + sseKeyLen + delim
	}

	// Sort encryption keys in descending order of prefix length
	for _, encKeys := range encMap {
		sort.Sort(byPrefixLength(encKeys))
	}

	// Success.
	return encMap, nil
}
1265918
func (c *Config) UnknownAttrs() map[string]interface{} {
	newAttrs := make(map[string]interface{})
	for k, v := range c.unknown {
		newAttrs[k] = v
	}
	return newAttrs
}
1374763
func (d *DNSProvider) setHosts(sld, tld string, hosts []Record) error {
	req, err := d.newRequestPost("namecheap.domains.dns.setHosts",
		addParam("SLD", sld),
		addParam("TLD", tld),
		func(values url.Values) {
			for i, h := range hosts {
				ind := fmt.Sprintf("%d", i+1)
				values.Add("HostName"+ind, h.Name)
				values.Add("RecordType"+ind, h.Type)
				values.Add("Address"+ind, h.Address)
				values.Add("MXPref"+ind, h.MXPref)
				values.Add("TTL"+ind, h.TTL)
			}
		},
	)
	if err != nil {
		return err
	}

	var shr setHostsResponse
	err = d.do(req, &shr)
	if err != nil {
		return err
	}

	if len(shr.Errors) > 0 {
		return fmt.Errorf("%s [%d]", shr.Errors[0].Description, shr.Errors[0].Number)
	}
	if shr.Result.IsSuccess != "true" {
		return fmt.Errorf("setHosts failed")
	}

	return nil
}
452058
func NormalizeAddresses(addrs []string, defaultPort string) ([]string, error) {
	var (
		normalized = make([]string, 0, len(addrs))
		seenSet    = make(map[string]struct{})
	)

	for _, addr := range addrs {
		normalizedAddr, err := NormalizeAddress(addr, defaultPort)
		if err != nil {
			return nil, err
		}
		_, seen := seenSet[normalizedAddr]
		if !seen {
			normalized = append(normalized, normalizedAddr)
			seenSet[normalizedAddr] = struct{}{}
		}
	}

	return normalized, nil
}
1128859
func KnownConfigKeys(schema environschema.Fields) set.Strings {
	result := set.NewStrings()
	for name := range schema {
		result.Add(name)
	}
	return result
}