Пример #1
0
    def test05_open_with_subj_alt_names_verification(self):
        ctx = SSL.Context(SSL.TLSv1_2_METHOD)

        # Set wildcard hostname for subject alternative name matching -
        # setting a minimum of two name components for hostname
        split_hostname = Constants.HOSTNAME.split('.', 1)
        if len(split_hostname) > 1:
            _hostname = '*.' + split_hostname[-1]
        else:
            _hostname = Constants.HOSTNAME

        server_ssl_verify = ServerSSLCertVerification(hostname=_hostname)
        verify_callback_ = server_ssl_verify.get_verify_server_cert_func()
        ctx.set_verify(SSL.VERIFY_PEER, verify_callback_)

        # Set default verify paths if testing with peer that has corresponding
        # CA cert in bundle provided with the OS.  In this case, load verify
        # locations is not needed.
        #ctx.set_default_verify_paths()

        ctx.set_verify_depth(9)

        # Set correct location for CA certs to verify with
        ctx.load_verify_locations(None, Constants.CACERT_DIR)

        opener = build_opener(ssl_context=ctx)
        res = opener.open(Constants.TEST_URI)
        self.assertTrue(res)
        print("res = %s" % res.read())
Пример #2
0
 def test04_open_peer_cert_verification_fails(self):
     # Explicitly set empty CA directory to make verification fail
     ctx = SSL.Context(SSL.SSLv3_METHOD)
     verify_callback = lambda conn, x509, errnum, errdepth, preverify_ok: \
         preverify_ok 
         
     ctx.set_verify(SSL.VERIFY_PEER, verify_callback)
     ctx.load_verify_locations(None, './')
     opener = build_opener(ssl_context=ctx)
     self.failUnlessRaises(SSL.Error, opener.open, Constants.TEST_URI)
Пример #3
0
    def test04_open_peer_cert_verification_fails(self):
        # Explicitly set empty CA directory to make verification fail
        ctx = SSL.Context(SSL.SSLv3_METHOD)
        verify_callback = lambda conn, x509, errnum, errdepth, preverify_ok: \
            preverify_ok

        ctx.set_verify(SSL.VERIFY_PEER, verify_callback)
        ctx.load_verify_locations(None, './')
        opener = build_opener(ssl_context=ctx)
        self.failUnlessRaises(SSL.Error, opener.open, Constants.TEST_URI)
Пример #4
0
def open_url(url, config, data=None, handlers=None):
    """Attempts to open a connection to a specified URL.
    @param url: URL to attempt to open
    @param config: SSL context configuration
    @type config: Configuration
    @param data: HTTP POST data
    @type data: str
    @param handlers: list of custom urllib2 handlers to add to the request
    @type handlers: iterable
    @return: tuple (
        returned HTTP status code or 0 if an error occurred
        returned message or error description
        response object)
    """
    debuglevel = 1 if config.debug else 0

    # Set up handlers for URL opener.
    if config.cookie:
        cj = config.cookie
    else:
        cj = cookielib.CookieJar()
        
    # Use a cookie processor that accumulates cookies when redirects occur so
    # that an application can redirect for authentication and retain both any
    # cookies for the application and the security system (c.f.,
    # urllib2.HTTPCookieProcessor which replaces cookies).
    cookie_handler = AccumulatingHTTPCookieProcessor(cj)

    if not handlers:
        handlers = []
        
    handlers.append(cookie_handler)

    if config.debug:
        http_handler = HTTPHandler(debuglevel=debuglevel)
        https_handler = HTTPSContextHandler(config.ssl_context, 
                                            debuglevel=debuglevel)
        handlers.extend([http_handler, https_handler])
        
    if config.http_basicauth:
        # currently only supports http basic auth
        auth_handler = HTTPBasicAuthHandler(HTTPPasswordMgrWithDefaultRealm())
        auth_handler.add_password(realm=None, uri=url,
                                  user=config.httpauth[0],
                                  passwd=config.httpauth[1])
        handlers.append(auth_handler)


    # Explicitly remove proxy handling if the host is one listed in the value of
    # the no_proxy environment variable because urllib2 does use proxy settings 
    # set via http_proxy and https_proxy, but does not take the no_proxy value 
    # into account.
    if not _should_use_proxy(url, config.no_proxy):
        handlers.append(urllib2.ProxyHandler({}))
        log.debug("Not using proxy")
    elif config.proxies:
        handlers.append(urllib2.ProxyHandler(config.proxies))
        log.debug("Configuring proxies: %s" % config.proxies)

    opener = build_opener(*handlers, ssl_context=config.ssl_context)
    
    headers = config.headers
    if headers is None: 
        headers = {}
        
    request = urllib2.Request(url, data, headers)

    # Open the URL and check the response.
    return_code = 0
    return_message = ''
    response = None
    try:
        response = opener.open(request)
        return_message = response.msg
        return_code = response.code
        if log.isEnabledFor(logging.DEBUG):
            for index, cookie in enumerate(cj):
                log.debug("%s  :  %s", index, cookie)
                
    except urllib2.HTTPError, exc:
        return_code = exc.code
        return_message = "Error: %s" % exc.msg
        if log.isEnabledFor(logging.DEBUG):
            log.debug("%s %s", exc.code, exc.msg)
Пример #5
0
def open_url(url, config, data=None, handlers=None):
    """Attempts to open a connection to a specified URL.
    @param url: URL to attempt to open
    @param config: SSL context configuration
    @type config: Configuration
    @param data: HTTP POST data
    @type data: str
    @param handlers: list of custom urllib2 handlers to add to the request
    @type handlers: iterable
    @return: tuple (
        returned HTTP status code or 0 if an error occurred
        returned message or error description
        response object)
    """
    debuglevel = 1 if config.debug else 0

    # Set up handlers for URL opener.
    if config.cookie:
        cj = config.cookie
    else:
        cj = cookiejar_.CookieJar()

    # Use a cookie processor that accumulates cookies when redirects occur so
    # that an application can redirect for authentication and retain both any
    # cookies for the application and the security system (c.f.,
    # urllib2.HTTPCookieProcessor which replaces cookies).
    cookie_handler = AccumulatingHTTPCookieProcessor(cj)

    if not handlers:
        handlers = []

    handlers.append(cookie_handler)

    if config.debug:
        http_handler = HTTPHandler_(debuglevel=debuglevel)
        https_handler = HTTPSContextHandler(config.ssl_context,
                                            debuglevel=debuglevel)
        handlers.extend([http_handler, https_handler])

    if config.http_basicauth:
        # currently only supports http basic auth
        auth_handler = HTTPBasicAuthHandler_(HTTPPasswordMgrWithDefaultRealm_())
        auth_handler.add_password(realm=None, uri=url,
                                  user=config.httpauth[0],
                                  passwd=config.httpauth[1])
        handlers.append(auth_handler)


    # Explicitly remove proxy handling if the host is one listed in the value of
    # the no_proxy environment variable because urllib2 does use proxy settings
    # set via http_proxy and https_proxy, but does not take the no_proxy value
    # into account.
    if not _should_use_proxy(url, config.no_proxy):
        handlers.append(ProxyHandler_({}))
        log.debug("Not using proxy")
    elif config.proxies:
        handlers.append(ProxyHandler_(config.proxies))
        log.debug("Configuring proxies: %s" % config.proxies)

    opener = build_opener(*handlers, ssl_context=config.ssl_context)

    headers = config.headers
    if headers is None:
        headers = {}

    request = Request_(url, data, headers)

    # Open the URL and check the response.
    return_code = 0
    return_message = ''
    response = None

    # FIXME
    response = opener.open(request)

    try:
        response = opener.open(request)
        return_message = response.msg
        return_code = response.code
        if log.isEnabledFor(logging.DEBUG):
            for index, cookie in enumerate(cj):
                log.debug("%s  :  %s", index, cookie)

    except HTTPError_ as exc:
        return_code = exc.code
        return_message = "Error: %s" % exc.msg
        if log.isEnabledFor(logging.DEBUG):
            log.debug("%s %s", exc.code, exc.msg)

    except Exception as exc:
        return_message = "Error: %s" % exc.__str__()
        if log.isEnabledFor(logging.DEBUG):
            import traceback
            log.debug(traceback.format_exc())

    return (return_code, return_message, response)
Пример #6
0
 def test03_open_fails_unknown_loc(self):
     opener = build_opener()
     self.failUnlessRaises(URLError, opener.open, Constants.TEST_URI2)
Пример #7
0
 def test02_open(self):
     opener = build_opener()
     res = opener.open(Constants.TEST_URI)
     self.assert_(res)
     print("res = %s" % res.read())
Пример #8
0
 def test01_urllib2_build_opener(self):     
     opener = build_opener()
     self.assert_(opener)
Пример #9
0
 def test03_open_fails_unknown_loc(self):
     opener = build_opener()
     self.failUnlessRaises(URLError, opener.open, Constants.TEST_URI2)
Пример #10
0
 def test02_open(self):
     opener = build_opener()
     res = opener.open(Constants.TEST_URI)
     self.assert_(res)
     print("res = %s" % res.read())
Пример #11
0
 def test01_urllib2_build_opener(self):
     opener = build_opener()
     self.assert_(opener)