authentication.py 6.9 KB

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