// Negotiate is part of the AuthServer interface.
// It will be called if Method is anything else than MysqlNativePassword.
// We only recognize MysqlClearPassword and MysqlDialog here.
760497
func (a *AuthServerStatic) Negotiate(c *Conn, user string, remoteAddr net.Addr) (Getter, error) {
	// Finish the negotiation.
	password, err := AuthServerNegotiateClearOrDialog(c, a.Method)
	if err != nil {
		return nil, err
	}

	a.mu.Lock()
	entries, ok := a.Entries[user]
	a.mu.Unlock()

	if !ok {
		return &StaticUserData{}, NewSQLError(ERAccessDeniedError, SSAccessDeniedError, "Access denied for user '%v'", user)
	}
	for _, entry := range entries {
		// Validate the password.
		if matchSourceHost(remoteAddr, entry.SourceHost) && entry.Password == password {
			return &StaticUserData{entry.UserData, entry.Groups}, nil
		}
	}
	return &StaticUserData{}, NewSQLError(ERAccessDeniedError, SSAccessDeniedError, "Access denied for user '%v'", user)
}
1311890
func PasswordAuth(fn PasswordHandler) Option {
	return func(srv *Server) error {
		srv.PasswordHandler = fn
		return nil
	}
}
854586
func NegotiateClaim(ctx context.Context, audience string, conn *amqp.Client, provider auth.TokenProvider) error {
	span, ctx := tracing.StartSpanFromContext(ctx, "az-amqp-common.cbs.NegotiateClaim")
	defer span.End()

	link, err := rpc.NewLink(conn, cbsAddress)
	if err != nil {
		return err
	}
	defer link.Close(ctx)

	token, err := provider.GetToken(audience)
	if err != nil {
		return err
	}

	log.For(ctx).Debug(fmt.Sprintf("negotiating claim for audience %s with token type %s and expiry of %s", audience, token.TokenType, token.Expiry))
	msg := &amqp.Message{
		Value: token.Token,
		ApplicationProperties: map[string]interface{}{
			cbsOperationKey:  cbsOperationPutToken,
			cbsTokenTypeKey:  string(token.TokenType),
			cbsAudienceKey:   audience,
			cbsExpirationKey: token.Expiry,
		},
	}

	res, err := link.RetryableRPC(ctx, 3, 1*time.Second, msg)
	if err != nil {
		log.For(ctx).Error(err)
		return err
	}

	log.For(ctx).Debug(fmt.Sprintf("negotiated with response code %d and message: %s", res.Code, res.Description))
	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
}
484919
func (p *Peer) negotiateOutboundProtocol() error {
	if err := p.writeLocalVersionMsg(); err != nil {
		return err
	}

	return p.readRemoteVersionMsg()
}
556492
func (p *Prober) Solve(authorizations []acme.Authorization) error {
	failures := make(obtainError)

	var authSolvers []*selectedAuthSolver
	var authSolversSequential []*selectedAuthSolver

	// Loop through the resources, basically through the domains.
	// First pass just selects a solver for each authz.
	for _, authz := range authorizations {
		domain := challenge.GetTargetedDomain(authz)
		if authz.Status == acme.StatusValid {
			// Boulder might recycle recent validated authz (see issue #267)
			log.Infof("[%s] acme: authorization already valid; skipping challenge", domain)
			continue
		}

		if solvr := p.solverManager.chooseSolver(authz); solvr != nil {
			authSolver := &selectedAuthSolver{authz: authz, solver: solvr}

			switch s := solvr.(type) {
			case sequential:
				if ok, _ := s.Sequential(); ok {
					authSolversSequential = append(authSolversSequential, authSolver)
				} else {
					authSolvers = append(authSolvers, authSolver)
				}
			default:
				authSolvers = append(authSolvers, authSolver)
			}
		} else {
			failures[domain] = fmt.Errorf("[%s] acme: could not determine solvers", domain)
		}
	}

	parallelSolve(authSolvers, failures)

	sequentialSolve(authSolversSequential, failures)

	// Be careful not to return an empty failures map,
	// for even an empty obtainError is a non-nil error value
	if len(failures) > 0 {
		return failures
	}
	return nil
}
474162
func (s mysqlSource) MySQLConfig() (*mysql.Config, error) {
	cfg, err := mysql.ParseDSN(string(s))
	if err != nil {
		return nil, errors.Wrap(err, `failed to parse DSN`)
	}

	// because _I_ need support for tls, I'm going to handle setting up
	// the tls stuff, by using
	// tls=true&ssl-ca=file=...&ssl-cert=...&ssql-secret=...
	if v, err := strconv.ParseBool(cfg.TLSConfig); err == nil && v {
		sslCa := cfg.Params["ssl-ca"]
		sslCert := cfg.Params["ssl-cert"]
		sslSecret := cfg.Params["ssl-secret"]
		if sslCa == "" || sslCert == "" || sslSecret == "" {
			return nil, errors.New(`to enable tls, you must provide ssl-ca, ssl-cert, and ssl-secret parameters to the DSN`)
		}

		// When comparing two mysql schemas against eachother, we will have
		// multiple calls to RegisterTLSConfig, and in that case we need
		// unique names for both.
		//
		// Here, we do the poor man's UUID, and create a unique name
		b := make([]byte, 16)
		rand.Reader.Read(b)
		b[6] = (b[6] & 0x0F) | 0x40
		b[8] = (b[8] &^ 0x40) | 0x80
		tlsName := fmt.Sprintf("custom-tls-%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])

		rootCertPool := x509.NewCertPool()
		pem, err := ioutil.ReadFile(sslCa)
		if err != nil {
			return nil, errors.Wrap(err, `failed to read ssl-ca file`)
		}

		if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
			return nil, errors.New(`failed to append ssl-ca PEM to cert pool`)
		}
		certs, err := tls.LoadX509KeyPair(sslCert, sslSecret)
		if err != nil {
			return nil, errors.Wrap(err, `failed to load X509 key pair`)
		}
		mysql.RegisterTLSConfig(tlsName, &tls.Config{
			RootCAs:      rootCertPool,
			Certificates: []tls.Certificate{certs},
		})
		cfg.TLSConfig = tlsName
	}
	return cfg, nil
}
472281
func NegotiateMediaTypeOptions(header string, accepted []runtime.SerializerInfo, endpoint EndpointRestrictions) (MediaTypeOptions, bool) {
	if len(header) == 0 && len(accepted) > 0 {
		return MediaTypeOptions{
			Accepted: accepted[0],
		}, true
	}

	var candidates candidateMediaTypeSlice
	clauses := goautoneg.ParseAccept(header)
	for _, clause := range clauses {
		for i := range accepted {
			accepts := &accepted[i]
			switch {
			case clause.Type == accepts.MediaTypeType && clause.SubType == accepts.MediaTypeSubType,
				clause.Type == accepts.MediaTypeType && clause.SubType == "*",
				clause.Type == "*" && clause.SubType == "*":
				candidates = append(candidates, candidateMediaType{accepted: accepts, clauses: clause})
			}
		}
	}

	for _, v := range candidates {
		if retVal, ret := acceptMediaTypeOptions(v.clauses.Params, v.accepted, endpoint); ret {
			return retVal, true
		}
	}

	return MediaTypeOptions{}, false
}
707199
func (r *redirector) AuthenticationChallenge(req *http.Request) (http.Header, error) {
	redirectURL, err := buildRedirectURL(r.RedirectURL, r.BaseRequestURL, req.URL)
	if err != nil {
		return nil, err
	}
	headers := http.Header{}
	headers.Add("Location", redirectURL.String())
	return headers, nil
}
123317
func (cli *Client) negotiateAPIVersionPing(p types.Ping) {
	// try the latest version before versioning headers existed
	if p.APIVersion == "" {
		p.APIVersion = "1.24"
	}

	// if the client is not initialized with a version, start with the latest supported version
	if cli.version == "" {
		cli.version = api.DefaultVersion
	}

	// if server version is lower than the client version, downgrade
	if versions.LessThan(p.APIVersion, cli.version) {
		cli.version = p.APIVersion
	}

	// Store the results, so that automatic API version negotiation (if enabled)
	// won't be performed on the next request.
	if cli.negotiateVersion {
		cli.negotiated = true
	}
}
788746
func (c *Client) GrantOffer(user, access string, offerURLs ...string) error {
	return c.modifyOfferUser(params.GrantOfferAccess, user, access, offerURLs)
}
947916
func (a *AskPassCredentialHelper) args(prompt string) []string {
	if len(prompt) == 0 {
		return nil
	}
	return []string{prompt}
}
879856
func Auth(authorizer Authorizer, next http.Handler) http.HandlerFunc {
	// Heavily inspired by:
	// https://github.com/syncthing/syncthing/blob/161326c5489d000972a6846564f0ce12779bd8f2/cmd/syncthing/gui_auth.go
	return func(w http.ResponseWriter, r *http.Request) {
		cookie, err := r.Cookie(authCookieName)
		if err == nil && cookie != nil {
			// FIXME use RWMutex
			sessionsMut.Lock()
			_, ok := sessions[cookie.Value]
			sessionsMut.Unlock()
			if ok {
				next.ServeHTTP(w, r)
				return
			}
		}
		error := func() {
			// Mitigate risk of timing attacks.
			// https://en.wikipedia.org/wiki/Timing_attack
			// FIXME use crypto/rand
			time.Sleep(time.Duration(rand.Intn(100)+100) * time.Millisecond)
			w.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		}
		username, passwd, ok := r.BasicAuth()
		if !ok {
			error()
			return
		}
		if !authorizer.Verify(username, passwd) {
			error()
			return
		}
		sessionid := randomString(32)
		sessionsMut.Lock()
		sessions[sessionid] = struct{}{}
		sessionsMut.Unlock()
		http.SetCookie(w, &http.Cookie{
			Name:   authCookieName,
			Value:  sessionid,
			MaxAge: 0,
		})
		next.ServeHTTP(w, r)
	}
}
836513
func (au *LocalAuthenticator) Authenticate(user, password string) bool {
	if au == nil {
		return true
	}

	au.mux.RLock()
	defer au.mux.RUnlock()

	if len(au.kvs) == 0 {
		return true
	}

	v, ok := au.kvs[user]
	return ok && (v == "" || password == v)
}
263163
func (p *MySQLPrivilege) RequestVerification(activeRoles []*auth.RoleIdentity, user, host, db, table, column string, priv mysql.PrivilegeType) bool {
	roleList := p.FindAllRole(activeRoles)
	roleList = append(roleList, &auth.RoleIdentity{Username: user, Hostname: host})

	var userPriv, dbPriv, tablePriv, columnPriv mysql.PrivilegeType
	for _, r := range roleList {
		userRecord := p.matchUser(r.Username, r.Hostname)
		if userRecord != nil {
			userPriv |= userRecord.Privileges
		}
	}
	if userPriv&priv > 0 {
		return true
	}

	for _, r := range roleList {
		dbRecord := p.matchDB(r.Username, r.Hostname, db)
		if dbRecord != nil {
			dbPriv |= dbRecord.Privileges
		}
	}
	if dbPriv&priv > 0 {
		return true
	}

	for _, r := range roleList {
		tableRecord := p.matchTables(r.Username, r.Hostname, db, table)
		if tableRecord != nil {
			tablePriv |= tableRecord.TablePriv
			if column != "" {
				columnPriv |= tableRecord.ColumnPriv
			}
		}
	}
	if tablePriv&priv > 0 || columnPriv&priv > 0 {
		return true
	}

	columnPriv = 0
	for _, r := range roleList {
		columnRecord := p.matchColumns(r.Username, r.Hostname, db, table, column)
		if columnRecord != nil {
			columnPriv |= columnRecord.ColumnPriv
		}
	}
	if columnPriv&priv > 0 {
		return true
	}

	return priv == 0
}
1338028
func (a denyPasswordAuthenticator) AuthenticatePassword(ctx context.Context, username, password string) (*authenticator.Response, bool, error) {
	return nil, false, nil
}
148092
func (msm *MultistreamMuxer) NegotiateLazy(rwc io.ReadWriteCloser) (Multistream, string, HandlerFunc, error) {
	pval := make(chan string, 1)
	writeErr := make(chan error, 1)
	defer close(pval)

	lzc := &lazyServerConn{
		con: rwc,
	}

	started := make(chan struct{})
	go lzc.waitForHandshake.Do(func() {
		close(started)

		defer close(writeErr)

		if err := delimWriteBuffered(rwc, []byte(ProtocolID)); err != nil {
			lzc.werr = err
			writeErr <- err
			return
		}

		for proto := range pval {
			if err := delimWriteBuffered(rwc, []byte(proto)); err != nil {
				lzc.werr = err
				writeErr <- err
				return
			}
		}
	})
	<-started

	line, err := ReadNextToken(rwc)
	if err != nil {
		return nil, "", nil, err
	}

	if line != ProtocolID {
		rwc.Close()
		return nil, "", nil, ErrIncorrectVersion
	}

loop:
	for {
		// Now read and respond to commands until they send a valid protocol id
		tok, err := ReadNextToken(rwc)
		if err != nil {
			rwc.Close()
			return nil, "", nil, err
		}

		switch tok {
		case "ls":
			select {
			case pval <- "ls":
			case err := <-writeErr:
				rwc.Close()
				return nil, "", nil, err
			}
		default:
			h := msm.findHandler(tok)
			if h == nil {
				select {
				case pval <- "na":
				case err := <-writeErr:
					rwc.Close()
					return nil, "", nil, err
				}
				continue loop
			}

			select {
			case pval <- tok:
			case <-writeErr:
				// explicitly ignore this error. It will be returned to any
				// writers and if we don't plan on writing anything, we still
				// want to complete the handshake
			}

			// hand off processing to the sub-protocol handler
			return lzc, tok, h.Handle, nil
		}
	}
}