authentication.py 6.9 KB

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