// handleCapabilitiesAccessor returns the ACL capabilities of the
// token associated with the given accessor for a given path.
487658
func (b *SystemBackend) handleCapabilitiesAccessor(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
	accessor := d.Get("accessor").(string)
	if accessor == "" {
		return logical.ErrorResponse("missing accessor"), nil
	}

	aEntry, err := b.Core.tokenStore.lookupByAccessor(ctx, accessor, false, false)
	if err != nil {
		return nil, err
	}

	d.Raw["token"] = aEntry.TokenID
	return b.handleCapabilities(ctx, req, d)
}
977739
func (r *rpcHandler) handleAcceptErr(ctx context.Context, err error, loopDelay *time.Duration) {
	const baseDelay = 5 * time.Millisecond
	const maxDelayPerm = 5 * time.Second
	const maxDelayTemp = 1 * time.Second

	if *loopDelay == 0 {
		*loopDelay = baseDelay
	} else {
		*loopDelay *= 2
	}

	temporaryError := false
	if ne, ok := err.(net.Error); ok && ne.Temporary() {
		temporaryError = true
	}

	if temporaryError && *loopDelay > maxDelayTemp {
		*loopDelay = maxDelayTemp
	} else if *loopDelay > maxDelayPerm {
		*loopDelay = maxDelayPerm
	}

	r.logger.Error("failed to accept RPC conn", "error", err, "delay", *loopDelay)

	select {
	case <-ctx.Done():
	case <-time.After(*loopDelay):
	}
}
329452
func (a *AuthorizationServer) HandlerAccessToken(request http.Request, response http.Response) (string, error) {
	grantType := request.GetParam(util.OAUTH_GRANT_TYPE)

	if grantType == "" {
		Logger.Debug("GrantType not found %s", grantType)
		return "", util.NewInvalidRequestError(grantType)
	}

	if _, ok := a.grants[grantType]; !ok {
		return "", util.NewUnSupportedGrantTypeError(grantType)
	}

	message, err := a.grants[grantType].HandleResponse(request)
	if err != nil {
		return "", err
	}

	if message == nil {
		return "", util.NewOAuthRuntimeError()
	}

	return message.Encode(), nil
}
679421
func ValidateControllerAccess(access Access) error {
	switch access {
	case LoginAccess, SuperuserAccess:
		return nil
	}
	return errors.NotValidf("%q controller access", access)
}
1071246
func (s *Server) handleAuthorization(w http.ResponseWriter, r *http.Request) {
	authReq, err := s.parseAuthorizationRequest(r)
	if err != nil {
		s.logger.Errorf("Failed to parse authorization request: %v", err)
		if handler, ok := err.Handle(); ok {
			// client_id and redirect_uri checked out and we can redirect back to
			// the client with the error.
			handler.ServeHTTP(w, r)
			return
		}

		// Otherwise render the error to the user.
		//
		// TODO(ericchiang): Should we just always render the error?
		s.renderError(w, err.Status(), err.Error())
		return
	}

	// TODO(ericchiang): Create this authorization request later in the login flow
	// so users don't hit "not found" database errors if they wait at the login
	// screen too long.
	//
	// See: https://github.com/dexidp/dex/issues/646
	authReq.Expiry = s.now().Add(s.authRequestsValidFor)
	if err := s.storage.CreateAuthRequest(authReq); err != nil {
		s.logger.Errorf("Failed to create authorization request: %v", err)
		s.renderError(w, http.StatusInternalServerError, "Failed to connect to the database.")
		return
	}

	connectors, e := s.storage.ListConnectors()
	if e != nil {
		s.logger.Errorf("Failed to get list of connectors: %v", err)
		s.renderError(w, http.StatusInternalServerError, "Failed to retrieve connector list.")
		return
	}

	if len(connectors) == 1 {
		for _, c := range connectors {
			// TODO(ericchiang): Make this pass on r.URL.RawQuery and let something latter
			// on create the auth request.
			http.Redirect(w, r, s.absPath("/auth", c.ID)+"?req="+authReq.ID, http.StatusFound)
			return
		}
	}

	connectorInfos := make([]connectorInfo, len(connectors))
	i := 0
	for _, conn := range connectors {
		connectorInfos[i] = connectorInfo{
			ID:   conn.ID,
			Name: conn.Name,
			// TODO(ericchiang): Make this pass on r.URL.RawQuery and let something latter
			// on create the auth request.
			URL: s.absPath("/auth", conn.ID) + "?req=" + authReq.ID,
		}
		i++
	}

	if err := s.templates.login(w, connectorInfos); err != nil {
		s.logger.Errorf("Server template error: %v", err)
	}
}
964950
func (v *Validator) CheckCapabilities() (errs error) {
	if v.platform != "linux" {
		errs = multierror.Append(errs, fmt.Errorf("For %q platform, the configuration structure does not support process.capabilities", v.platform))
		return
	}

	process := v.spec.Process
	var effective, permitted, inheritable, ambient bool
	caps := make(map[string][]string)

	for _, cap := range process.Capabilities.Bounding {
		caps[cap] = append(caps[cap], "bounding")
	}
	for _, cap := range process.Capabilities.Effective {
		caps[cap] = append(caps[cap], "effective")
	}
	for _, cap := range process.Capabilities.Inheritable {
		caps[cap] = append(caps[cap], "inheritable")
	}
	for _, cap := range process.Capabilities.Permitted {
		caps[cap] = append(caps[cap], "permitted")
	}
	for _, cap := range process.Capabilities.Ambient {
		caps[cap] = append(caps[cap], "ambient")
	}

	for capability, owns := range caps {
		if err := CapValid(capability, v.HostSpecific); err != nil {
			errs = multierror.Append(errs, fmt.Errorf("capability %q is not valid, man capabilities(7)", capability))
		}

		effective, permitted, ambient, inheritable = false, false, false, false
		for _, set := range owns {
			if set == "effective" {
				effective = true
				continue
			}
			if set == "inheritable" {
				inheritable = true
				continue
			}
			if set == "permitted" {
				permitted = true
				continue
			}
			if set == "ambient" {
				ambient = true
				continue
			}
		}
		if effective && !permitted {
			errs = multierror.Append(errs, fmt.Errorf("effective capability %q is not allowed, as it's not permitted", capability))
		}
		if ambient && !(permitted && inheritable) {
			errs = multierror.Append(errs, fmt.Errorf("ambient capability %q is not allowed, as it's not permitted and inheribate", capability))
		}
	}

	return
}
750046
func TokenHandler(cb AuthTokenHandler) Option {
	return func(o *Options) error {
		if o.Token != "" {
			return ErrTokenAlreadySet
		}
		o.TokenHandler = cb
		return nil
	}
}
1256317
func makeAccessible(path string, uid, gid int) error {
	for ; path != "/"; path = filepath.Dir(path) {
		st, err := os.Stat(path)
		if err != nil {
			if os.IsNotExist(err) {
				return nil
			}
			return err
		}
		if int(st.Sys().(*syscall.Stat_t).Uid) == uid && int(st.Sys().(*syscall.Stat_t).Gid) == gid {
			continue
		}
		if st.Mode()&0111 != 0111 {
			if err := os.Chmod(path, st.Mode()|0111); err != nil {
				return err
			}
		}
	}
	return nil
}
1060709
func canAccessFile(path string) bool {
	if fi, err := os.Stat(path); err == nil {
		return fi.Mode().Perm()&0400 != 0
	}
	return false
}
305502
func (a *ACL) AllowNamespaceOperation(ns string, op string) bool {
	// Hot path management tokens
	if a.management {
		return true
	}

	// Check for a matching capability set
	capabilities, ok := a.matchingCapabilitySet(ns)
	if !ok {
		return false
	}

	// Check if the capability has been granted
	return capabilities.Check(op)
}
959893
func (s *Secret) TokenAccessor() (string, error) {
	if s == nil {
		return "", nil
	}

	if s.Auth != nil && len(s.Auth.Accessor) > 0 {
		return s.Auth.Accessor, nil
	}

	if s.Data == nil || s.Data["accessor"] == nil {
		return "", nil
	}

	accessor, ok := s.Data["accessor"].(string)
	if !ok {
		return "", fmt.Errorf("token found but in the wrong format")
	}

	return accessor, nil
}
883481
func (m *model) handleAutoAccepts(deviceCfg config.DeviceConfiguration, folder protocol.Folder) bool {
	if cfg, ok := m.cfg.Folder(folder.ID); !ok {
		defaultPath := m.cfg.Options().DefaultFolderPath
		defaultPathFs := fs.NewFilesystem(fs.FilesystemTypeBasic, defaultPath)
		pathAlternatives := []string{
			sanitizePath(folder.Label),
			sanitizePath(folder.ID),
		}
		for _, path := range pathAlternatives {
			if _, err := defaultPathFs.Lstat(path); !fs.IsNotExist(err) {
				continue
			}

			fcfg := config.NewFolderConfiguration(m.id, folder.ID, folder.Label, fs.FilesystemTypeBasic, filepath.Join(defaultPath, path))
			fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{
				DeviceID: deviceCfg.DeviceID,
			})
			// Need to wait for the waiter, as this calls CommitConfiguration,
			// which sets up the folder and as we return from this call,
			// ClusterConfig starts poking at m.folderFiles and other things
			// that might not exist until the config is committed.
			w, _ := m.cfg.SetFolder(fcfg)
			w.Wait()

			l.Infof("Auto-accepted %s folder %s at path %s", deviceCfg.DeviceID, folder.Description(), fcfg.Path)
			return true
		}
		l.Infof("Failed to auto-accept folder %s from %s due to path conflict", folder.Description(), deviceCfg.DeviceID)
		return false
	} else {
		for _, device := range cfg.DeviceIDs() {
			if device == deviceCfg.DeviceID {
				// Already shared nothing todo.
				return false
			}
		}
		cfg.Devices = append(cfg.Devices, config.FolderDeviceConfiguration{
			DeviceID: deviceCfg.DeviceID,
		})
		w, _ := m.cfg.SetFolder(cfg)
		w.Wait()
		l.Infof("Shared %s with %s due to auto-accept", folder.ID, deviceCfg.DeviceID)
		return true
	}
}
693279
func (settings FileSettings) ClientCertificateAuthorizerWithResource(resource string) (autorest.Authorizer, error) {
	cfg, err := settings.clientCertificateConfigWithResource(resource)
	if err != nil {
		return nil, err
	}
	return cfg.Authorizer()
}
697262
func (b *SystemBackend) handleAuthTuneRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	path := data.Get("path").(string)
	if path == "" {
		return logical.ErrorResponse(
				"path must be specified as a string"),
			logical.ErrInvalidRequest
	}
	return b.handleTuneReadCommon(ctx, "auth/"+path)
}
1151722
func (m *Internal) KeyringOperation(
	args *structs.KeyringRequest,
	reply *structs.KeyringResponses) error {

	// Check ACLs
	rule, err := m.srv.ResolveToken(args.Token)
	if err != nil {
		return err
	}
	if rule != nil {
		switch args.Operation {
		case structs.KeyringList:
			if !rule.KeyringRead() {
				return fmt.Errorf("Reading keyring denied by ACLs")
			}
		case structs.KeyringInstall:
			fallthrough
		case structs.KeyringUse:
			fallthrough
		case structs.KeyringRemove:
			if !rule.KeyringWrite() {
				return fmt.Errorf("Modifying keyring denied due to ACLs")
			}
		default:
			panic("Invalid keyring operation")
		}
	}

	// Only perform WAN keyring querying and RPC forwarding once
	if !args.Forwarded && m.srv.serfWAN != nil {
		args.Forwarded = true
		m.executeKeyringOp(args, reply, true)
		return m.srv.globalRPC("Internal.KeyringOperation", args, reply)
	}

	// Query the LAN keyring of this node's DC
	m.executeKeyringOp(args, reply, false)
	return nil
}
224601
func (st *State) setControllerAccess(access permission.Access, userGlobalKey string) error {
	if err := permission.ValidateControllerAccess(access); err != nil {
		return errors.Trace(err)
	}
	op := updatePermissionOp(controllerKey(st.ControllerUUID()), userGlobalKey, access)

	err := st.db().RunTransaction([]txn.Op{op})
	if err == txn.ErrAborted {
		return errors.NotFoundf("existing permissions")
	}
	return errors.Trace(err)
}
371891
func (service *Service) AuthorizeHandler(w http.ResponseWriter, request *http.Request) {

	err := request.ParseForm()
	if err != nil {
		log.Debug("ERROR parsing form", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	//Check if the requested authorization grant type is supported
	requestedResponseType := request.Form.Get("response_type")
	if requestedResponseType != AuthorizationGrantCodeType {
		log.Debug("Invalid authorization grant type requested")
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	//Check if the user is already authenticated, if not, redirect to the login page before returning here
	var protectedSession bool
	username, err := service.GetWebuser(request, w)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if username == "" {
		username, err = service.GetOauthUser(request, w)
		if err != nil {
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		if username != "" {
			log.Debug("protected session")
			protectedSession = true
		} else {
			redirectToNextPage(w, request)
			return
		}
	}

	//Validate client and redirect_uri
	redirectURI, err := url.QueryUnescape(request.Form.Get("redirect_uri"))
	if err != nil {
		log.Debug("Unparsable redirect_uri")
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	clientID := request.Form.Get("client_id")
	mgr := NewManager(request)
	valid, err := validateRedirectURI(mgr, redirectURI, clientID)
	if err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if !valid {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	requestedScopes := oauth2.SplitScopeString(request.Form.Get("scope"))
	possibleScopes, err := service.filterPossibleScopes(request, username, requestedScopes, true)
	if err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	authorizedScopes, err := service.filterAuthorizedScopes(request, username, clientID, possibleScopes)
	if err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	var authorizedScopeString string
	var validAuthorization bool

	if authorizedScopes != nil {
		authorizedScopeString = strings.Join(authorizedScopes, ",")
		validAuthorization = IsAuthorizationValid(possibleScopes, authorizedScopes)

		// Check if the user still has the given authorizations
		authorization, err := user.NewManager(request).GetAuthorization(username, clientID)
		if err != nil {
			log.Error("Failed to load authorization: ", err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		if validAuthorization {
			validAuthorization, err = UserHasAuthorizedScopes(request, authorization)
			if err != nil {
				log.Error("Failed to check if authorizated labels are still present: ", err)
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
				return
			}
		}

		//Check if we are redirected from the authorize page, it might be that not all authorizations were given,
		// authorize the login but only with the authorized scopes
		referrer := request.Header.Get("Referer")
		if referrer != "" && !validAuthorization { //If we already have a valid authorization, no need to check if we come from the authorize page
			if referrerURL, e := url.Parse(referrer); e == nil {
				validAuthorization = referrerURL.Host == request.Host && referrerURL.Path == "/authorize"
			} else {
				log.Debug("Error parsing referrer: ", e)
			}
		}
	}

	//If no valid authorization, ask the user for authorizations
	if !validAuthorization {
		if protectedSession {
			log.Debug("protected session active, but need to give authorizations")
			// We need a full session to give authorizations, so remove the l2fa entry
			// This way the login function will require 2fa and give a full session with admin scopes
			l2faMgr := organizationdb.NewLast2FAManager(request)
			if l2faMgr.Exists(clientID, username) {
				err = l2faMgr.RemoveLast2FA(clientID, username)
				if err != nil {
					log.Error(err)
					http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
					return
				}
			}
			redirectToNextPage(w, request)
			return
		}
		token, e := service.createItsYouOnlineAdminToken(username, request)
		if e != nil {
			log.Error(e)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		service.sessionService.SetAPIAccessToken(w, token)
		redirectToScopeRequestPage(w, request, possibleScopes)
		return
	}

	if clientID == "itsyouonline" {
		log.Warn("HACK attempt, someone tried to get a token as the 'itsyouonline' client")
		//TODO: log the entire request and everything we know
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	redirectURI, err = handleAuthorizationGrantCodeType(request, username, clientID, redirectURI, authorizedScopeString)

	if err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	log.Debug("Redirecting from authorize handler to: ", redirectURI)
	http.Redirect(w, request, redirectURI, http.StatusFound)

}