connect.py 7.2 KB

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