// AuthenticateSSHUser authenticates SSH console user, creates and  returns a pair of signed TLS and SSH
// short lived certificates as a result
160244
func (a *AuthWithRoles) AuthenticateSSHUser(req AuthenticateSSHRequest) (*SSHLoginResponse, error) {
	// authentication request has it's own authentication, however this limits the requests
	// types to proxies to make it harder to break
	if !a.hasBuiltinRole(string(teleport.RoleProxy)) {
		return nil, trace.AccessDenied("this request can be only executed by a proxy")
	}
	return a.authServer.AuthenticateSSHUser(req)
}
413612
func (r *Repository) GetSSHURL() string {
	if r == nil || r.SSHURL == nil {
		return ""
	}
	return *r.SSHURL
}
402128
func (p *PushEventRepository) GetSSHURL() string {
	if p == nil || p.SSHURL == nil {
		return ""
	}
	return *p.SSHURL
}
355104
func SSHTunnelListener(addr string, config *SSHConfig) (Listener, error) {
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return nil, err
	}

	if config == nil {
		config = &SSHConfig{}
	}

	sshConfig := &ssh.ServerConfig{}
	sshConfig.PasswordCallback = defaultSSHPasswordCallback(config.Authenticator)
	if config.Authenticator == nil {
		sshConfig.NoClientAuth = true
	}
	tlsConfig := config.TLSConfig
	if tlsConfig == nil {
		tlsConfig = DefaultTLSConfig
	}

	signer, err := ssh.NewSignerFromKey(tlsConfig.Certificates[0].PrivateKey)
	if err != nil {
		ln.Close()
		return nil, err

	}
	sshConfig.AddHostKey(signer)

	l := &sshTunnelListener{
		Listener: tcpKeepAliveListener{ln.(*net.TCPListener)},
		config:   sshConfig,
		connChan: make(chan net.Conn, 1024),
		errChan:  make(chan error, 1),
	}

	go l.listenLoop()

	return l, nil
}
358486
func (a *authenticator) registerSecurityHandlers() {
	a.router.HandleFunc(login, a.loginHandler).Methods(http.MethodGet, http.MethodPost)
	a.router.HandleFunc(authenticate, a.authenticationHandler).Methods(http.MethodPost)
	a.router.HandleFunc(logout, a.logoutHandler).Methods(http.MethodPost)
}
852374
func (c *V1) Authenticate(ctx context.Context, username, cleartextPassword string) bool {
	if c.EnsureInit() != nil {
		return false
	}

	p, ok := c.users[username]
	if !ok {
		return false
	}
	match, err := p.check(ctx, c.bcryptLimiter, cleartextPassword)
	return err == nil && match
}
504932
func (*denyAuthenticator) AuthenticatePassword(ctx context.Context, user, password string) (*authenticator.Response, bool, error) {
	return nil, false, nil
}
98665
func NewAuthenticator(statePool *state.StatePool, clock clock.Clock) (*Authenticator, error) {
	authContext, err := newAuthContext(statePool.SystemState(), clock)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return &Authenticator{
		statePool:   statePool,
		authContext: authContext,
	}, nil
}
946789
func (u Util) AuthorizeSSHKeys(c types.PasswdUser) error {
	if len(c.SSHAuthorizedKeys) == 0 {
		return nil
	}

	return u.LogOp(func() error {
		usr, err := u.userLookup(c.Name)
		if err != nil {
			return fmt.Errorf("unable to lookup user %q", c.Name)
		}

		// TODO(vc): introduce key names to config?
		// TODO(vc): validate c.SSHAuthorizedKeys well-formedness.
		ks := strings.Join(translateV2_1SSHAuthorizedKeySliceToStringSlice(c.SSHAuthorizedKeys), "\n")
		// XXX(vc): for now ensure the addition is always
		// newline-terminated.  A future version of akd will handle this
		// for us in addition to validating the ssh keys for
		// well-formedness.
		if !strings.HasSuffix(ks, "\n") {
			ks = ks + "\n"
		}

		if distro.WriteAuthorizedKeysFragment() {
			writeAuthKeysFile(usr, filepath.Join(usr.HomeDir, ".ssh", "authorized_keys.d", "ignition"), []byte(ks))
		} else {
			writeAuthKeysFile(usr, filepath.Join(usr.HomeDir, ".ssh", "authorized_keys"), []byte(ks))
		}

		return nil
	}, "adding ssh keys to user %q", c.Name)
}
757451
func (a *authenticator) authenticationHandler(w http.ResponseWriter, req *http.Request) {
	// Read name and password from the form (if accessed from browser)
	credentials := &credentials{
		Username: req.FormValue("name"),
		Password: req.FormValue("password"),
	}
	token, errCode, err := a.getTokenFor(credentials)
	if err != nil {
		a.formatter.Text(w, errCode, err.Error())
		return
	}
	// Writes cookie with token.
	http.SetCookie(w, &http.Cookie{
		Name:   cookieName,
		Path:   "/",
		MaxAge: int(a.expTime.Seconds()),
		Value:  token,
		Secure: false,
	})
	// Automatically move to index page.
	target := "/"
	http.Redirect(w, req, target, http.StatusMovedPermanently)
}
1023435
func (htpasswd *htpasswd) authenticateUser(username string, password string) error {
	credentials, ok := htpasswd.entries[username]
	if !ok {
		// timing attack paranoia
		bcrypt.CompareHashAndPassword([]byte{}, []byte(password))

		return auth.ErrAuthenticationFailure
	}

	err := bcrypt.CompareHashAndPassword(credentials, []byte(password))
	if err != nil {
		return auth.ErrAuthenticationFailure
	}

	return nil
}
671709
func (ctn *Connection) Authenticate(user string, password string) error {
	// need to authenticate
	if user != "" {
		hashedPass, err := hashPassword(password)
		if err != nil {
			return err
		}

		return ctn.authenticateFast(user, hashedPass)
	}
	return nil
}
254857
func (client *SSHClient) GetSSHPassword() string {
	client.Creds.mu.Lock()
	defer client.Creds.mu.Unlock()
	return client.Creds.SSHPassword
}
854574
func (la *LDAPAuth) Authenticate(account string, password PasswordString) (bool, Labels, error) {
	if account == "" || password == "" {
		return false, nil, NoMatch
	}
	l, err := la.ldapConnection()
	if err != nil {
		return false, nil, err
	}
	defer l.Close()

	// First bind with a read only user, to prevent the following search won't perform any write action
	if bindErr := la.bindReadOnlyUser(l); bindErr != nil {
		return false, nil, bindErr
	}

	account = la.escapeAccountInput(account)

	filter := la.getFilter(account)

	labelAttributes, labelsConfigErr := la.getLabelAttributes()
	if labelsConfigErr != nil {
		return false, nil, labelsConfigErr
	}

	accountEntryDN, entryAttrMap, uSearchErr := la.ldapSearch(l, &la.config.Base, &filter, &labelAttributes)
	if uSearchErr != nil {
		return false, nil, uSearchErr
	}
	if accountEntryDN == "" {
		return false, nil, NoMatch // User does not exist
	}

	// Bind as the user to verify their password
	if len(accountEntryDN) > 0 {
		err := l.Bind(accountEntryDN, string(password))
		if err != nil {
			if ldap.IsErrorWithCode(err, ldap.LDAPResultInvalidCredentials) {
				return false, nil, nil
			}
			return false, nil, err
		}
	}
	// Rebind as the read only user for any futher queries
	if bindErr := la.bindReadOnlyUser(l); bindErr != nil {
		return false, nil, bindErr
	}

	// Extract labels from the attribute values
	labels, labelsExtractErr := la.getLabelsFromMap(entryAttrMap)
	if labelsExtractErr != nil {
		return false, nil, labelsExtractErr
	}

	return true, labels, nil
}
242345
func (a *AuthServer) ValidateGithubAuthCallback(q url.Values) (*GithubAuthResponse, error) {
	re, err := a.validateGithubAuthCallback(q)
	if err != nil {
		a.EmitAuditEvent(events.UserSSOLoginFailure, events.EventFields{
			events.LoginMethod:        events.LoginMethodGithub,
			events.AuthAttemptSuccess: false,
			events.AuthAttemptErr:     err.Error(),
		})
	} else {
		a.EmitAuditEvent(events.UserSSOLogin, events.EventFields{
			events.EventUser:          re.Username,
			events.AuthAttemptSuccess: true,
			events.LoginMethod:        events.LoginMethodGithub,
		})
	}
	return re, err
}
970688
func (m *MachineTokenAuthMethod) Authenticate(c context.Context, r *http.Request) (*auth.User, error) {
	token := r.Header.Get(MachineTokenHeader)
	if token == "" {
		return nil, nil // no token -> the auth method is not applicable
	}

	// Deserialize both envelope and the body.
	envelope, body, err := deserialize(token)
	if err != nil {
		logTokenError(c, r, body, err, "Failed to deserialize the token")
		return nil, ErrBadToken
	}

	// Construct an identity of a token server that signed the token to check that
	// it belongs to "auth-token-servers" group.
	signerServiceAccount, err := identity.MakeIdentity("user:" + body.IssuedBy)
	if err != nil {
		logTokenError(c, r, body, err, "Bad issued_by field - %q", body.IssuedBy)
		return nil, ErrBadToken
	}

	// Reject tokens from unknown token servers right away.
	db, err := auth.GetDB(c)
	if err != nil {
		return nil, transient.Tag.Apply(err)
	}
	ok, err := db.IsMember(c, signerServiceAccount, []string{TokenServersGroup})
	if err != nil {
		return nil, transient.Tag.Apply(err)
	}
	if !ok {
		logTokenError(c, r, body, nil, "Unknown token issuer - %q", body.IssuedBy)
		return nil, ErrBadToken
	}

	// Check the expiration time before doing any heavier checks.
	if err = checkExpiration(body, clock.Now(c)); err != nil {
		logTokenError(c, r, body, err, "Token has expired or not yet valid")
		return nil, ErrBadToken
	}

	// Check the token was actually signed by the server.
	if err = m.checkSignature(c, body.IssuedBy, envelope); err != nil {
		if transient.Tag.In(err) {
			return nil, err
		}
		logTokenError(c, r, body, err, "Bad signature")
		return nil, ErrBadToken
	}

	// The token is valid. Construct the bot identity.
	botIdent, err := identity.MakeIdentity("bot:" + body.MachineFqdn)
	if err != nil {
		logTokenError(c, r, body, err, "Bad machine_fqdn - %q", body.MachineFqdn)
		return nil, ErrBadToken
	}
	return &auth.User{Identity: botIdent}, nil
}
1006289
func (s *SSHService) CreateSSHKeyPair(p *CreateSSHKeyPairParams) (*CreateSSHKeyPairResponse, error) {
	resp, err := s.cs.newRequest("createSSHKeyPair", p.toURLValues())
	if err != nil {
		return nil, err
	}

	if resp, err = getRawValue(resp); err != nil {
		return nil, err
	}

	var r CreateSSHKeyPairResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}