connect.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. """Openconnect-Microsoft-login connection helpers."""
  2. import logging
  3. import time
  4. from dataclasses import dataclass
  5. from typing import Optional
  6. from urllib.parse import urlparse
  7. from otppy import OTP
  8. from selenium import webdriver
  9. from selenium.common.exceptions import ElementClickInterceptedException
  10. from selenium.common.exceptions import ElementNotInteractableException
  11. from selenium.common.exceptions import NoSuchElementException
  12. from selenium.common.exceptions import StaleElementReferenceException
  13. from selenium.common.exceptions import TimeoutException
  14. from selenium.webdriver.common.by import By
  15. from selenium.webdriver.firefox.options import Options as FirefoxOptions
  16. from selenium.webdriver.support import expected_conditions as EC
  17. from selenium.webdriver.support.ui import WebDriverWait
  18. USERNAME_INPUT_NAME = "loginfmt"
  19. PASSWORD_INPUT_NAME = "passwd"
  20. MFA_INPUT_NAME = "otc"
  21. CONTINUE_BUTTON_ID = "idSIButton9"
  22. MFA_CONTINUE_BUTTON_ID = "idSubmit_SAOTCC_Continue"
  23. MFA_ERROR_TEXT_ID = "idSpan_SAOTCC_Error_OTC"
  24. VPN_INSTALL_PAGE_EXCLUSIVE_ELEMENT_ID = "provisioning_action_label"
  25. MAX_RETRY_DOMAIN_CHECK = 16
  26. MFA_MAX_RETRY_COUNT = 3
  27. ELEMENT_CHECK_DELAY = 0.5
  28. DOMAIN_CHECK_DELAY = 0.5
  29. LOGGER = logging.getLogger("OCMA")
  30. LOGGER.setLevel(logging.INFO)
  31. @dataclass
  32. class VPNCookie:
  33. """VPN cookie data container."""
  34. domain: str
  35. cookie: str
  36. def login(
  37. username: str,
  38. password: str,
  39. mfa_secret: Optional[str] = None,
  40. vpn_site: str = "https://vpn.fhnw.ch",
  41. headless: bool = True,
  42. log_messages: bool = False,
  43. ) -> VPNCookie:
  44. """
  45. Log in to the vpn.
  46. Parameters
  47. ----------
  48. username : str
  49. Microsoft account username.
  50. password : str
  51. Microsoft account password.
  52. mfa_secret : Optional[str], optional
  53. Multifactor secret, by default None
  54. vpn_site : _type_, optional
  55. VPN site to log into, by default "https://vpn.fhnw.ch"
  56. headless : bool, optional
  57. If the browser should be run in headless mode, by default True
  58. log_messages : bool, optional
  59. If messages should be logged to the console, by default False
  60. Returns
  61. -------
  62. VPNCookie
  63. Cookie to log into the openconnect VPN.
  64. Raises
  65. ------
  66. ValueError
  67. If anything went sideways during the login.
  68. """
  69. if log_messages:
  70. formatter = logging.Formatter(
  71. "%(asctime)s: %(levelname)s - %(name)s - %(message)s"
  72. )
  73. fh_s = logging.StreamHandler()
  74. fh_s.setLevel(logging.INFO)
  75. fh_s.setFormatter(formatter)
  76. LOGGER.addHandler(fh_s)
  77. LOGGER.info("Starting")
  78. options = FirefoxOptions()
  79. if headless:
  80. LOGGER.info("Running in headless mode")
  81. options.add_argument("--headless")
  82. driver = webdriver.Firefox(options=options)
  83. driver.get(vpn_site)
  84. retries = MAX_RETRY_DOMAIN_CHECK
  85. while not _is_on_ms_login_page(driver) and retries > 0:
  86. retries -= 1
  87. time.sleep(DOMAIN_CHECK_DELAY)
  88. if retries < 0:
  89. raise ValueError(
  90. f"We never reached the MS login page! Currently on {driver.current_url}"
  91. )
  92. _fill_login(driver, username, password)
  93. _fill_mfa(driver, mfa_secret)
  94. _confirm_stay_signed_in(driver)
  95. _is_on_install_page(driver)
  96. return _get_webvpn_cookie(driver)
  97. def _fill_login(driver: webdriver.Firefox, username: str, password: str) -> None:
  98. LOGGER.info("Filling in login information")
  99. _check_on_ms_login_page(driver)
  100. if not _find_element(driver, By.NAME, USERNAME_INPUT_NAME):
  101. raise ValueError("Could not find login page!")
  102. if not _element_interactable(driver, By.NAME, USERNAME_INPUT_NAME):
  103. raise ValueError("Could not find username field!")
  104. driver.find_element(By.NAME, USERNAME_INPUT_NAME).send_keys(username)
  105. click_continue(driver)
  106. if not _element_interactable(driver, By.NAME, PASSWORD_INPUT_NAME):
  107. raise ValueError("Could not find password input!")
  108. driver.find_element(By.NAME, PASSWORD_INPUT_NAME).send_keys(password)
  109. click_continue(driver)
  110. retries = MAX_RETRY_DOMAIN_CHECK
  111. while on_login_form(driver) and retries > 0:
  112. LOGGER.info(
  113. "Login information may not have yet been confirmed. Checking again (Try %s of %s)",
  114. MAX_RETRY_DOMAIN_CHECK - retries + 1,
  115. MAX_RETRY_DOMAIN_CHECK,
  116. )
  117. time.sleep(ELEMENT_CHECK_DELAY)
  118. if on_login_form(driver):
  119. LOGGER.info("Login information has not yet been confirmed. Trying again")
  120. click_continue(driver) # Confirm password
  121. retries -= 1
  122. if retries < 0:
  123. raise ValueError("Failed to confirm login form!")
  124. LOGGER.info("Login information filled out")
  125. def on_login_form(driver: webdriver.Firefox) -> bool:
  126. """
  127. Check if we are on the login form.
  128. Parameters
  129. ----------
  130. driver : webdriver.Firefox
  131. The web driver to check on.
  132. Returns
  133. -------
  134. bool
  135. True if we are on the login form, else false.
  136. """
  137. return "saml2" in driver.current_url
  138. def _fill_mfa(driver: webdriver.Firefox, mfa_secret: Optional[str]) -> None:
  139. LOGGER.info("Checking if we can fill in MFA information")
  140. _check_on_ms_login_page(driver)
  141. # Check if we have the MFA page
  142. if driver.current_url.endswith("/login") and mfa_secret is None:
  143. raise ValueError("You need to supply your MFA secret to log in!")
  144. # Check if we have an MFA code to enter
  145. if mfa_secret is None:
  146. LOGGER.info("Filling in login information")
  147. return
  148. for i in range(MFA_MAX_RETRY_COUNT):
  149. LOGGER.info(
  150. "Filling in MFA information (Try %s of %s)", i + 1, MFA_MAX_RETRY_COUNT
  151. )
  152. if not _find_element(driver, By.NAME, MFA_INPUT_NAME):
  153. time.sleep(ELEMENT_CHECK_DELAY)
  154. continue
  155. mfa_code = get_mfa_code(mfa_secret)
  156. driver.find_element(By.NAME, MFA_INPUT_NAME).send_keys(mfa_code)
  157. click_continue(driver, MFA_CONTINUE_BUTTON_ID) # Confirm otp
  158. LOGGER.info("Confirmed MFA code")
  159. if not driver.current_url.endswith("/login"):
  160. # We have moved on
  161. LOGGER.info("We have moved away from the MFA page")
  162. break
  163. # Check for any errors
  164. if not _find_element(driver, By.ID, MFA_ERROR_TEXT_ID, 2):
  165. # Did not find an error
  166. LOGGER.info("MFA seems to have been accepted, no errors")
  167. break
  168. def _confirm_stay_signed_in(driver: webdriver.Firefox) -> bool:
  169. LOGGER.info("Cheking if we should confirm if we should stay signed in")
  170. if not _is_on_ms_login_page(driver):
  171. LOGGER.info("Already logged in, can't confirm 'stay signed in'")
  172. return False
  173. if not driver.current_url.endswith("/common/SAS/ProcessAuth"):
  174. LOGGER.info(
  175. "We have reached a dead end. We have completed the login, but not on the 'stay signed in' page"
  176. )
  177. return False
  178. click_continue(driver) # Confirm stay signed in
  179. LOGGER.info("Confirmed to 'stay signed in'")
  180. return True
  181. def _find_element(driver: webdriver.Firefox, by: str, item: str, wait: int = 8) -> bool:
  182. try:
  183. w = WebDriverWait(driver, wait)
  184. w.until(EC.presence_of_element_located((by, item)))
  185. return True
  186. except TimeoutException:
  187. return False
  188. def _element_interactable(
  189. driver: webdriver.Firefox, by: str, item: str, wait: int = 8
  190. ) -> bool:
  191. try:
  192. w = WebDriverWait(driver, wait)
  193. w.until(EC.element_to_be_clickable((by, item)))
  194. return True
  195. except ElementNotInteractableException:
  196. return False
  197. def _is_on_install_page(driver: webdriver.Firefox) -> None:
  198. if not _find_element(driver, By.ID, VPN_INSTALL_PAGE_EXCLUSIVE_ELEMENT_ID):
  199. raise ValueError("Could not find install page!")
  200. def _get_webvpn_cookie(driver: webdriver.Firefox) -> VPNCookie:
  201. webvpn_cookie = driver.get_cookie("webvpn")
  202. driver.close()
  203. if webvpn_cookie is None:
  204. raise ValueError(
  205. "Failed to find the webvpn cookie. Maybe the authentication has failed?"
  206. )
  207. webvpn_domain = webvpn_cookie["domain"]
  208. webvpn_value = webvpn_cookie["value"]
  209. return VPNCookie(domain=webvpn_domain, cookie=webvpn_value)
  210. def _check_on_ms_login_page(driver: webdriver.Firefox) -> None:
  211. if not _is_on_ms_login_page(driver):
  212. raise ValueError("We should still be on the MS login page but we aren't!")
  213. def _is_on_ms_login_page(driver: webdriver.Firefox) -> bool:
  214. return urlparse(driver.current_url).netloc == "login.microsoftonline.com"
  215. def click_continue(driver: webdriver.Firefox, btn_id: str = CONTINUE_BUTTON_ID) -> bool:
  216. """
  217. Click the continue button.
  218. Parameters
  219. ----------
  220. driver : webdriver.Firefox
  221. The driver for which to click the continue button.
  222. btn_id : str, optional
  223. The buttons ID to be clicked, by default CONTINUE_BUTTON_ID
  224. Returns
  225. -------
  226. bool
  227. True if still on login page, false if not.
  228. """
  229. for _ in range(16):
  230. try:
  231. driver.find_element(By.ID, btn_id).click()
  232. return True
  233. except (ElementClickInterceptedException, StaleElementReferenceException):
  234. pass
  235. except NoSuchElementException:
  236. pass
  237. time.sleep(ELEMENT_CHECK_DELAY)
  238. return False
  239. def get_mfa_code(secret: str) -> str:
  240. """
  241. Get the multifactor authentication code for the given secret.
  242. Parameters
  243. ----------
  244. secret : str
  245. MFA secret
  246. Returns
  247. -------
  248. str
  249. MFA code
  250. """
  251. otp = OTP.fromb32(secret)
  252. code: str = otp.TOTP()[0]
  253. return code