Example #1
0
 def test_disable_headless(self):
     launcher = Launcher({'headless': False})
     for opt in self.headless_options:
         self.assertNotIn(opt, launcher.chrome_args)
Example #2
0
 def test_executable(self):
     launcher = Launcher({'executablePath': '/path/to/chrome'})
     self.assertEqual(launcher.exec, '/path/to/chrome')
Example #3
0
 async def get_new_browser(self):
     """Get a new browser, set proxy and arguments"""
     agent = UserAgent(verify_ssl=False).random
     args = [
         '--cryptauth-http-host ""',
         '--disable-accelerated-2d-canvas',
         '--disable-background-networking',
         '--disable-background-timer-throttling',
         '--disable-browser-side-navigation',
         '--disable-client-side-phishing-detection',
         '--disable-default-apps',
         '--disable-dev-shm-usage',
         '--disable-device-discovery-notifications',
         '--disable-extensions',
         '--disable-features=site-per-process',
         '--disable-hang-monitor',
         '--disable-java',
         '--disable-popup-blocking',
         '--disable-prompt-on-repost',
         '--disable-setuid-sandbox',
         '--disable-sync',
         '--disable-translate',
         '--disable-web-security',
         '--disable-webgl',
         '--metrics-recording-only',
         '--no-first-run',
         '--safebrowsing-disable-auto-update',
         '--no-sandbox',
         # Automation arguments
         '--enable-automation',
         '--password-store=basic',
         '--use-mock-keychain',
         '--lang="{0}"'.format(self.language),
         '--user-agent="{0}"'.format(agent)
     ]
     if self.proxy:
         if self.proxy == 'auto':
             self.proxy = get_random_proxy()
         args.append(f"--proxy-server={self.proxy}")
     if "args" in self.options:
         args.extend(self.options.pop("args"))
     self.options.update({
         "headless": self.headless,
         "args": args,
         #  Silence Pyppeteer logs
         "logLevel": "CRITICAL"
     })
     if self.chromePath:
         self.options.update({
             "executablePath": self.chromePath,
         })
     self.launcher = Launcher(self.options,
                              handleSIGINT=False,
                              handleSIGTERM=False,
                              handleSIGHUP=False)
     browser = await self.launcher.launch()
     # Set user-agent to all pages
     pages = await browser.pages()
     for page in pages:
         await page.setUserAgent(agent)
     self.page = pages[0]  # Set first page
     return browser
Example #4
0
 def test_no_option(self):
     launcher = Launcher()
     self.check_default_args(launcher)
     self.assertEqual(launcher.exec, str(chromium_excutable()))
Example #5
0
 def test_user_data_dir(self):
     launcher = Launcher({'args': ['--user-data-dir=/path/to/profile']})
     self.check_default_args(launcher)
     self.assertIn('--user-data-dir=/path/to/profile',
                   launcher.chromeArguments)
     self.assertIsNone(launcher.temporaryUserDataDir)
Example #6
0
 def test_args(self):
     launcher = Launcher({'args': ['--some-args']})
     self.check_default_args(launcher)
     self.assertIn('--some-args', launcher.chromeArguments)
Example #7
0
 def test_disable_default_args(self):
     launcher = Launcher(ignoreDefaultArgs=True)
     # check default args
     self.assertNotIn('--no-first-run', launcher.chromeArguments)
     # check automation args
     self.assertNotIn('--enable-automation', launcher.chromeArguments)
Example #8
0
 def test_user_data_dir(self):
     launcher = Launcher({'args': ['--user-data-dir=/path/to/profile']})
     self.check_default_args(launcher)
     self.assertIn('--user-data-dir=/path/to/profile', launcher.chrome_args)
     self.assertIsNone(launcher._tmp_user_data_dir)
Example #9
0
    async def _render_js_form(self, url, username, password, mfa=None):
        print("before launch")
        # l = Launcher(executablePath=self._EXEC_PATH, headless=self._headless, ignoreHTTPSErrors=True, options={"ignoreDefaultArgs": True, "args": ["--user-data-dir=\"C:\\\""]})
        # l = Launcher(executablePath=self._EXEC_PATH, headless=self._headless, ignoreHTTPSErrors=True, options={"ignoreDefaultArgs": True, "args": ["--no-sandbox", "--headless"]})
        l = Launcher(executablePath=self._EXEC_PATH,
                     headless=self._headless,
                     ignoreHTTPSErrors=True)
        print(f"url {l.url}")
        print(f"url {l.cmd}")
        browser = await l.launch()
        print("after launch")

        print("before page")
        pages = await browser.pages()
        print("after page")
        page = pages[0]

        async def _saml_response(req):
            print("saml response")
            if req.url == 'https://signin.aws.amazon.com/saml':
                self.saml_response = parse_qs(req.postData)['SAMLResponse'][0]
                print("saml response" + self.saml_response)
                await req.respond({
                    'status': 200,
                    'contentType': 'text/plain',
                    'body': ''
                })
                print("response done")
            else:
                await req.continue_()

        print("load url")
        await page.goto(url, waitUntil='domcontentloaded')
        print("url loaded")
        await page.waitForSelector(
            'input[name="loginfmt"]:not(.moveOffScreen)', {"visible": True})
        print("loginfmt waited")
        await page.focus('input[name="loginfmt"]')
        print("loginfmt focus")
        await page.keyboard.type(username)
        print("typed username")
        await page.click('input[type=submit]')
        print("click submit")
        await page.waitForSelector(
            'input[name="Password"]:not(.moveOffScreen)', {"visible": True})
        print("waiting for password")
        await page.focus('input[name="Password"]')
        print("focus password")
        await page.keyboard.type(password)
        print("type password")
        await page.click('span[class=submit]')

        try:
            if await self._querySelector(page, '.has-error'):
                raise FormError
            print("final submit")
            time.sleep(600)
            await page.click('input[type=submit]')
            print("done")

            if mfa:
                if self._azure_mfa not in MFA_WAIT_METHODS:
                    await page.waitForSelector(
                        'input[name="otc"]:not(.moveOffScreen)',
                        {"visible": True})
                    await page.focus('input[name="otc"]')
                    mfa_token = input('Azure MFA Token: ')
                    for l in mfa_token:
                        await page.keyboard.sendCharacter(l)
                    await page.click('input[type=submit]')
                else:
                    print('Processing MFA authentication...')

            if self._azure_kmsi:
                await page.waitForSelector('form[action="/kmsi"]',
                                           timeout=self._AWAIT_TIMEOUT)
                await page.waitForSelector('#idBtn_Back')
                await page.click('#idBtn_Back')

            async def response_callback(resp):
                print(f"url: {resp.url}")
                print(f"status: {resp.status}")
                text = await resp.text()
                print(f"json: {text}")

            page.on('request', _saml_response)

            print("sending request")
            await page.setRequestInterception(True)
            print("intercepted")

            wait_time = time.time() + self._MFA_TIMEOUT
            while time.time() < wait_time and not self.saml_response:
                if await self._querySelector(page, '.has-error'):
                    raise FormError

            if not self.saml_response:
                raise TimeoutError

        except (TimeoutError, BrowserError, FormError) as e:
            print('An error occurred while authenticating, check credentials.')
            print(e)
            if self._debug:
                debugfile = 'aadaerror-{}.png'.format(
                    datetime.now().strftime("%Y-%m-%dT%H%m%SZ"))
                await page.screenshot({'path': debugfile})
                print('See screenshot {} for clues.'.format(debugfile))
            exit(1)