auth.rb 13.1 KB
Newer Older
1 2
# frozen_string_literal: true

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
3
module Gitlab
4
  module Auth
5
    MissingPersonalAccessTokenError = Class.new(StandardError)
6
    IpBlacklisted = Class.new(StandardError)
7

8
    # Scopes used for GitLab API access
9
    API_SCOPES = [:api, :read_user, :read_api].freeze
10 11 12 13 14

    # Scopes used for GitLab Repository access
    REPOSITORY_SCOPES = [:read_repository, :write_repository].freeze

    # Scopes used for GitLab Docker Registry access
15
    REGISTRY_SCOPES = [:read_registry, :write_registry].freeze
16

17 18
    # Scopes used for GitLab as admin
    ADMIN_SCOPES = [:sudo].freeze
19

20
    # Scopes used for OpenID Connect
21 22
    OPENID_SCOPES = [:openid].freeze

23 24 25
    # OpenID Connect profile scopes
    PROFILE_SCOPES = [:profile, :email].freeze

26
    # Default scopes for OAuth applications that don't define their own
27
    DEFAULT_SCOPES = [:api].freeze
28

29 30
    CI_JOB_USER = 'gitlab-ci-token'

31
    class << self
32
      prepend_mod_with('Gitlab::Auth') # rubocop: disable Cop/InjectEnterpriseEditionModule
33

34 35
      def omniauth_enabled?
        Gitlab.config.omniauth.enabled
36 37
      end

38
      def find_for_git_client(login, password, project:, ip:)
39 40
        raise "Must provide an IP for rate limiting" if ip.nil?

41 42 43 44
        rate_limiter = Gitlab::Auth::IpRateLimiter.new(ip)

        raise IpBlacklisted if !skip_rate_limit?(login: login) && rate_limiter.banned?

45 46 47
        # `user_with_password_for_git` should be the last check
        # because it's the most expensive, especially when LDAP
        # is enabled.
48
        result =
49
          service_request_check(login, password, project) ||
50
          build_access_token_check(login, password) ||
51
          lfs_token_check(login, password, project) ||
52
          oauth_access_token_check(login, password) ||
53
          personal_access_token_check(password, project) ||
54
          deploy_token_check(login, password, project) ||
55
          user_with_password_for_git(login, password) ||
56
          Gitlab::Auth::Result.new
57

58
        rate_limit!(rate_limiter, success: result.success?, login: login)
59
        look_to_limit_user(result.actor)
60

61
        return result if result.success? || authenticate_using_internal_or_ldap_password?
62 63 64

        # If sign-in is disabled and LDAP is not configured, recommend a
        # personal access token on failed auth attempts
65
        raise Gitlab::Auth::MissingPersonalAccessTokenError
66 67
      end

68 69 70 71 72 73 74 75 76
      # Find and return a user if the provided password is valid for various
      # authenticators (OAuth, LDAP, Local Database).
      #
      # Specify `increment_failed_attempts: true` to increment Devise `failed_attempts`.
      # CAUTION: Avoid incrementing failed attempts when authentication falls through
      # different mechanisms, as in `.find_for_git_client`. This may lead to
      # unwanted access locks when the value provided for `password` was actually
      # a PAT, deploy token, etc.
      def find_with_user_password(login, password, increment_failed_attempts: false)
77 78
        # Avoid resource intensive checks if login credentials are not provided
        return unless login.present? && password.present?
79

80 81 82 83
        # Nothing to do here if internal auth is disabled and LDAP is
        # not configured
        return unless authenticate_using_internal_or_ldap_password?

84 85
        Gitlab::Auth::UniqueIpsLimiter.limit_user! do
          user = User.by_login(login)
86

87
          break if user && !can_user_login_with_non_expired_password?(user)
88 89 90 91 92 93 94 95 96 97 98 99 100

          authenticators = []

          if user
            authenticators << Gitlab::Auth::OAuth::Provider.authentication(user, 'database')

            # Add authenticators for all identities if user is not nil
            user&.identities&.each do |identity|
              authenticators << Gitlab::Auth::OAuth::Provider.authentication(user, identity.provider)
            end
          else
            # If no user is provided, try LDAP.
            #   LDAP users are only authenticated via LDAP
101
            authenticators << Gitlab::Auth::Ldap::Authentication
102
          end
103 104 105

          authenticators.compact!

106
          # return found user that was authenticated first for given login credentials
107
          authenticated_user = authenticators.find do |auth|
108 109 110
            authenticated_user = auth.login(login, password)
            break authenticated_user if authenticated_user
          end
111 112 113 114

          user_auth_attempt!(user, success: !!authenticated_user) if increment_failed_attempts

          authenticated_user
115 116 117
        end
      end

118 119 120 121
      private

      def rate_limit!(rate_limiter, success:, login:)
        return if skip_rate_limit?(login: login)
Jacob Vosmaer's avatar
Jacob Vosmaer committed
122 123 124 125 126 127 128 129 130

        if success
          # Repeated login 'failures' are normal behavior for some Git clients so
          # it is important to reset the ban counter once the client has proven
          # they are not a 'bad guy'.
          rate_limiter.reset!
        else
          # Register a login failure so that Rack::Attack can block the next
          # request from this IP if needed.
131 132 133
          # This returns true when the failures are over the threshold and the IP
          # is banned.
          if rate_limiter.register_fail!
Rajendra Kadam's avatar
Rajendra Kadam committed
134
            Gitlab::AppLogger.info "IP #{rate_limiter.ip} failed to login " \
Jacob Vosmaer's avatar
Jacob Vosmaer committed
135 136 137 138 139
              "as #{login} but has been temporarily banned from Git auth"
          end
        end
      end

140
      def skip_rate_limit?(login:)
141
        CI_JOB_USER == login
142 143
      end

144 145 146 147
      def look_to_limit_user(actor)
        Gitlab::Auth::UniqueIpsLimiter.limit_user!(actor) if actor.is_a?(User)
      end

148
      def authenticate_using_internal_or_ldap_password?
149
        Gitlab::CurrentSettings.password_authentication_enabled_for_git? || Gitlab::Auth::Ldap::Config.enabled?
150 151
      end

152
      def service_request_check(login, password, project)
153 154
        matched_login = /(?<service>^[a-zA-Z]*-ci)-token$/.match(login)

155
        return unless project && matched_login.present?
156 157 158

        underscored_service = matched_login['service'].underscore

159
        if Integration.available_services_names.include?(underscored_service)
160
          # We treat underscored_service as a trusted input because it is included
161
          # in the Integration.available_services_names allowlist.
162
          service = project.public_send("#{underscored_service}_service") # rubocop:disable GitlabSecurity/PublicSend
163

164
          if service && service.activated? && service.valid_token?(password)
165
            Gitlab::Auth::Result.new(nil, project, :ci, build_authentication_abilities)
166 167 168 169 170 171
          end
        end
      end

      def user_with_password_for_git(login, password)
        user = find_with_user_password(login, password)
172 173
        return unless user

174
        raise Gitlab::Auth::MissingPersonalAccessTokenError if user.two_factor_enabled?
175

176
        Gitlab::Auth::Result.new(user, nil, :gitlab_or_ldap, full_authentication_abilities)
177 178
      end

179 180 181
      def oauth_access_token_check(login, password)
        if login == "oauth2" && password.present?
          token = Doorkeeper::AccessToken.by_token(password)
182

183
          if valid_oauth_token?(token)
184
            user = User.id_in(token.resource_owner_id).first
185
            return unless user && can_user_login_with_non_expired_password?(user)
186

187
            Gitlab::Auth::Result.new(user, nil, :oauth, full_authentication_abilities)
188
          end
189 190
        end
      end
191

192
      def personal_access_token_check(password, project)
Simon Vocella's avatar
Simon Vocella committed
193
        return unless password.present?
194

195
        token = PersonalAccessTokensFinder.new(state: 'active').find_by_token(password)
Simon Vocella's avatar
Simon Vocella committed
196

197 198 199 200
        return unless token

        return unless valid_scoped_token?(token, all_available_scopes)

Serena Fang's avatar
Serena Fang committed
201 202
        return if project && token.user.project_bot? && !project.bots.include?(token.user)

203
        if can_user_login_with_non_expired_password?(token.user) || token.user.project_bot?
204
          Gitlab::Auth::Result.new(token.user, nil, :personal_access_token, abilities_for_scopes(token.scopes))
205 206
        end
      end
Patricio Cano's avatar
Patricio Cano committed
207

208
      def valid_oauth_token?(token)
209
        token && token.accessible? && valid_scoped_token?(token, [:api])
210 211
      end

Z.J. van de Weg's avatar
Z.J. van de Weg committed
212
      def valid_scoped_token?(token, scopes)
213 214 215
        AccessTokenValidationService.new(token).include_any_scope?(scopes)
      end

216 217 218
      def abilities_for_scopes(scopes)
        abilities_by_scope = {
          api: full_authentication_abilities,
219
          read_api: read_only_authentication_abilities,
220
          read_registry: [:read_container_image],
221
          write_registry: [:create_container_image],
222 223
          read_repository: [:download_code],
          write_repository: [:download_code, :push_code]
224 225 226 227 228
        }

        scopes.flat_map do |scope|
          abilities_by_scope.fetch(scope.to_sym, [])
        end.uniq
229 230
      end

231
      def deploy_token_check(login, password, project)
232
        return unless password.present?
233

234
        token = DeployToken.active.find_by_token(password)
235

236 237
        return unless token && login
        return if login != token.username
238

239 240
        # Registry access (with jwt) does not have access to project
        return if project && !token.has_access_to?(project)
241 242
        # When repository is disabled, no resources are accessible via Deploy Token
        return if project&.repository_access_level == ::ProjectFeature::DISABLED
243

244
        scopes = abilities_for_scopes(token.scopes)
245

246
        if valid_scoped_token?(token, all_available_scopes)
247
          Gitlab::Auth::Result.new(token, project, :deploy_token, scopes)
248 249 250
        end
      end

251
      def lfs_token_check(login, encoded_token, project)
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
        deploy_key_matches = login.match(/\Alfs\+deploy-key-(\d+)\z/)

        actor =
          if deploy_key_matches
            DeployKey.find(deploy_key_matches[1])
          else
            User.by_login(login)
          end

        return unless actor

        token_handler = Gitlab::LfsToken.new(actor)

        authentication_abilities =
          if token_handler.user?
267
            read_write_project_authentication_abilities
268 269
          elsif token_handler.deploy_key_pushable?(project)
            read_write_authentication_abilities
270
          else
271
            read_only_authentication_abilities
272 273
          end

274
        if token_handler.token_valid?(encoded_token)
275 276
          Gitlab::Auth::Result.new(actor, nil, token_handler.type, authentication_abilities)
        end
277 278
      end

279
      def build_access_token_check(login, password)
280
        return unless login == CI_JOB_USER
281 282
        return unless password

283
        build = find_build_by_token(password)
284
        return unless build
Kamil Trzcinski's avatar
Kamil Trzcinski committed
285
        return unless build.project.builds_enabled?
286 287

        if build.user
288
          return unless can_user_login_with_non_expired_password?(build.user) || (build.user.project_bot? && build.project.bots&.include?(build.user))
289

290
          # If user is assigned to build, use restricted credentials of user
291
          Gitlab::Auth::Result.new(build.user, build.project, :build, build_authentication_abilities)
292 293
        else
          # Otherwise use generic CI credentials (backward compatibility)
294
          Gitlab::Auth::Result.new(nil, build.project, :ci, build_authentication_abilities)
295
        end
296
      end
297

298 299
      public

300
      def build_authentication_abilities
301 302
        [
          :read_project,
303 304
          :build_download_code,
          :build_read_container_image,
305 306
          :build_create_container_image,
          :build_destroy_container_image
307 308 309
        ]
      end

310
      def read_only_project_authentication_abilities
311 312
        [
          :read_project,
313 314 315 316 317 318 319 320 321 322 323 324
          :download_code
        ]
      end

      def read_write_project_authentication_abilities
        read_only_project_authentication_abilities + [
          :push_code
        ]
      end

      def read_only_authentication_abilities
        read_only_project_authentication_abilities + [
325 326 327 328
          :read_container_image
        ]
      end

329
      def read_write_authentication_abilities
330
        read_only_authentication_abilities + [
331
          :push_code,
332 333 334 335 336 337
          :create_container_image
        ]
      end

      def full_authentication_abilities
        read_write_authentication_abilities + [
338
          :admin_container_image
339 340
        ]
      end
341

342 343 344
      def available_scopes_for(current_user)
        scopes = non_admin_available_scopes
        scopes += ADMIN_SCOPES if current_user.admin?
Douwe Maan's avatar
Douwe Maan committed
345
        scopes
346 347
      end

348 349 350 351
      def all_available_scopes
        non_admin_available_scopes + ADMIN_SCOPES
      end

352 353
      # Other available scopes
      def optional_scopes
354
        all_available_scopes + OPENID_SCOPES + PROFILE_SCOPES - DEFAULT_SCOPES
355 356 357 358 359 360 361
      end

      def registry_scopes
        return [] unless Gitlab.config.registry.enabled

        REGISTRY_SCOPES
      end
362

363 364 365 366
      def resource_bot_scopes
        Gitlab::Auth::API_SCOPES + Gitlab::Auth::REPOSITORY_SCOPES + Gitlab::Auth.registry_scopes - [:read_user]
      end

367 368
      private

369 370 371 372
      def non_admin_available_scopes
        API_SCOPES + REPOSITORY_SCOPES + registry_scopes
      end

373
      def find_build_by_token(token)
Thong Kuah's avatar
Thong Kuah committed
374 375 376
        ::Gitlab::Database::LoadBalancing::Session.current.use_primary do
          ::Ci::AuthJobFinder.new(token: token).execute
        end
377
      end
378 379 380 381 382 383 384

      def user_auth_attempt!(user, success:)
        return unless user && Gitlab::Database.read_write?
        return user.unlock_access! if success

        user.increment_failed_attempts!
      end
385 386

      def can_user_login_with_non_expired_password?(user)
387
        user.can?(:log_in) && !user.password_expired_if_applicable?
388
      end
389
    end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
390 391
  end
end