authentication.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import base64
  2. from datetime import datetime, timezone
  3. from ipaddress import ip_address
  4. from django.contrib.auth.hashers import PBKDF2PasswordHasher
  5. from django.utils import timezone
  6. from rest_framework import exceptions, HTTP_HEADER_ENCODING
  7. from rest_framework.authentication import (
  8. BaseAuthentication,
  9. get_authorization_header,
  10. TokenAuthentication as RestFrameworkTokenAuthentication,
  11. BasicAuthentication)
  12. from desecapi.models import Domain, Token
  13. from desecapi.serializers import AuthenticatedBasicUserActionSerializer, EmailPasswordSerializer
  14. class DynAuthenticationMixin:
  15. def authenticate_credentials(self, username, key):
  16. user, token = TokenAuthentication().authenticate_credentials(key)
  17. # Make sure username is not misleading
  18. try:
  19. if username in ['', user.email] or Domain.objects.filter_qname(username.lower(), owner=user).exists():
  20. return user, token
  21. except ValueError:
  22. pass
  23. raise exceptions.AuthenticationFailed
  24. class TokenAuthentication(RestFrameworkTokenAuthentication):
  25. model = Token
  26. # Note: This method's runtime depends on in what way a credential is invalid (expired, wrong client IP).
  27. # It thus exposes the failure reason when under timing attack.
  28. def authenticate(self, request):
  29. try:
  30. user, token = super().authenticate(request) # may raise exceptions.AuthenticationFailed if token is invalid
  31. except TypeError: # no token given
  32. return None # unauthenticated
  33. # REMOTE_ADDR is populated by the environment of the wsgi-request [1], which in turn is set up by nginx as per
  34. # uwsgi_params [2]. The value of $remote_addr finally is given by the network connection [3].
  35. # [1]: https://github.com/django/django/blob/stable/3.1.x/django/core/handlers/wsgi.py#L77
  36. # [2]: https://github.com/desec-io/desec-stack/blob/62820ad/www/conf/sites-available/90-desec.api.location.var#L11
  37. # [3]: https://nginx.org/en/docs/http/ngx_http_core_module.html#var_remote_addr
  38. # While the request.META dictionary contains a mixture of values from various sources, HTTP headers have keys
  39. # with the HTTP_ prefix. Client addresses can therefore not be spoofed through headers.
  40. # In case the stack is run behind an application proxy, the address will be the proxy's address. Extracting the
  41. # real client address is currently not supported. For further information on this case, see
  42. # https://www.django-rest-framework.org/api-guide/throttling/#how-clients-are-identified
  43. client_ip = ip_address(request.META.get('REMOTE_ADDR'))
  44. # This can likely be done within Postgres with django-postgres-extensions (client_ip <<= ANY allowed_subnets).
  45. # However, the django-postgres-extensions package is unmaintained, and the GitHub repo has been archived.
  46. if not any(client_ip in subnet for subnet in token.allowed_subnets):
  47. raise exceptions.AuthenticationFailed('Invalid token.')
  48. return user, token
  49. def authenticate_credentials(self, key):
  50. key = Token.make_hash(key)
  51. try:
  52. user, token = super().authenticate_credentials(key)
  53. except TypeError: # no token given
  54. return None # unauthenticated
  55. if not token.is_valid:
  56. raise exceptions.AuthenticationFailed('Invalid token.')
  57. token.last_used = timezone.now()
  58. token.save()
  59. return user, token
  60. class BasicTokenAuthentication(BaseAuthentication, DynAuthenticationMixin):
  61. """
  62. HTTP Basic authentication that uses username and token.
  63. Clients should authenticate by passing the username and the token as a
  64. password in the "Authorization" HTTP header, according to the HTTP
  65. Basic Authentication Scheme
  66. Authorization: Basic dXNlcm5hbWU6dG9rZW4=
  67. For username "username" and password "token".
  68. """
  69. # A custom token model may be used, but must have the following properties.
  70. #
  71. # * key -- The string identifying the token
  72. # * user -- The user to which the token belongs
  73. model = Token
  74. def authenticate(self, request):
  75. auth = get_authorization_header(request).split()
  76. if not auth or auth[0].lower() != b'basic':
  77. return None
  78. if len(auth) == 1:
  79. msg = 'Invalid basic auth token header. No credentials provided.'
  80. raise exceptions.AuthenticationFailed(msg)
  81. elif len(auth) > 2:
  82. msg = 'Invalid basic auth token header. Basic authentication string should not contain spaces.'
  83. raise exceptions.AuthenticationFailed(msg)
  84. try:
  85. username, key = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).split(':')
  86. return self.authenticate_credentials(username, key)
  87. except Exception:
  88. raise exceptions.AuthenticationFailed("badauth")
  89. def authenticate_header(self, request):
  90. return 'Basic'
  91. class URLParamAuthentication(BaseAuthentication, DynAuthenticationMixin):
  92. """
  93. Authentication against username/password as provided in URL parameters.
  94. """
  95. model = Token
  96. def authenticate(self, request):
  97. """
  98. Returns `(User, Token)` if a correct username and token have been supplied
  99. using URL parameters. Otherwise raises `AuthenticationFailed`.
  100. """
  101. if 'username' not in request.query_params:
  102. msg = 'No username URL parameter provided.'
  103. raise exceptions.AuthenticationFailed(msg)
  104. if 'password' not in request.query_params:
  105. msg = 'No password URL parameter provided.'
  106. raise exceptions.AuthenticationFailed(msg)
  107. try:
  108. return self.authenticate_credentials(request.query_params['username'], request.query_params['password'])
  109. except Exception:
  110. raise exceptions.AuthenticationFailed("badauth")
  111. class EmailPasswordPayloadAuthentication(BaseAuthentication):
  112. authenticate_credentials = BasicAuthentication.authenticate_credentials
  113. def authenticate(self, request):
  114. serializer = EmailPasswordSerializer(data=request.data)
  115. serializer.is_valid(raise_exception=True)
  116. return self.authenticate_credentials(serializer.data['email'], serializer.data['password'], request)
  117. class AuthenticatedBasicUserActionAuthentication(BaseAuthentication):
  118. """
  119. Authenticates a request based on whether the serializer determines the validity of the given verification code
  120. based on the view's 'code' kwarg and the view serializer's code validity period.
  121. """
  122. def authenticate(self, request):
  123. view = request.parser_context['view']
  124. return self.authenticate_credentials(view.get_serializer_context())
  125. def authenticate_credentials(self, context):
  126. serializer = AuthenticatedBasicUserActionSerializer(data={}, context=context)
  127. serializer.is_valid(raise_exception=True)
  128. user = serializer.validated_data['user']
  129. email_verified = datetime.fromtimestamp(serializer.timestamp, timezone.utc)
  130. user.email_verified = max(user.email_verified or email_verified, email_verified)
  131. user.save()
  132. # When user.is_active is None, activation is pending. We need to admit them to finish activation, so only
  133. # reject strictly False. There are permissions to make sure that such accounts can't do anything else.
  134. if user.is_active == False:
  135. raise exceptions.AuthenticationFailed('User inactive.')
  136. return user, None
  137. class TokenHasher(PBKDF2PasswordHasher):
  138. algorithm = 'pbkdf2_sha256_iter1'
  139. iterations = 1