// Client -> Server
// - Auth start
//
// Server -> Client
// - B: server public key
// - s: salt
177394
func (setup *SetupServerController) handlePairStart(in util.Container) (util.Container, error) {
	out := util.NewTLV8Container()
	setup.step = PairStepStartResponse

	out.SetByte(TagSequence, setup.step.Byte())
	out.SetBytes(TagPublicKey, setup.session.PublicKey)
	out.SetBytes(TagSalt, setup.session.Salt)

	log.Debug.Println("<-     B:", hex.EncodeToString(out.GetBytes(TagPublicKey)))
	log.Debug.Println("<-     s:", hex.EncodeToString(out.GetBytes(TagSalt)))

	return out, nil
}
442083
func PasswordSalt(password string) string {
	pass := []byte(password)
	salt, _ := bcrypt.GenerateFromPassword(pass, bcrypt.DefaultCost)
	return string(salt)
}
148716
func (s Server) getClientAuth(w *Response, r *http.Request, allowQueryParams bool) *BasicAuth {

	if allowQueryParams {
		// Allow for auth without password
		if _, hasSecret := r.Form["client_secret"]; hasSecret {
			auth := &BasicAuth{
				Username: r.FormValue("client_id"),
				Password: r.FormValue("client_secret"),
			}
			if auth.Username != "" {
				return auth
			}
		}
	}

	auth, err := CheckBasicAuth(r)
	if err != nil {
		s.setErrorAndLog(w, E_INVALID_REQUEST, err, "get_client_auth=%s", "check auth error")
		return nil
	}
	if auth == nil {
		s.setErrorAndLog(w, E_INVALID_REQUEST, errors.New("Client authentication not sent"), "get_client_auth=%s", "client authentication not sent")
		return nil
	}
	return auth
}
263708
func (_m *API) AuthenticateHost(_a0 string) (string, int64, error) {
	ret := _m.Called(_a0)

	var r0 string
	if rf, ok := ret.Get(0).(func(string) string); ok {
		r0 = rf(_a0)
	} else {
		r0 = ret.Get(0).(string)
	}

	var r1 int64
	if rf, ok := ret.Get(1).(func(string) int64); ok {
		r1 = rf(_a0)
	} else {
		r1 = ret.Get(1).(int64)
	}

	var r2 error
	if rf, ok := ret.Get(2).(func(string) error); ok {
		r2 = rf(_a0)
	} else {
		r2 = ret.Error(2)
	}

	return r0, r1, r2
}
1297322
func (h *basicAuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	username, password, _ := r.BasicAuth()
	usernameOk := subtle.ConstantTimeCompare([]byte(h.Username), []byte(username)) == 1
	passwordOk := subtle.ConstantTimeCompare([]byte(h.Password), []byte(password)) == 1
	if !usernameOk || !passwordOk {
		w.Header().Set("WWW-Authenticate", `Basic realm="metrics"`)
		http.Error(w, "Invalid username or password", http.StatusUnauthorized)
		return
	}

	h.nextHandler.ServeHTTP(w, r)
}
329384
func (a BasicAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	var protected, isAuthenticated bool

	for _, rule := range a.Rules {
		for _, res := range rule.Resources {
			if !httpserver.Path(r.URL.Path).Matches(res) {
				continue
			}

			// path matches; this endpoint is protected
			protected = true

			// parse auth header
			username, password, ok := r.BasicAuth()

			// check credentials
			if !ok ||
				username != rule.Username ||
				!rule.Password(password) {
				continue
			}

			// by this point, authentication was successful
			isAuthenticated = true

			// remove credentials from request to avoid leaking upstream
			r.Header.Del("Authorization")
		}
	}

	if protected && !isAuthenticated {
		// browsers show a message that says something like:
		// "The website says: <realm>"
		// which is kinda dumb, but whatever.
		w.Header().Set("WWW-Authenticate", "Basic realm=\"Restricted\"")
		return http.StatusUnauthorized, nil
	}

	// Pass-through when no paths match
	return a.Next.ServeHTTP(w, r)
}
931878
func main() {
	ws := new(restful.WebService)
	ws.Route(ws.GET("/secret").Filter(basicAuthenticate).To(secret))
	restful.Add(ws)
	log.Fatal(http.ListenAndServe(":8080", nil))
}
302317
func serverAuth(server string) string {
	configOnce.Do(parseConfig)
	alias := config.Alias(server)
	if alias == "" {
		return ""
	}
	return config.Servers[alias].Auth
}
775017
func (c *RPCClient) auth(authKey string) error {
	header := requestHeader{
		Command: authCommand,
		Seq:     c.getSeq(),
	}
	req := authRequest{
		AuthKey: authKey,
	}
	return c.genericRPC(&header, &req, nil)
}
808677
func Basic(username string, password string) macaron.Handler {
	var siteAuth = base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
	return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
		auth := req.Header.Get("Authorization")
		if !SecureCompare(auth, basicPrefix+siteAuth) {
			basicUnauthorized(res)
			return
		}
		c.Map(User(username))
	}
}
873869
func (u *Client) ClientCredentialGrant(clientId, clientSecret string) (string, error) {
	values := url.Values{
		"grant_type":    {"client_credentials"},
		"response_type": {"token"},
		"client_id":     {clientId},
		"client_secret": {clientSecret},
	}

	token, err := u.tokenGrantRequest(values)

	return token.AccessToken, err
}
922135
func (w *Wrapper) UpsertAuthServer(s services.Server) error {
	return w.Write.UpsertAuthServer(s)
}
710338
func (c *Cipher) InitSaltedCipher(key, salt []byte) error {
	k := len(key)
	if k < 4 {
		return KeySizeError(k)
	}
	initCipher(key, c)
	expandKeyWithSalt(key, salt, c)
	return nil
}
1143498
func crypt(key, salt string) string {
	cdata := C.struct_crypt_data{}
	ckey := C.CString(key)
	csalt := C.CString(salt)
	result := C.GoString(C.crypt_r(ckey, csalt, &cdata))
	C.free(unsafe.Pointer(ckey))
	C.free(unsafe.Pointer(csalt))
	return result
}
1135430
func (f *CryptoFuncs) PBKDF2(password, salt, iter, keylen interface{}, hashFunc ...string) (k string, err error) {
	var h gcrypto.Hash
	if len(hashFunc) == 0 {
		h = gcrypto.SHA1
	} else {
		h, err = crypto.StrToHash(hashFunc[0])
		if err != nil {
			return "", err
		}
	}
	pw := toBytes(password)
	s := toBytes(salt)
	i := conv.ToInt(iter)
	kl := conv.ToInt(keylen)

	dk, err := crypto.PBKDF2(pw, s, i, kl, h)
	return fmt.Sprintf("%02x", dk), err
}
461663
func Login(c *client.Client, username, password string) (string, error) {
	user := api.AuthLoginRequest{Username: username, Password: password}
	reqBody, err := json.Marshal(user)

	if err != nil {
		return "", err
	}

	body, err := c.BasicRequest("POST", "/v1/auth/login/", reqBody)

	if err != nil {
		return "", err
	}

	token := api.AuthLoginResponse{}
	if err = json.Unmarshal([]byte(body), &token); err != nil {
		return "", err
	}

	return token.Token, nil
}
1374557
func BasicAuth(username, password string) http.HandlerFunc {
	// Inspired by https://github.com/codegangsta/martini-contrib/blob/master/auth/
	return func(res http.ResponseWriter, req *http.Request) {
		if !secureCompare(req.Header.Get("Authorization"),
			"Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password)),
		) {
			res.Header().Set("WWW-Authenticate",
				"Basic realm=\"Authorization Required\"",
			)
			http.Error(res, "Not Authorized", http.StatusUnauthorized)
		}
	}
}