Exemplo n.º 1
0
 def post(url, allow_mitm=False, **kwargs):
     if not allow_mitm:
         fingerprint_info = SSLUtil.requestFingerprintFromURL(url)
         if SSLUtil.__compare_known_fingerprints__(fingerprint_info):
             # known fingerprint -> skip check
             _, _, fp = fingerprint_info
             s = requests.Session()
             s.verify = False
             s.mount(url, FingerprintAdapter(fp))
             print("Execute POST by known fingerprint")
             r = s.post(url, **kwargs)
             s.close()
             return r
         else:
             # try global certificate
             s = requests.Session()
             s.verify = True
             print("Execute POST by global HTTPS CERT system")
             r = s.post(url, **kwargs)
             s.close()
             return r
     else:
         # dangerous
         s = requests.Session()
         s.verify = False
         print("Execute POST UNSAFE")
         r = s.post(url, **kwargs)
         s.close()
         return r
Exemplo n.º 2
0
def call_api(action, server, userid=None, username=None):
    """Wrapper thing to call the API based on different actions."""
    if action == 'deluser' and not userid:
        raise Exception('Cannot call deluser without passing a User ID')

    # Construct the URL string to use and get the sha256 fp from the server definition
    urlline = [servers[server]['apiUrl'], '/access-keys']
    certfp = servers[server]['certSha256']

    # Mount adapter to verify fingerprint
    s = requests.Session()
    s.mount(urlline[0], FingerprintAdapter(certfp))

    if action == "adduser":
        try:
            r = s.post(''.join(urlline), verify=False)
            pass
        except Exception as e:
            raise e

        # TODO: Figure out how to get the username to show up in the record we print when done
        if username:
            data = json.loads(r.text)
            uid = data['id']
            urlline.append("/" + str(uid) + "/name")
            try:
                r2 = s.put(''.join(urlline),
                           data={'name': username},
                           verify=False)
                pass
            except Exception as e:
                raise e
            print r2.text

    elif action == "deluser":
        urlline.append("/" + str(userid))
        try:
            r = s.delete(''.join(urlline), verify=False)
            pass
        except Exception as e:
            raise e
        else:
            if r.status_code == requests.codes.no_content:
                print "User key %s deleted successfully" % userid
            else:
                print "Unexpected status code: %s" % r.status_code
            pass

    elif action == "listusers":
        try:
            r = s.get(''.join(urlline), verify=False)
            pass
        except Exception as e:
            raise e
    else:
        raise Exception("%s is not a legal option!" % action)

    return r
Exemplo n.º 3
0
def _install_fingerprint_adapter(session, fingerprint):
    prefix = "https://"
    try:
        from requests_toolbelt.adapters.fingerprint import FingerprintAdapter
    except ImportError:
        raise RuntimeError("`verify_fingerprint` can only be used with "
                           "requests-toolbelt versions >= 0.4.0")

    if not isinstance(session.adapters[prefix], FingerprintAdapter):
        fingerprint_adapter = FingerprintAdapter(fingerprint)
        session.mount(prefix, fingerprint_adapter)
Exemplo n.º 4
0
 def get(self, url):
     session = requests.Session()
     session.mount(API_URL, FingerprintAdapter(SSL_FINGERPRINT))
     try:
         response = session.get(API_URL + url,
                                headers=self.configuration.get_headers())
         data = self._decode(response.text)
         if response.status_code < 200 or response.status_code >= 300:
             Logger.error(
                 LOCATION, 'status: ' + str(response.status_code) +
                 ', body: ' + json.dumps(data))
             raise falcon.HTTPServiceUnavailable
         return self._get_response(data)
     except requests.exceptions.SSLError:
         self._handle_ssl_exception()
Exemplo n.º 5
0
 def post(self, url, data):
     session = requests.Session()
     session.mount(API_URL, FingerprintAdapter(SSL_FINGERPRINT))
     try:
         response = session.post(API_URL + url,
                                 data=self._create_request_body(data),
                                 headers=self.configuration.get_headers())
         if response.status_code < 200 or response.status_code >= 300:
             Logger.error(
                 LOCATION, 'status: ' + str(response.status_code) +
                 ', body: ' + response.text)
             raise falcon.HTTPServiceUnavailable
     except requests.exceptions.SSLError:
         self._handle_ssl_exception()
     except:
         Logger.error(LOCATION, 'Failed to POST resource.')
         raise falcon.HTTPServiceUnavailable
Exemplo n.º 6
0
    def _request_api(self, path, data=None, method="GET"):
        """Helper method for making a REST-compliant API call.

        Args:
            path: path on the server to call
            data: dictionary of data to send to the server in message body
            method: - HTTP verb to use for the request

        Returns:
            the JSON-parsed result body
        """

        complete_path = self.api_endpoint + path

        session = Session()
        session.headers.update(self.headers)

        for fingerprint in self.fingerprints:
            session.mount(self.api_endpoint, FingerprintAdapter(fingerprint.lower()))
            try:
                response = session.request(method, complete_path, json=data)
            except SSLError:
                logging.warn('Fingerprint "%s" was invalid', fingerprint)
            else:
                break
            finally:
                session.close()
        else:
            raise SSLError


        if 200 <= response.status_code < 300 or self._has_error(response.json()):
            if response.text == '':
                return {}
            return response.json()
        elif response.status_code in ERROR_MESSAGES:
            return {'error': ERROR_MESSAGES[response.status_code]}

        logger.warn("Querying the API failed when accessing '%s': %d",
                    complete_path,
                    response.status_code)

        return {'error': {
            'message': "internal_server_error",
            'description': "We are very sorry, but something went wrong",
            'code': 90000}}
Exemplo n.º 7
0
 def __init__(self,
              app_id,
              client_key,
              api_version=api_version,
              dev_mode=False,
              verify=None):
     """Add your appId and clientKey. If you are using development key, set dev_mode=True.
     :param app_id: Your Leanplum appId.
     :param client_key: Your Leanplum clientKey (production or development).
     :param api_version: Leanplum API version to use defaults to 1.0.6. Should not need to change.
     :param dev_mode: Set to True to access the development environment. Defaults to False.
     """
     self.app_id = app_id
     self.client_key = client_key
     self.dev_mode = dev_mode
     # if api_version is not None:
     #     self.api_version = api_version
     if verify:
         self.requests = requests.Session()
         self.requests.mount(self.BASE_HOST, FingerprintAdapter(verify))
     else:
         self.requests = requests
Exemplo n.º 8
0
 def __init_requests_session(self):
     self.session = requests.Session()
     self.session.mount(self.apiUrl, FingerprintAdapter(self.certSha256))
Exemplo n.º 9
0
 def setUp(self):
     self.session = requests.Session()
     self.session.mount('https://http2bin.org', FingerprintAdapter(self.HTTP2BIN_FINGERPRINT))
     self.recorder = get_betamax(self.session)
Exemplo n.º 10
0
def upgrade(host, port, username, password, filenames, trustdb=None):
    cert = get_server_cert(host, port, trustdb)
    fingerprint = sha256(cert).hexdigest()

    session = requests.Session()
    # self-signed verification fails, count on FingerprintAdapter for validation
    session.verify = False
    session.mount('https://', FingerprintAdapter(fingerprint))

    session.headers.update(
        {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:85.0) Gecko/20100101 Firefox/85.0'})

    base_url = 'https://%s:%d' % (host, port)

    r = session.get(
        base_url + '/session?aimGetProp=hostname,gui_str_title_bar,OEMHostName,fwVersion,sysDesc')
    r.raise_for_status()
    print(host, r.json()['aimGetProp']['hostname'])

    try:
        for retry in range(3):
            login_url = base_url + '/login.html'
            r = session.get(login_url)
            r.raise_for_status()
            session.post(base_url + '/data/logout')

            r = session.post(base_url + '/data/login',
                             data={'user': username, 'password': password},
                             headers={'Referer': login_url})
            r.raise_for_status()

            if '<authResult>0</authResult>' in r.text:
                break
            elif '<authResult>1</authResult>' in r.text:
                blockingTime, = re.search(
                    r'<blockingTime>(\d+)</blockingTime>', r.text).groups()
                blockingTime = int(blockingTime)
                if blockingTime == 0:
                    raise RuntimeError('Incorrect username or password')
                print('login blocked, waiting %d seconds' %
                      blockingTime, file=sys.stderr)
                time.sleep(blockingTime)
            else:
                raise RuntimeError('Login failure: ' + r.text)
        else:
            raise RuntimeError('Login retries exceeded')

        st1, st2 = re.search(
            r'ST1=([0-9a-f]+),ST2=([0-9a-f]+)', r.text).groups()

        r = session.get(base_url + '/cemgui/fwupdate.html')
        r.raise_for_status()
        scratch_pad, = re.search(
            r'dupScratchPadURI = "(.*?)"', r.text).groups()
        apply_path, = re.search(r'applyURI = "(.*?)"', r.text).groups()

        # a GET with side-effects, oh my
        r = session.get(base_url + scratch_pad + '?splock=1')
        r.raise_for_status()

        for filename in filenames:
            print(filename, file=sys.stderr)
            e = MultipartEncoder(fields={
                'firmwareUpdate': (
                    os.path.basename(filename),
                    open(filename, 'rb'),
                    'application/x-ms-dos-executable'
                )
            })
            m = MultipartEncoderMonitor(e, status_callback)
            r = session.post(base_url + scratch_pad,
                             params={'ST1': st1},
                             data=m,
                             headers={'Content-Type': m.content_type})
            print(file=sys.stderr)
            r.raise_for_status()

        # response is cumulative, and contains all files sent until now
        targets = [m.group(1) for m in re.finditer(r'target="(.*?)"', r.text)]

        xml = '<Repository><target>%s</target><rebootType>1</rebootType></Repository>' % ','.join(
            target for target in targets if target != '')
        r = session.put(base_url + apply_path, data=xml, headers={'ST2': st2})
        r.raise_for_status()
    finally:
        session.get(base_url + '/data/logout')
 def create_session(self) -> None:
     self.session = requests.Session()
     self.session.mount(
         self.base_url(),
         FingerprintAdapter(self.rfpac.host_certificate_fingerprint()),
     )