| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from urllib.parse import urlparse |
| 4 |
|
| 5 |
from django.core.cache import cache |
| 6 |
from django.core.exceptions import ImproperlyConfigured |
| 7 |
from django.http import Http404, HttpRequest |
| 8 |
from django.urls import reverse |
| 9 |
from django.utils.http import urlencode |
| 10 |
|
| 11 |
from onelogin.saml2.auth import OneLogin_Saml2_Auth |
| 12 |
from onelogin.saml2.constants import OneLogin_Saml2_Constants |
| 13 |
from onelogin.saml2.idp_metadata_parser import OneLogin_Saml2_IdPMetadataParser |
| 14 |
|
| 15 |
from allauth.account.adapter import get_adapter as get_account_adapter |
| 16 |
from allauth.socialaccount.adapter import get_adapter |
| 17 |
from allauth.socialaccount.models import SocialApp |
| 18 |
from allauth.socialaccount.providers.saml.provider import SAMLProvider |
| 19 |
|
| 20 |
|
| 21 |
def get_app_or_404(request: HttpRequest, organization_slug): |
| 22 |
adapter = get_adapter() |
| 23 |
try: |
| 24 |
return adapter.get_app( |
| 25 |
request, provider=SAMLProvider.id, client_id=organization_slug |
| 26 |
) |
| 27 |
except SocialApp.DoesNotExist: |
| 28 |
raise Http404(f"no SocialApp found with client_id={organization_slug}") |
| 29 |
|
| 30 |
|
| 31 |
def prepare_django_request(request: HttpRequest) -> dict: |
| 32 |
result = { |
| 33 |
"https": "on" if request.is_secure() else "off", |
| 34 |
"http_host": request.META["HTTP_HOST"], |
| 35 |
"script_name": request.META.get("SCRIPT_NAME"), |
| 36 |
"path_info": request.META["PATH_INFO"], |
| 37 |
"get_data": request.GET.copy(), |
| 38 |
# 'lowercase_urlencoding': True, |
| 39 |
"post_data": request.POST.copy(), |
| 40 |
} |
| 41 |
return result |
| 42 |
|
| 43 |
|
| 44 |
def build_sp_config(request: HttpRequest, provider_config, org) -> dict: |
| 45 |
acs_url = request.build_absolute_uri(reverse("saml_acs", args=[org])) |
| 46 |
sls_url = request.build_absolute_uri(reverse("saml_sls", args=[org])) |
| 47 |
metadata_url = request.build_absolute_uri(reverse("saml_metadata", args=[org])) |
| 48 |
# SP entity ID generated with the following precedence: |
| 49 |
# 1. Explicitly configured SP via the SocialApp.settings |
| 50 |
# 2. Fallback to the SAML metadata urlpattern |
| 51 |
_sp_config = provider_config.get("sp", {}) |
| 52 |
sp_entity_id = _sp_config.get("entity_id") |
| 53 |
sp_config = { |
| 54 |
"entityId": sp_entity_id or metadata_url, |
| 55 |
"assertionConsumerService": { |
| 56 |
"url": acs_url, |
| 57 |
"binding": OneLogin_Saml2_Constants.BINDING_HTTP_POST, |
| 58 |
}, |
| 59 |
"singleLogoutService": { |
| 60 |
"url": sls_url, |
| 61 |
"binding": OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT, |
| 62 |
}, |
| 63 |
} |
| 64 |
avd = provider_config.get("advanced", {}) |
| 65 |
if avd.get("x509cert") is not None: |
| 66 |
sp_config["x509cert"] = avd["x509cert"] |
| 67 |
|
| 68 |
if avd.get("x509cert_new"): |
| 69 |
sp_config["x509certNew"] = avd["x509cert_new"] |
| 70 |
|
| 71 |
if avd.get("private_key") is not None: |
| 72 |
sp_config["privateKey"] = avd["private_key"] |
| 73 |
|
| 74 |
if avd.get("name_id_format") is not None: |
| 75 |
sp_config["NameIDFormat"] = avd["name_id_format"] |
| 76 |
|
| 77 |
return sp_config |
| 78 |
|
| 79 |
|
| 80 |
def fetch_metadata_url_config(idp_config): |
| 81 |
metadata_url = idp_config["metadata_url"] |
| 82 |
entity_id = idp_config["entity_id"] |
| 83 |
cache_key = f"saml.metadata.{metadata_url}.{entity_id}" |
| 84 |
saml_config = cache.get(cache_key) |
| 85 |
if saml_config is None: |
| 86 |
saml_config = OneLogin_Saml2_IdPMetadataParser.parse_remote( |
| 87 |
metadata_url, |
| 88 |
entity_id=entity_id, |
| 89 |
timeout=idp_config.get("metadata_request_timeout", 10), |
| 90 |
) |
| 91 |
cache.set( |
| 92 |
cache_key, |
| 93 |
saml_config, |
| 94 |
idp_config.get("metadata_cache_timeout", 60 * 60 * 4), |
| 95 |
) |
| 96 |
return saml_config |
| 97 |
|
| 98 |
|
| 99 |
def build_saml_config(request: HttpRequest, provider_config, org) -> dict: |
| 100 |
avd = provider_config.get("advanced", {}) |
| 101 |
security_config = { |
| 102 |
"authnRequestsSigned": avd.get("authn_request_signed", False), |
| 103 |
"digestAlgorithm": avd.get("digest_algorithm", OneLogin_Saml2_Constants.SHA256), |
| 104 |
"logoutRequestSigned": avd.get("logout_request_signed", False), |
| 105 |
"logoutResponseSigned": avd.get("logout_response_signed", False), |
| 106 |
"requestedAuthnContext": False, |
| 107 |
"signatureAlgorithm": avd.get( |
| 108 |
"signature_algorithm", OneLogin_Saml2_Constants.RSA_SHA256 |
| 109 |
), |
| 110 |
"signMetadata": avd.get("metadata_signed", False), |
| 111 |
"wantAssertionsEncrypted": avd.get("want_assertion_encrypted", False), |
| 112 |
"wantAssertionsSigned": avd.get("want_assertion_signed", False), |
| 113 |
"wantMessagesSigned": avd.get("want_message_signed", False), |
| 114 |
"nameIdEncrypted": avd.get("name_id_encrypted", False), |
| 115 |
"wantNameIdEncrypted": avd.get("want_name_id_encrypted", False), |
| 116 |
"allowSingleLabelDomains": avd.get("allow_single_label_domains", False), |
| 117 |
"rejectDeprecatedAlgorithm": avd.get("reject_deprecated_algorithm", True), |
| 118 |
"wantNameId": avd.get("want_name_id", False), |
| 119 |
"wantAttributeStatement": avd.get("want_attribute_statement", True), |
| 120 |
"allowRepeatAttributeName": avd.get("allow_repeat_attribute_name", True), |
| 121 |
"metadataValidUntil": avd.get("metadata_valid_until", None), |
| 122 |
"metadataCacheDuration": avd.get("metadata_cache_duration", None), |
| 123 |
} |
| 124 |
saml_config = { |
| 125 |
"strict": avd.get("strict", True), |
| 126 |
"security": security_config, |
| 127 |
} |
| 128 |
|
| 129 |
contact_person = provider_config.get("contact_person") |
| 130 |
if contact_person: |
| 131 |
saml_config["contactPerson"] = contact_person |
| 132 |
|
| 133 |
organization = provider_config.get("organization") |
| 134 |
if organization: |
| 135 |
saml_config["organization"] = organization |
| 136 |
|
| 137 |
idp = provider_config.get("idp") |
| 138 |
if idp is None: |
| 139 |
raise ImproperlyConfigured("`idp` missing") |
| 140 |
metadata_url = idp.get("metadata_url") |
| 141 |
if metadata_url: |
| 142 |
meta_config = fetch_metadata_url_config(idp) |
| 143 |
saml_config["idp"] = meta_config["idp"] |
| 144 |
else: |
| 145 |
saml_config["idp"] = { |
| 146 |
"entityId": idp["entity_id"], |
| 147 |
"x509cert": idp["x509cert"], |
| 148 |
"singleSignOnService": {"url": idp["sso_url"]}, |
| 149 |
} |
| 150 |
slo_url = idp.get("slo_url") |
| 151 |
if slo_url: |
| 152 |
saml_config["idp"]["singleLogoutService"] = {"url": slo_url} |
| 153 |
|
| 154 |
saml_config["sp"] = build_sp_config(request, provider_config, org) |
| 155 |
return saml_config |
| 156 |
|
| 157 |
|
| 158 |
def encode_relay_state(state) -> str: |
| 159 |
params = {"state": state} |
| 160 |
return urlencode(params) |
| 161 |
|
| 162 |
|
| 163 |
def decode_relay_state(relay_state): |
| 164 |
"""According to the spec, RelayState need not be a URL, yet, |
| 165 |
``onelogin.saml2` exposes it as ``return_to -- The target URL the user |
| 166 |
should be redirected to after login``. Also, for an IdP initiated login |
| 167 |
sometimes a URL is used. |
| 168 |
""" |
| 169 |
next_url = None |
| 170 |
if relay_state: |
| 171 |
parts = urlparse(relay_state) |
| 172 |
if parts.scheme or parts.netloc or (parts.path and parts.path.startswith("/")): |
| 173 |
if get_account_adapter().is_safe_url(relay_state): |
| 174 |
next_url = relay_state |
| 175 |
return next_url |
| 176 |
|
| 177 |
|
| 178 |
def build_auth(request: HttpRequest, provider): |
| 179 |
req = prepare_django_request(request) |
| 180 |
config = build_saml_config(request, provider.app.settings, provider.app.client_id) |
| 181 |
auth = OneLogin_Saml2_Auth(req, config) |
| 182 |
return auth |