connect.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import logging
  2. import time
  3. from dataclasses import dataclass
  4. from typing import Optional
  5. from urllib.parse import urlparse
  6. from otppy import OTP
  7. from selenium import webdriver
  8. from selenium.common.exceptions import ElementClickInterceptedException
  9. from selenium.common.exceptions import NoSuchElementException
  10. from selenium.common.exceptions import StaleElementReferenceException
  11. from selenium.common.exceptions import TimeoutException
  12. from selenium.webdriver.common.by import By
  13. from selenium.webdriver.firefox.options import Options as FirefoxOptions
  14. from selenium.webdriver.support import expected_conditions as EC
  15. from selenium.webdriver.support.ui import WebDriverWait
  16. USERNAME_INPUT_NAME = "loginfmt"
  17. PASSWORD_INPUT_NAME = "passwd"
  18. MFA_INPUT_NAME = "otc"
  19. CONTINUE_BUTTON_ID = "idSIButton9"
  20. MFA_CONTINUE_BUTTON_ID = "idSubmit_SAOTCC_Continue"
  21. MFA_ERROR_TEXT_ID = "idSpan_SAOTCC_Error_OTC"
  22. VPN_INSTALL_PAGE_EXCLUSIVE_ELEMENT_ID = "provisioning_action_label"
  23. MAX_RETRY_DOMAIN_CHECK = 16
  24. MFA_MAX_RETRY_COUNT = 3
  25. ELEMENT_CHECK_DELAY = 0.5
  26. DOMAIN_CHECK_DELAY = 0.5
  27. LOGGER = logging.getLogger("OCMA")
  28. LOGGER.setLevel(logging.INFO)
  29. @dataclass
  30. class VPNCookie:
  31. domain: str
  32. cookie: str
  33. def login(
  34. username: str,
  35. password: str,
  36. mfa_secret: Optional[str] = None,
  37. vpn_site: str = "https://vpn.fhnw.ch",
  38. headless: bool = True,
  39. log_messages: bool = False,
  40. ) -> VPNCookie:
  41. if log_messages:
  42. formatter = logging.Formatter(
  43. "%(asctime)s: %(levelname)s - %(name)s - %(message)s"
  44. )
  45. fh_s = logging.StreamHandler()
  46. fh_s.setLevel(logging.INFO)
  47. fh_s.setFormatter(formatter)
  48. LOGGER.addHandler(fh_s)
  49. LOGGER.info("Starting")
  50. options = FirefoxOptions()
  51. if headless:
  52. LOGGER.info("Running in headless mode")
  53. options.add_argument("--headless")
  54. driver = webdriver.Firefox(options=options)
  55. driver.get(vpn_site)
  56. retries = MAX_RETRY_DOMAIN_CHECK
  57. while not _is_on_ms_login_page(driver) and retries > 0:
  58. retries -= 1
  59. time.sleep(DOMAIN_CHECK_DELAY)
  60. if retries < 0:
  61. raise ValueError(
  62. f"We never reached the MS login page! Currently on {driver.current_url}"
  63. )
  64. _fill_login(driver, username, password)
  65. _fill_mfa(driver, mfa_secret)
  66. _confirm_stay_signed_in(driver)
  67. _is_on_install_page(driver)
  68. return _get_webvpn_cookie(driver)
  69. def _fill_login(driver: webdriver.Firefox, username: str, password: str) -> None:
  70. LOGGER.info("Filling in login information")
  71. _check_on_ms_login_page(driver)
  72. if not _find_element(driver, By.NAME, USERNAME_INPUT_NAME):
  73. raise ValueError("Could not find login page!")
  74. driver.find_element(By.NAME, USERNAME_INPUT_NAME).send_keys(username)
  75. driver.find_element(By.NAME, PASSWORD_INPUT_NAME).send_keys(password)
  76. click_continue(driver) # Confirm username
  77. click_continue(driver) # Confirm password
  78. on_login_form = lambda: "saml2" in driver.current_url
  79. retries = MAX_RETRY_DOMAIN_CHECK
  80. while on_login_form() and retries > 0:
  81. LOGGER.info(
  82. f"Login information may not have yet been confirmed. Checking again (Try {MAX_RETRY_DOMAIN_CHECK - retries + 1} of {MAX_RETRY_DOMAIN_CHECK})"
  83. )
  84. time.sleep(ELEMENT_CHECK_DELAY)
  85. if on_login_form():
  86. LOGGER.info("Login information has not yet been confirmed. Trying again")
  87. click_continue(driver) # Confirm password
  88. retries -= 1
  89. if retries < 0:
  90. raise ValueError("Failed to confirm login form!")
  91. LOGGER.info("Login information filled out")
  92. def _fill_mfa(driver: webdriver.Firefox, mfa_secret: Optional[str]) -> None:
  93. LOGGER.info("Checking if we can fill in MFA information")
  94. _check_on_ms_login_page(driver)
  95. # Check if we have the MFA page
  96. if driver.current_url.endswith("/login") and mfa_secret is None:
  97. raise ValueError("You need to supply your MFA secret to log in!")
  98. # Check if we have an MFA code to enter
  99. if mfa_secret is None:
  100. LOGGER.info("Filling in login information")
  101. return
  102. for i in range(MFA_MAX_RETRY_COUNT):
  103. LOGGER.info(
  104. f"Filling in MFA information (Try {i + 1} of {MFA_MAX_RETRY_COUNT})"
  105. )
  106. if not _find_element(driver, By.NAME, MFA_INPUT_NAME):
  107. time.sleep(ELEMENT_CHECK_DELAY)
  108. continue
  109. mfa_code = get_mfa_code(mfa_secret)
  110. driver.find_element(By.NAME, MFA_INPUT_NAME).send_keys(mfa_code)
  111. click_continue(driver, MFA_CONTINUE_BUTTON_ID) # Confirm otp
  112. LOGGER.info(f"Confirmed MFA code")
  113. if not driver.current_url.endswith("/login"):
  114. # We have moved on
  115. LOGGER.info(f"We have moved away from the MFA page")
  116. break
  117. # Check for any errors
  118. if not _find_element(driver, By.ID, MFA_ERROR_TEXT_ID, 2):
  119. # Did not find an error
  120. LOGGER.info(f"MFA seems to have been accepted, no errors")
  121. break
  122. def _confirm_stay_signed_in(driver: webdriver.Firefox) -> bool:
  123. LOGGER.info(f"Cheking if we should confirm if we should stay signed in")
  124. if not _is_on_ms_login_page(driver):
  125. LOGGER.info(f"Already logged in, can't confirm 'stay signed in'")
  126. return False
  127. if not driver.current_url.endswith("/common/SAS/ProcessAuth"):
  128. LOGGER.info(
  129. f"We have reached a dead end. We have completed the login, but not on the 'stay signed in' page"
  130. )
  131. return False
  132. click_continue(driver) # Confirm stay signed in
  133. LOGGER.info(f"Confirmed to 'stay signed in'")
  134. return True
  135. def _find_element(driver: webdriver.Firefox, by: str, item: str, wait: int = 8) -> bool:
  136. try:
  137. w = WebDriverWait(driver, wait)
  138. w.until(EC.presence_of_element_located((by, item)))
  139. return True
  140. except TimeoutException:
  141. return False
  142. def _is_on_install_page(driver: webdriver.Firefox) -> None:
  143. if not _find_element(driver, By.ID, VPN_INSTALL_PAGE_EXCLUSIVE_ELEMENT_ID):
  144. raise ValueError("Could not find install page!")
  145. def _get_webvpn_cookie(driver: webdriver.Firefox) -> VPNCookie:
  146. webvpn_cookie = driver.get_cookie("webvpn")
  147. driver.close()
  148. if webvpn_cookie is None:
  149. raise ValueError(
  150. "Failed to find the webvpn cookie. Maybe the authentication has failed?"
  151. )
  152. webvpn_domain = webvpn_cookie["domain"]
  153. webvpn_value = webvpn_cookie["value"]
  154. return VPNCookie(domain=webvpn_domain, cookie=webvpn_value)
  155. def _check_on_ms_login_page(driver: webdriver.Firefox) -> None:
  156. if not _is_on_ms_login_page(driver):
  157. raise ValueError("We should still be on the MS login page but we aren't!")
  158. def _is_on_ms_login_page(driver: webdriver.Firefox) -> bool:
  159. return urlparse(driver.current_url).netloc == "login.microsoftonline.com"
  160. def click_continue(driver: webdriver.Firefox, btn_id: str = CONTINUE_BUTTON_ID) -> bool:
  161. """Returns true if still on login page, false if not"""
  162. for _ in range(16):
  163. try:
  164. driver.find_element(By.ID, btn_id).click()
  165. return True
  166. except (ElementClickInterceptedException, StaleElementReferenceException):
  167. pass
  168. except NoSuchElementException:
  169. pass
  170. time.sleep(ELEMENT_CHECK_DELAY)
  171. return False
  172. def get_mfa_code(secret: str) -> str:
  173. otp = OTP.fromb32(secret)
  174. code: str = otp.TOTP()[0]
  175. return code