2023-03-23 17:05:35 +01:00
|
|
|
from typing import Any, Dict, Optional, Union
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
import aiohttp
|
2022-01-14 20:15:19 +01:00
|
|
|
import yarl
|
2023-03-23 17:05:35 +01:00
|
|
|
from bs4 import BeautifulSoup
|
2021-05-16 14:32:53 +02:00
|
|
|
|
2021-05-25 15:11:52 +02:00
|
|
|
from ...auth import Authenticator, TfaAuthenticator
|
2021-05-23 19:16:42 +02:00
|
|
|
from ...config import Config
|
2023-03-23 17:05:35 +01:00
|
|
|
from ...logging import log
|
|
|
|
from ...utils import soupify
|
|
|
|
from ..crawler import CrawlError, CrawlWarning
|
|
|
|
from .async_helpers import _iorepeat
|
|
|
|
from .ilias_web_crawler import IliasConfig, IliasWebCrawler, IliasWebCrawlerSection
|
2021-05-15 15:18:51 +02:00
|
|
|
|
2022-10-24 13:13:36 +02:00
|
|
|
_ILIAS_URL = "https://ilias.studium.kit.edu"
|
|
|
|
|
|
|
|
|
|
|
|
class KitShibbolethBackgroundLoginSuccessful():
|
|
|
|
pass
|
|
|
|
|
2021-05-15 15:18:51 +02:00
|
|
|
|
2023-03-23 17:05:35 +01:00
|
|
|
class KitIliasWebCrawlerSection(IliasWebCrawlerSection):
|
|
|
|
def conf(self) -> IliasConfig:
|
|
|
|
return IliasConfig(
|
|
|
|
base_url=_ILIAS_URL,
|
|
|
|
client_id="",
|
|
|
|
)
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
def tfa_auth(self, authenticators: Dict[str, Authenticator]) -> Optional[Authenticator]:
|
2021-05-25 14:12:19 +02:00
|
|
|
value: Optional[str] = self.s.get("tfa_auth")
|
|
|
|
if value is None:
|
2021-05-15 15:18:51 +02:00
|
|
|
return None
|
2021-05-25 14:12:19 +02:00
|
|
|
auth = authenticators.get(value)
|
2021-05-15 15:18:51 +02:00
|
|
|
if auth is None:
|
2021-05-25 14:12:19 +02:00
|
|
|
self.invalid_value("tfa_auth", value, "No such auth section exists")
|
2021-05-15 15:18:51 +02:00
|
|
|
return auth
|
|
|
|
|
|
|
|
|
2023-03-23 17:05:35 +01:00
|
|
|
class KitIliasWebCrawler(IliasWebCrawler):
|
2021-05-15 15:18:51 +02:00
|
|
|
def __init__(
|
2023-03-23 17:05:35 +01:00
|
|
|
self,
|
|
|
|
name: str,
|
|
|
|
section: KitIliasWebCrawlerSection,
|
|
|
|
config: Config,
|
|
|
|
authenticators: Dict[str, Authenticator]
|
2021-05-15 15:18:51 +02:00
|
|
|
):
|
2023-03-23 17:05:35 +01:00
|
|
|
super().__init__(name, section, config, authenticators)
|
2021-05-15 15:18:51 +02:00
|
|
|
self._shibboleth_login = KitShibbolethLogin(
|
2023-03-23 17:05:35 +01:00
|
|
|
self._auth,
|
2021-05-24 13:10:19 +02:00
|
|
|
section.tfa_auth(authenticators),
|
2021-05-15 15:18:51 +02:00
|
|
|
)
|
2021-05-24 13:10:19 +02:00
|
|
|
|
2021-05-21 12:02:51 +02:00
|
|
|
# We repeat this as the login method in shibboleth doesn't handle I/O errors.
|
|
|
|
# Shibboleth is quite reliable as well, the repeat is likely not critical here.
|
2022-05-24 23:28:09 +02:00
|
|
|
@ _iorepeat(3, "Login", failure_is_error=True)
|
2021-05-21 12:02:51 +02:00
|
|
|
async def _authenticate(self) -> None:
|
|
|
|
await self._shibboleth_login.login(self.session)
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
|
|
|
|
class KitShibbolethLogin:
|
|
|
|
"""
|
|
|
|
Login via KIT's shibboleth system.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, authenticator: Authenticator, tfa_authenticator: Optional[Authenticator]) -> None:
|
|
|
|
self._auth = authenticator
|
|
|
|
self._tfa_auth = tfa_authenticator
|
|
|
|
|
|
|
|
async def login(self, sess: aiohttp.ClientSession) -> None:
|
|
|
|
"""
|
|
|
|
Performs the ILIAS Shibboleth authentication dance and saves the login
|
|
|
|
cookies it receieves.
|
|
|
|
|
|
|
|
This function should only be called whenever it is detected that you're
|
|
|
|
not logged in. The cookies obtained should be good for a few minutes,
|
|
|
|
maybe even an hour or two.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Equivalent: Click on "Mit KIT-Account anmelden" button in
|
|
|
|
# https://ilias.studium.kit.edu/login.php
|
2022-10-24 13:13:36 +02:00
|
|
|
url = f"{_ILIAS_URL}/shib_login.php"
|
2021-05-15 15:18:51 +02:00
|
|
|
data = {
|
|
|
|
"sendLogin": "1",
|
|
|
|
"idp_selection": "https://idp.scc.kit.edu/idp/shibboleth",
|
2022-01-14 20:15:19 +01:00
|
|
|
"il_target": "",
|
|
|
|
"home_organization_selection": "Weiter",
|
2021-05-15 15:18:51 +02:00
|
|
|
}
|
2022-10-24 13:13:36 +02:00
|
|
|
soup: Union[BeautifulSoup, KitShibbolethBackgroundLoginSuccessful] = await _shib_post(sess, url, data)
|
|
|
|
|
|
|
|
if isinstance(soup, KitShibbolethBackgroundLoginSuccessful):
|
|
|
|
return
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
# Attempt to login using credentials, if necessary
|
|
|
|
while not self._login_successful(soup):
|
|
|
|
# Searching the form here so that this fails before asking for
|
|
|
|
# credentials rather than after asking.
|
|
|
|
form = soup.find("form", {"class": "full content", "method": "post"})
|
|
|
|
action = form["action"]
|
|
|
|
|
|
|
|
csrf_token = form.find("input", {"name": "csrf_token"})["value"]
|
|
|
|
|
|
|
|
# Equivalent: Enter credentials in
|
|
|
|
# https://idp.scc.kit.edu/idp/profile/SAML2/Redirect/SSO
|
|
|
|
url = "https://idp.scc.kit.edu" + action
|
|
|
|
username, password = await self._auth.credentials()
|
|
|
|
data = {
|
|
|
|
"_eventId_proceed": "",
|
|
|
|
"j_username": username,
|
|
|
|
"j_password": password,
|
|
|
|
"csrf_token": csrf_token
|
|
|
|
}
|
|
|
|
soup = await _post(sess, url, data)
|
|
|
|
|
2022-04-03 11:32:38 +02:00
|
|
|
if soup.find(id="attributeRelease"):
|
|
|
|
raise CrawlError(
|
|
|
|
"ILIAS Shibboleth entitlements changed! "
|
|
|
|
"Please log in once in your browser and review them"
|
|
|
|
)
|
|
|
|
|
2021-05-15 15:18:51 +02:00
|
|
|
if self._tfa_required(soup):
|
|
|
|
soup = await self._authenticate_tfa(sess, soup)
|
|
|
|
|
|
|
|
if not self._login_successful(soup):
|
2021-05-15 17:37:05 +02:00
|
|
|
self._auth.invalidate_credentials()
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
# Equivalent: Being redirected via JS automatically
|
|
|
|
# (or clicking "Continue" if you have JS disabled)
|
|
|
|
relay_state = soup.find("input", {"name": "RelayState"})
|
|
|
|
saml_response = soup.find("input", {"name": "SAMLResponse"})
|
2022-10-24 13:13:36 +02:00
|
|
|
url = f"{_ILIAS_URL}/Shibboleth.sso/SAML2/POST"
|
2021-05-15 15:18:51 +02:00
|
|
|
data = { # using the info obtained in the while loop above
|
|
|
|
"RelayState": relay_state["value"],
|
|
|
|
"SAMLResponse": saml_response["value"],
|
|
|
|
}
|
|
|
|
await sess.post(url, data=data)
|
|
|
|
|
|
|
|
async def _authenticate_tfa(
|
|
|
|
self,
|
|
|
|
session: aiohttp.ClientSession,
|
|
|
|
soup: BeautifulSoup
|
|
|
|
) -> BeautifulSoup:
|
|
|
|
if not self._tfa_auth:
|
2021-05-25 15:11:52 +02:00
|
|
|
self._tfa_auth = TfaAuthenticator("ilias-anon-tfa")
|
2021-05-15 15:18:51 +02:00
|
|
|
|
2021-05-15 18:24:03 +02:00
|
|
|
tfa_token = await self._tfa_auth.password()
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
# Searching the form here so that this fails before asking for
|
|
|
|
# credentials rather than after asking.
|
|
|
|
form = soup.find("form", {"method": "post"})
|
|
|
|
action = form["action"]
|
2021-05-25 19:23:06 +02:00
|
|
|
csrf_token = form.find("input", {"name": "csrf_token"})["value"]
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
# Equivalent: Enter token in
|
|
|
|
# https://idp.scc.kit.edu/idp/profile/SAML2/Redirect/SSO
|
|
|
|
url = "https://idp.scc.kit.edu" + action
|
|
|
|
data = {
|
|
|
|
"_eventId_proceed": "",
|
2021-05-25 19:23:06 +02:00
|
|
|
"j_tokenNumber": tfa_token,
|
|
|
|
"csrf_token": csrf_token
|
2021-05-15 15:18:51 +02:00
|
|
|
}
|
2021-05-25 19:19:51 +02:00
|
|
|
return await _post(session, url, data)
|
2021-05-15 15:18:51 +02:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _login_successful(soup: BeautifulSoup) -> bool:
|
|
|
|
relay_state = soup.find("input", {"name": "RelayState"})
|
|
|
|
saml_response = soup.find("input", {"name": "SAMLResponse"})
|
|
|
|
return relay_state is not None and saml_response is not None
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _tfa_required(soup: BeautifulSoup) -> bool:
|
|
|
|
return soup.find(id="j_tokenNumber") is not None
|
|
|
|
|
|
|
|
|
|
|
|
async def _post(session: aiohttp.ClientSession, url: str, data: Any) -> BeautifulSoup:
|
|
|
|
async with session.post(url, data=data) as response:
|
|
|
|
return soupify(await response.read())
|
2022-01-14 20:15:19 +01:00
|
|
|
|
|
|
|
|
2022-10-24 13:13:36 +02:00
|
|
|
async def _shib_post(
|
|
|
|
session: aiohttp.ClientSession,
|
|
|
|
url: str,
|
|
|
|
data: Any
|
|
|
|
) -> Union[BeautifulSoup, KitShibbolethBackgroundLoginSuccessful]:
|
2022-01-14 20:15:19 +01:00
|
|
|
"""
|
|
|
|
aiohttp unescapes '/' and ':' in URL query parameters which is not RFC compliant and rejected
|
|
|
|
by Shibboleth. Thanks a lot. So now we unroll the requests manually, parse location headers and
|
2022-01-15 15:06:02 +01:00
|
|
|
build encoded URL objects ourselves... Who thought mangling location header was a good idea??
|
2022-01-14 20:15:19 +01:00
|
|
|
"""
|
2022-10-24 13:13:36 +02:00
|
|
|
log.explain_topic("Shib login POST")
|
2022-01-14 20:15:19 +01:00
|
|
|
async with session.post(url, data=data, allow_redirects=False) as response:
|
|
|
|
location = response.headers.get("location")
|
2022-10-24 13:13:36 +02:00
|
|
|
log.explain(f"Got location {location!r}")
|
2022-01-14 20:15:19 +01:00
|
|
|
if not location:
|
2022-04-27 13:55:24 +02:00
|
|
|
raise CrawlWarning(f"Login failed (1), no location header present at {url}")
|
2022-01-14 20:15:19 +01:00
|
|
|
correct_url = yarl.URL(location, encoded=True)
|
2022-10-24 13:13:36 +02:00
|
|
|
log.explain(f"Corrected location to {correct_url!r}")
|
|
|
|
|
|
|
|
if str(correct_url).startswith(_ILIAS_URL):
|
|
|
|
log.explain("ILIAS recognized our shib token and logged us in in the background, returning")
|
|
|
|
return KitShibbolethBackgroundLoginSuccessful()
|
2022-01-14 20:15:19 +01:00
|
|
|
|
|
|
|
async with session.get(correct_url, allow_redirects=False) as response:
|
|
|
|
location = response.headers.get("location")
|
2022-10-24 13:13:36 +02:00
|
|
|
log.explain(f"Redirected to {location!r} with status {response.status}")
|
2022-04-27 13:55:24 +02:00
|
|
|
# If shib still still has a valid session, it will directly respond to the request
|
|
|
|
if location is None:
|
2022-10-24 13:13:36 +02:00
|
|
|
log.explain("Shib recognized us, returning its response directly")
|
2022-04-27 13:55:24 +02:00
|
|
|
return soupify(await response.read())
|
2022-01-14 20:15:19 +01:00
|
|
|
|
2022-04-27 13:55:24 +02:00
|
|
|
as_yarl = yarl.URL(response.url)
|
|
|
|
# Probably not needed anymore, but might catch a few weird situations with a nicer message
|
2022-01-14 20:15:19 +01:00
|
|
|
if not location or not as_yarl.host:
|
2022-04-27 13:55:24 +02:00
|
|
|
raise CrawlWarning(f"Login failed (2), no location header present at {correct_url}")
|
2022-01-14 20:15:19 +01:00
|
|
|
|
|
|
|
correct_url = yarl.URL.build(
|
|
|
|
scheme=as_yarl.scheme,
|
|
|
|
host=as_yarl.host,
|
|
|
|
path=location,
|
|
|
|
encoded=True
|
|
|
|
)
|
2022-10-24 13:13:36 +02:00
|
|
|
log.explain(f"Corrected location to {correct_url!r}")
|
2022-01-14 20:15:19 +01:00
|
|
|
|
|
|
|
async with session.get(correct_url, allow_redirects=False) as response:
|
|
|
|
return soupify(await response.read())
|