Skip to content

Commit 12ca726

Browse files
soerfaceshaleh
authored andcommitted
Refresh Token Reuse Protection (django-oauth#1452)
* Implement REFRESH_TOKEN_REUSE_PROTECTION (django-oauth#1404) According to https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-29#name-recommendations, the authorization server needs a way to determine which refresh tokens belong to the same session, so it is able to figure out which tokens to revoke. Therefore, this commit introduces a "token_family" field to the RefreshToken table. Whenever a revoked refresh token is reused, the auth server uses the token family to revoke all related tokens.
1 parent f00c393 commit 12ca726

File tree

9 files changed

+184
-12
lines changed

9 files changed

+184
-12
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ Shaheed Haque
106106
Shaun Stanworth
107107
Silvano Cerza
108108
Sora Yanai
109+
Sören Wegener
109110
Spencer Carroll
110111
Stéphane Raimbault
111112
Tom Evans

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1616

1717
## [unreleased]
1818
### Added
19+
* #1404 Add a new setting `REFRESH_TOKEN_REUSE_PROTECTION`
1920
### Changed
2021
* Transactions wrapping writes of the Tokens now rely on Django's database routers to determine the correct
2122
database to use instead of assuming that 'default' is the correct one.

docs/settings.rst

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,18 @@ The import string of the class (model) representing your refresh tokens. Overwri
185185
this value if you wrote your own implementation (subclass of
186186
``oauth2_provider.models.RefreshToken``).
187187

188+
REFRESH_TOKEN_REUSE_PROTECTION
189+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
190+
When this is set to ``True`` (default ``False``), and ``ROTATE_REFRESH_TOKEN`` is used, the server will check
191+
if a previously, already revoked refresh token is used a second time. If it detects a reuse, it will automatically
192+
revoke all related refresh tokens.
193+
A reused refresh token indicates a breach. Since the server can't determine which request came from the legitimate
194+
user and which from an attacker, it will end the session for both. The user is required to perform a new login.
195+
196+
Can be used in combination with ``REFRESH_TOKEN_GRACE_PERIOD_SECONDS``
197+
198+
More details at https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-29#name-recommendations
199+
188200
ROTATE_REFRESH_TOKEN
189201
~~~~~~~~~~~~~~~~~~~~
190202
When is set to ``True`` (default) a new refresh token is issued to the client when the client refreshes an access token.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Generated by Django 5.2 on 2024-08-09 16:40
2+
3+
from django.db import migrations, models
4+
from oauth2_provider.settings import oauth2_settings
5+
6+
class Migration(migrations.Migration):
7+
8+
dependencies = [
9+
('oauth2_provider', '0010_application_allowed_origins'),
10+
migrations.swappable_dependency(oauth2_settings.REFRESH_TOKEN_MODEL)
11+
]
12+
13+
operations = [
14+
migrations.AddField(
15+
model_name='refreshtoken',
16+
name='token_family',
17+
field=models.UUIDField(blank=True, editable=False, null=True),
18+
),
19+
]

oauth2_provider/models.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,7 @@ class AbstractRefreshToken(models.Model):
491491
null=True,
492492
related_name="refresh_token",
493493
)
494+
token_family = models.UUIDField(null=True, blank=True, editable=False)
494495

495496
created = models.DateTimeField(auto_now_add=True)
496497
updated = models.DateTimeField(auto_now=True)

oauth2_provider/oauth2_validators.py

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
from django.contrib.auth.hashers import check_password, identify_hasher
1616
from django.core.exceptions import ObjectDoesNotExist
1717
from django.db import router, transaction
18-
from django.db.models import Q
1918
from django.http import HttpRequest
2019
from django.utils import dateformat, timezone
2120
from django.utils.crypto import constant_time_compare
@@ -656,7 +655,9 @@ def _save_bearer_token(self, token, request, *args, **kwargs):
656655
source_refresh_token=refresh_token_instance,
657656
)
658657

659-
self._create_refresh_token(request, refresh_token_code, access_token)
658+
self._create_refresh_token(
659+
request, refresh_token_code, access_token, refresh_token_instance
660+
)
660661
else:
661662
# make sure that the token data we're returning matches
662663
# the existing token
@@ -700,9 +701,17 @@ def _create_authorization_code(self, request, code, expires=None):
700701
claims=json.dumps(request.claims or {}),
701702
)
702703

703-
def _create_refresh_token(self, request, refresh_token_code, access_token):
704+
def _create_refresh_token(self, request, refresh_token_code, access_token, previous_refresh_token):
705+
if previous_refresh_token:
706+
token_family = previous_refresh_token.token_family
707+
else:
708+
token_family = uuid.uuid4()
704709
return RefreshToken.objects.create(
705-
user=request.user, token=refresh_token_code, application=request.client, access_token=access_token
710+
user=request.user,
711+
token=refresh_token_code,
712+
application=request.client,
713+
access_token=access_token,
714+
token_family=token_family,
706715
)
707716

708717
def revoke_token(self, token, token_type_hint, request, *args, **kwargs):
@@ -764,22 +773,25 @@ def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs
764773
Also attach User instance to the request object
765774
"""
766775

767-
null_or_recent = Q(revoked__isnull=True) | Q(
768-
revoked__gt=timezone.now() - timedelta(seconds=oauth2_settings.REFRESH_TOKEN_GRACE_PERIOD_SECONDS)
769-
)
770-
rt = (
771-
RefreshToken.objects.filter(null_or_recent, token=refresh_token)
772-
.select_related("access_token")
773-
.first()
774-
)
776+
rt = RefreshToken.objects.filter(token=refresh_token).select_related("access_token").first()
775777

776778
if not rt:
777779
return False
778780

781+
if rt.revoked is not None and rt.revoked <= timezone.now() - timedelta(
782+
seconds=oauth2_settings.REFRESH_TOKEN_GRACE_PERIOD_SECONDS
783+
):
784+
if oauth2_settings.REFRESH_TOKEN_REUSE_PROTECTION and rt.token_family:
785+
rt_token_family = RefreshToken.objects.filter(token_family=rt.token_family)
786+
for related_rt in rt_token_family.all():
787+
related_rt.revoke()
788+
return False
789+
779790
request.user = rt.user
780791
request.refresh_token = rt.token
781792
# Temporary store RefreshToken instance to be reused by get_original_scopes and save_bearer_token.
782793
request.refresh_token_instance = rt
794+
783795
return rt.application == client
784796

785797
def _save_id_token(self, jti, request, expires, *args, **kwargs):

oauth2_provider/settings.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
"ID_TOKEN_EXPIRE_SECONDS": 36000,
5555
"REFRESH_TOKEN_EXPIRE_SECONDS": None,
5656
"REFRESH_TOKEN_GRACE_PERIOD_SECONDS": 0,
57+
"REFRESH_TOKEN_REUSE_PROTECTION": False,
5758
"ROTATE_REFRESH_TOKEN": True,
5859
"ERROR_RESPONSE_WITH_SCOPES": False,
5960
"APPLICATION_MODEL": APPLICATION_MODEL,
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Generated by Django 5.2 on 2024-08-09 16:40
2+
3+
from django.db import migrations, models
4+
from oauth2_provider.settings import oauth2_settings
5+
6+
7+
class Migration(migrations.Migration):
8+
9+
dependencies = [
10+
('tests', '0005_basetestapplication_allowed_origins_and_more'),
11+
migrations.swappable_dependency(oauth2_settings.REFRESH_TOKEN_MODEL)
12+
]
13+
14+
operations = [
15+
migrations.AddField(
16+
model_name='samplerefreshtoken',
17+
name='token_family',
18+
field=models.UUIDField(blank=True, editable=False, null=True),
19+
),
20+
]

tests/test_authorization_code.py

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -986,6 +986,54 @@ def test_refresh_fail_repeating_requests(self):
986986
response = self.client.post(reverse("oauth2_provider:token"), data=token_request_data, **auth_headers)
987987
self.assertEqual(response.status_code, 400)
988988

989+
def test_refresh_repeating_requests_revokes_old_token(self):
990+
"""
991+
If a refresh token is reused, the server should invalidate *all* access tokens that have a relation
992+
to the re-used token. This forces a malicious actor to be logged out.
993+
The server can't determine whether the first or the second client was legitimate, so it needs to
994+
revoke both.
995+
See https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-29#name-recommendations
996+
"""
997+
self.oauth2_settings.REFRESH_TOKEN_REUSE_PROTECTION = True
998+
self.client.login(username="test_user", password="123456")
999+
authorization_code = self.get_auth()
1000+
1001+
token_request_data = {
1002+
"grant_type": "authorization_code",
1003+
"code": authorization_code,
1004+
"redirect_uri": "http://example.org",
1005+
}
1006+
auth_headers = get_basic_auth_header(self.application.client_id, CLEARTEXT_SECRET)
1007+
1008+
response = self.client.post(reverse("oauth2_provider:token"), data=token_request_data, **auth_headers)
1009+
content = json.loads(response.content.decode("utf-8"))
1010+
self.assertTrue("refresh_token" in content)
1011+
1012+
token_request_data = {
1013+
"grant_type": "refresh_token",
1014+
"refresh_token": content["refresh_token"],
1015+
"scope": content["scope"],
1016+
}
1017+
# First response works as usual
1018+
response = self.client.post(reverse("oauth2_provider:token"), data=token_request_data, **auth_headers)
1019+
self.assertEqual(response.status_code, 200)
1020+
new_tokens = json.loads(response.content.decode("utf-8"))
1021+
1022+
# Second request fails
1023+
response = self.client.post(reverse("oauth2_provider:token"), data=token_request_data, **auth_headers)
1024+
self.assertEqual(response.status_code, 400)
1025+
1026+
# Previously returned tokens are now invalid as well
1027+
new_token_request_data = {
1028+
"grant_type": "refresh_token",
1029+
"refresh_token": new_tokens["refresh_token"],
1030+
"scope": new_tokens["scope"],
1031+
}
1032+
response = self.client.post(
1033+
reverse("oauth2_provider:token"), data=new_token_request_data, **auth_headers
1034+
)
1035+
self.assertEqual(response.status_code, 400)
1036+
9891037
def test_refresh_repeating_requests(self):
9901038
"""
9911039
Trying to refresh an access token with the same refresh token more than
@@ -1025,6 +1073,63 @@ def test_refresh_repeating_requests(self):
10251073
response = self.client.post(reverse("oauth2_provider:token"), data=token_request_data, **auth_headers)
10261074
self.assertEqual(response.status_code, 400)
10271075

1076+
def test_refresh_repeating_requests_grace_period_with_reuse_protection(self):
1077+
"""
1078+
Trying to refresh an access token with the same refresh token more than
1079+
once succeeds. Should work within the grace period, but should revoke previous tokens
1080+
"""
1081+
self.oauth2_settings.REFRESH_TOKEN_GRACE_PERIOD_SECONDS = 120
1082+
self.oauth2_settings.REFRESH_TOKEN_REUSE_PROTECTION = True
1083+
self.client.login(username="test_user", password="123456")
1084+
authorization_code = self.get_auth()
1085+
1086+
token_request_data = {
1087+
"grant_type": "authorization_code",
1088+
"code": authorization_code,
1089+
"redirect_uri": "http://example.org",
1090+
}
1091+
auth_headers = get_basic_auth_header(self.application.client_id, CLEARTEXT_SECRET)
1092+
1093+
response = self.client.post(reverse("oauth2_provider:token"), data=token_request_data, **auth_headers)
1094+
content = json.loads(response.content.decode("utf-8"))
1095+
self.assertTrue("refresh_token" in content)
1096+
1097+
refresh_token_1 = content["refresh_token"]
1098+
token_request_data = {
1099+
"grant_type": "refresh_token",
1100+
"refresh_token": refresh_token_1,
1101+
"scope": content["scope"],
1102+
}
1103+
response = self.client.post(reverse("oauth2_provider:token"), data=token_request_data, **auth_headers)
1104+
self.assertEqual(response.status_code, 200)
1105+
refresh_token_2 = json.loads(response.content.decode("utf-8"))["refresh_token"]
1106+
1107+
response = self.client.post(reverse("oauth2_provider:token"), data=token_request_data, **auth_headers)
1108+
self.assertEqual(response.status_code, 200)
1109+
refresh_token_3 = json.loads(response.content.decode("utf-8"))["refresh_token"]
1110+
1111+
self.assertEqual(refresh_token_2, refresh_token_3)
1112+
1113+
# Let the first refresh token expire
1114+
rt = RefreshToken.objects.get(token=refresh_token_1)
1115+
rt.revoked = timezone.now() - datetime.timedelta(minutes=10)
1116+
rt.save()
1117+
1118+
# Using the expired token fails
1119+
response = self.client.post(reverse("oauth2_provider:token"), data=token_request_data, **auth_headers)
1120+
self.assertEqual(response.status_code, 400)
1121+
1122+
# Because we used the expired token, the recently issued token is also revoked
1123+
new_token_request_data = {
1124+
"grant_type": "refresh_token",
1125+
"refresh_token": refresh_token_2,
1126+
"scope": content["scope"],
1127+
}
1128+
response = self.client.post(
1129+
reverse("oauth2_provider:token"), data=new_token_request_data, **auth_headers
1130+
)
1131+
self.assertEqual(response.status_code, 400)
1132+
10281133
def test_refresh_repeating_requests_non_rotating_tokens(self):
10291134
"""
10301135
Try refreshing an access token with the same refresh token more than once when not rotating tokens.

0 commit comments

Comments
 (0)