// ConcatAuthKeys concatenates the two sets of authorised keys, interposing
// a newline if necessary, because authorised keys are newline-separated.
195378
func ConcatAuthKeys(a, b string) string {
	if a == "" {
		return b
	}
	if b == "" {
		return a
	}
	if a[len(a)-1] != '\n' {
		return a + "\n" + b
	}
	return a + b
}
159999
func (h *AuthHandlers) UserKeyAuth(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
	fingerprint := fmt.Sprintf("%v %v", key.Type(), sshutils.Fingerprint(key))

	// as soon as key auth starts, we know something about the connection, so
	// update *log.Entry.
	h.Entry = log.WithFields(log.Fields{
		trace.Component: h.Component,
		trace.ComponentFields: log.Fields{
			"local":       conn.LocalAddr(),
			"remote":      conn.RemoteAddr(),
			"user":        conn.User(),
			"fingerprint": fingerprint,
		},
	})

	cid := fmt.Sprintf("conn(%v->%v, user=%v)", conn.RemoteAddr(), conn.LocalAddr(), conn.User())
	h.Debugf("%v auth attempt", cid)

	cert, ok := key.(*ssh.Certificate)
	h.Debugf("%v auth attempt with key %v, %#v", cid, fingerprint, cert)
	if !ok {
		h.Debugf("auth attempt, unsupported key type")
		return nil, trace.BadParameter("unsupported key type: %v", fingerprint)
	}
	if len(cert.ValidPrincipals) == 0 {
		h.Debugf("need a valid principal for key")
		return nil, trace.BadParameter("need a valid principal for key %v", fingerprint)
	}
	if len(cert.KeyId) == 0 {
		h.Debugf("need a valid key ID for key")
		return nil, trace.BadParameter("need a valid key for key %v", fingerprint)
	}
	teleportUser := cert.KeyId

	// only failed attempts are logged right now
	recordFailedLogin := func(err error) {
		fields := events.EventFields{
			events.EventUser:          teleportUser,
			events.AuthAttemptSuccess: false,
			events.AuthAttemptErr:     err.Error(),
		}
		h.Warnf("failed login attempt %#v", fields)
		h.AuditLog.EmitAuditEvent(events.AuthAttemptFailure, fields)
	}

	// Check that the user certificate uses supported public key algorithms, was
	// issued by Teleport, and check the certificate metadata (principals,
	// timestamp, etc). Fallback to keys is not supported.
	certChecker := utils.CertChecker{
		CertChecker: ssh.CertChecker{
			IsUserAuthority: h.IsUserAuthority,
		},
	}
	permissions, err := certChecker.Authenticate(conn, key)
	if err != nil {
		recordFailedLogin(err)
		return nil, trace.Wrap(err)
	}
	h.Debugf("Successfully authenticated")

	// see if the host user is valid, we only do this when logging into a teleport node
	if h.isTeleportNode() {
		_, err = user.Lookup(conn.User())
		if err != nil {
			host, _ := os.Hostname()
			h.Warnf("host '%s' does not have OS user '%s'", host, conn.User())
			h.Errorf("no such user")
			return nil, trace.AccessDenied("no such user: '%s'", conn.User())
		}
	}

	clusterName, err := h.AccessPoint.GetClusterName()
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// this is the only way we know of to pass valid additional data about the
	// connection to the handlers
	permissions.Extensions[utils.CertTeleportUser] = teleportUser
	permissions.Extensions[utils.CertTeleportClusterName] = clusterName.GetClusterName()
	permissions.Extensions[utils.CertTeleportUserCertificate] = string(ssh.MarshalAuthorizedKey(cert))

	if h.isProxy() {
		return permissions, nil
	}

	// check if the user has permission to log into the node.
	switch {
	case h.Component == teleport.ComponentForwardingNode:
		err = h.canLoginWithoutRBAC(cert, clusterName.GetClusterName(), teleportUser, conn.User())
	default:
		err = h.canLoginWithRBAC(cert, clusterName.GetClusterName(), teleportUser, conn.User())
	}
	if err != nil {
		h.Errorf("Permission denied: %v", err)
		recordFailedLogin(err)
		return nil, trace.Wrap(err)
	}

	return permissions, nil
}
1032390
func (e Entry) AllKeys() []KeyVal {
	if e.Set != nil {
		return MergeKeyValSet(e.Set.Keywords, e.Keywords)
	}
	return e.Keywords
}
677563
func (s *Signer) concatQueryParameters(values url.Values) string {
	str := ""
	keys := s.sortedQueryKeys(values)
	for _, k := range keys {
		if k == s.signatureParam {
			continue
		}
		str = fmt.Sprintf("%s%s", str, values.Get(k))
	}
	return str
}
388457
func (ba *BasicAuth) AddAuthHeaders(req *http.Request) {
	authString := []byte(ba.Username + ":" + ba.Password)
	header := "Basic " + base64.StdEncoding.EncodeToString(authString)
	req.Header.Set("Authorization", string(header))
}
779320
func NewAuthConfigurations(r io.Reader) (*AuthConfigurations, error) {
	var auth *AuthConfigurations
	confs, err := parseDockerConfig(r)
	if err != nil {
		return nil, err
	}
	auth, err = authConfigs(confs)
	if err != nil {
		return nil, err
	}
	return auth, nil
}
1199716
func (r *Role) AddKeys(ids []string) {
	r.KeyIDs = mergeStrSlices(r.KeyIDs, ids)
}
834100
func concatRows(tabs ...*Table) *Table {
	// TODO: Consider making this public. It would have to check
	// the columns, and we would probably also want a concatCols.

	switch len(tabs) {
	case 0:
		return new(Table)

	case 1:
		return tabs[0]
	}

	// Construct each column.
	var out Builder
	seqs := make([]slice.T, len(tabs))
	for _, col := range tabs[0].Columns() {
		seqs = seqs[:0]
		for _, tab := range tabs {
			seqs = append(seqs, tab.Column(col))
		}
		out.Add(col, slice.Concat(seqs...))
	}

	return out.Done()
}
1281452
func (t *TxStructure) HKeys(key []byte) ([][]byte, error) {
	var keys [][]byte
	err := t.iterateHash(key, func(field []byte, value []byte) error {
		keys = append(keys, append([]byte{}, field...))
		return nil
	})

	return keys, errors.Trace(err)
}
755378
func (s *DNSControllerScope) AllKeys() []string {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	var keys []string
	for k := range s.Records {
		keys = append(keys, k)
	}
	return keys
}
900531
func Concat(slices ...[]interface{}) []interface{} {
	offset := 0
	for _, slice := range slices {
		offset += len(slice)
	}
	concat := make([]interface{}, offset)
	offset = 0
	for _, slice := range slices {
		for i, e := range slice {
			concat[offset+i] = e
		}
		offset += len(slice)
	}
	return concat
}
1371108
func (j *JWT) KeyFuncRS256(token *gojwt.Token) (interface{}, error) {
	// Don't forget to validate the alg is what you expect:
	if _, ok := token.Method.(*gojwt.SigningMethodRSA); !ok {
		return nil, fmt.Errorf("unsupported signing method: %v", token.Header["alg"])
	}

	// read JWKS document from key discovery service
	if j.Jwksurl == "" {
		return nil, fmt.Errorf("token JWKSURL not specified, cannot validate RS256 signature")
	}

	rr, err := http.Get(j.Jwksurl)
	if err != nil {
		return nil, err
	}
	defer rr.Body.Close()
	body, err := ioutil.ReadAll(rr.Body)
	if err != nil {
		return nil, err
	}

	// parse json to struct
	var jwks JWKS
	if err := json.Unmarshal([]byte(body), &jwks); err != nil {
		return nil, err
	}

	// extract cert when kid and alg match
	var certPkix []byte
	for _, jwk := range jwks.Keys {
		if token.Header["kid"] == jwk.Kid {
			// FIXME: optionally walk the key chain, see rfc7517 section 4.7
			certPkix, err = base64.StdEncoding.DecodeString(jwk.X5c[0])
			if err != nil {
				return nil, fmt.Errorf("base64 decode error for JWK kid %v", token.Header["kid"])
			}
		}
	}
	if certPkix == nil {
		return nil, fmt.Errorf("no signing key found for kid %v", token.Header["kid"])
	}

	// parse certificate (from PKIX format) and return signing key
	cert, err := x509.ParseCertificate(certPkix)
	if err != nil {
		return nil, err
	}
	return cert.PublicKey, nil
}
1123993
func (c *ServiceConfigs) Keys() []string {
	keys := []string{}
	c.mu.RLock()
	defer c.mu.RUnlock()
	for name := range c.m {
		keys = append(keys, name)
	}
	return keys
}
762178
func concat(a, b []byte) []byte {
	c := make([]byte, len(a)+len(b))
	copy(c, a)
	copy(c[len(a):], b)
	return c
}
407187
func EncodeAuth(a *AuthConfig) string {
	authStr := a.Username + ":" + a.Password
	msg := []byte(authStr)
	encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg)))
	base64.StdEncoding.Encode(encoded, msg)
	return string(encoded)
}
343104
func (storage *MessageBodyStorage) BucketArnAllKeys() *gocf.StringExpr {
	return gocf.Join("",
		gocf.String("arn:aws:s3:::"),
		storage.bucketNameExpr,
		gocf.String("/*"))
}
1028974
func (c *Config) AuthorizedKeys() string {
	value, _ := c.defined[AuthorizedKeysKey].(string)
	return value
}