# Authentication Bypass

All sensitive actions on your website should require the user to be *authenticated* (i.e. to have identified who they are) and to be *authorized* (i.e. to have sufficient permissions to perform that action). If web routes fail to check the user identity, attackers will be able to access sensitive resources.

## Authentication Bypass in Python

Protected routes in your Python application should check the user is logged in, even if the path to access those resources is presumed unguessable. Attackers will poll common paths and scrape log files in an attempt to find unsecured routes, so the onus is on you to validate the user’s authentication status at the point of access.

A common way to do this in Python is to use function decorators, which can evaluate access permissions before a function is invoked. Here’s how to use the `@login_required` decorator in the Django web-framework:

“`python
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, renderdef do_login(request):
“””Check a user’s credentials and log them in if correct.”””
username = request.POST[‘username’]
password = request.POST[‘password’]

user = authenticate(request, username=username, password=password)

if user is not None:
login(request, user)
return redirect(‘/timeline’)
else:
messages.add_message(request, messages.ERROR, ‘Invalid credentials.’)
return redirect(‘/login’)

@login_required(login_url=’/login’)
def show_timeline(request):
“””Only show the user’s timeline if they are logged in, otherwise redirect
them to the login page.”””
return render(request, ‘views/timeline.html’)
“`

## Authentication in APIs

When you write a web-application designed for programmatic access rather than human users, authentication is typically done using an access token rather than cookies. A common design pattern is to expect the API key to be passed in each request in the `Authorization` header. This keeps you application stateless and makes it easier to scale.

Here’s one way to extract and check the API key using HTTP Basic authentication in the Flask web-server;

“`python
from flask import Flask
from flask_httpauth import HTTPBasicAuthapp = Flask(__name__)
auth = HTTPBasicAuth()

@app.route(‘/users’)
@auth.login_required
def users():
“””Enumerate all users if a valid API key is supplied.”””
return User.objects.all()

@app.route(‘/users/<user_id>’)
@auth.login_required
def user(user_id):
“””Return a description of a user if a valid API key is supplied.”””
return User.objects.get(id=user_id)

@auth.verify_password
def verify_api_key(api_key, _):
“””Verify the API key we expect to be passed as the ‘username’ part
of the ‘username:password’ pair in the Basic Authentication header.
We disregard the password part.”””
return ApiKeys.objects.get(value=api_key)
“`

## Temporary Access Tokens

When you issue temporary access tokens to users that allow them to bypass authentication – for example, in the case of password reset emails – ensure those tokens are strong random numbers, and time them out after a short period. Also, ensure these tokens can only be used once. If an attacker compromises a user’s email account, they will often scan their inbox for password reset links in an attempt to take ownership of further accounts on vulnerable platforms.

## Further Considerations

Authentication bypass vulnerabilities tend to occur when mistakes are made during the design phase. To avoid this, make sure you:

* Design your access control upfront and document it.
* Write unit tests to validate that unauthenticated users cannot access sensitive resources.
* Think like an attacker: focus on the biggest risks your organization faces and prioritize securing those.
* Record user activity in logs, so you have audit trails of who did what and when.

## CWEs

* [CWE-288](https://cwe.mitre.org/data/definitions/288.html)

About ShiftLeft

ShiftLeft empowers developers and AppSec teams to dramatically reduce risk by quickly finding and fixing the vulnerabilities most likely to reach their applications and ignoring reported vulnerabilities that pose little risk. Industry-leading accuracy allows developers to focus on security fixes that matter and improve code velocity while enabling AppSec engineers to shift security left.

A unified code security platform, ShiftLeft CORE scans for attack context across custom code, APIs, OSS, containers, internal microservices, and first-party business logic by combining results of the company’s and Intelligent Software Composition Analysis (SCA). Using its unique graph database that combines code attributes and analyzes actual attack paths based on real application architecture, ShiftLeft then provides detailed guidance on risk remediation within existing development workflows and tooling. Teams that use ShiftLeft ship more secure code, faster. Backed by SYN Ventures, Bain Capital Ventures, Blackstone, Mayfield, Thomvest Ventures, and SineWave Ventures, ShiftLeft is based in Santa Clara, California. For information, visit: www.shiftleft.io.

Share

See for yourself – run a scan on your code right now