def test01_open(self): conn = HTTPSConnection(Constants.HOSTNAME, port=Constants.PORT) conn.connect() conn.request('GET', '/') resp = conn.getresponse() print('Response = %s' % resp.read()) conn.close()
def test03_ssl_verification_of_peer_fails(self): ctx = SSL.Context(SSL.TLSv1_METHOD) def verify_callback(conn, x509, errnum, errdepth, preverify_ok): log.debug('SSL peer certificate verification failed for %r', x509.get_subject()) return preverify_ok ctx.set_verify(SSL.VERIFY_PEER, verify_callback) ctx.set_verify_depth(9) # Set bad location - unit test dir has no CA certs to verify with ctx.load_verify_locations(None, Constants.UNITTEST_DIR) conn = HTTPSConnection(Constants.HOSTNAME, port=Constants.PORT, ssl_context=ctx) conn.connect() self.assertRaises(SSL.Error, conn.request, 'GET', '/')
def test04_ssl_verification_with_subj_alt_name(self): ctx = SSL.Context(SSL.SSLv3_METHOD) verify_callback = ServerSSLCertVerification(hostname='localhost') ctx.set_verify(SSL.VERIFY_PEER, verify_callback) ctx.set_verify_depth(9) # Set correct location for CA certs to verify with ctx.load_verify_locations(None, Constants.CACERT_DIR) conn = HTTPSConnection(Constants.HOSTNAME, port=Constants.PORT, ssl_context=ctx) conn.connect() conn.request('GET', '/') resp = conn.getresponse() print('Response = %s' % resp.read())
def test03_ssl_verification_of_peer_succeeds(self): ctx = SSL.Context(SSL.TLSv1_METHOD) verify_callback = lambda conn, x509, errnum, errdepth, preverify_ok: \ preverify_ok ctx.set_verify(SSL.VERIFY_PEER, verify_callback) ctx.set_verify_depth(9) # Set correct location for CA certs to verify with ctx.load_verify_locations(None, Constants.CACERT_DIR) conn = HTTPSConnection(Constants.HOSTNAME, port=Constants.PORT, ssl_context=ctx) conn.connect() conn.request('GET', '/') resp = conn.getresponse() print('Response = %s' % resp.read())
def test04_ssl_verification_with_subj_common_name(self): ctx = SSL.Context(SSL.TLSv1_METHOD) # Explicitly set verification of peer hostname using peer certificate # subject common name verification = ServerSSLCertVerification(hostname='localhost', subj_alt_name_match=False) verify_callback = verification.get_verify_server_cert_func() ctx.set_verify(SSL.VERIFY_PEER, verify_callback) ctx.set_verify_depth(9) # Set correct location for CA certs to verify with ctx.load_verify_locations(None, Constants.CACERT_DIR) conn = HTTPSConnection(Constants.HOSTNAME, port=Constants.PORT, ssl_context=ctx) conn.connect() conn.request('GET', '/') resp = conn.getresponse() print('Response = %s' % resp.read())
def rerun(self,id): conn = getMySQLConn() with closing(conn.cursor()) as cursor: response = cursor.execute("SELECT path, http_method, request_params, body, rerun FROM transaction_log WHERE id = %s", (id,)) row = cursor.fetchone() conn.close() if row[4] == 1: raise cherrypy.HTTPRedirect("../translist?reason=This+transaction+has+already+been+re-run!") else: self.setRerun(id); ctx = SSL.Context(SSL.SSLv3_METHOD) httpcon = HTTPSConnection(host=hie_host, port=hie_port, ssl_context=ctx) userAndPass = b64encode((username + ":" + password).encode()).decode("ascii") headers = { 'Authorization' : 'Basic %s' % userAndPass } httpcon.request(row[1], "/" + row[0] +"?" + row[2], row[3], headers) resp = httpcon.getresponse() httpcon.close() raise cherrypy.HTTPRedirect("../translist?response="+ str(resp.status) + "&reason=" +resp.reason)
def test02_open_fails(self): conn = HTTPSConnection(Constants.HOSTNAME, port=Constants.PORT2) self.assertRaises(socket.error, conn.connect)
def _handleSecuredRedirect(self, response, sslCtx): '''Intercept security challenges - these are inferred by checking for a 302 response with a location header requesting a HTTPS endpoint ''' if response.status != httplib.FOUND: log.debug('_handleSecuredRedirect: No HTTP redirect found in ' 'response - passing back to caller') return # Check for redirect location authn_redirect_uri = response.getheader('Location') if authn_redirect_uri is None: log.error('_handleSecuredRedirect: no redirect location set for %r ' 'response- returning', httplib.FOUND) # Let client decide what to do with this response return # Check the scheme and only follow the redirect here if it HTTPS parsed_authn_redirect_uri = urlparse(authn_redirect_uri) if parsed_authn_redirect_uri.scheme != 'https': log.info('_handleSecuredRedirect: Non-HTTPS redirect location set ' 'for %r response - returning', httplib.FOUND) return # Prepare request authentication redirect location host, portStr = parsed_authn_redirect_uri.netloc.split(':', 1) port = int(portStr) authn_redirect_path = self.__class__._make_uri_path( parsed_authn_redirect_uri) # Process cookies from the response passed into this function and set # them in the authentication request. Use cookielib with fake urllib2 # HTTP request class needed to interface with response.info = lambda : response.msg authn_redirect_req = FakeUrllib2HTTPRequest(parsed_authn_redirect_uri) cookie_jar = CookieJar() cookie_jar.extract_cookies(response, authn_redirect_req) authn_redirect_ip_hdrs = authn_redirect_req.get_headers() # Redirect to HTTPS authentication endpoint uses GET method authn_conn = HTTPSConnection(host, port=port, ssl_context=sslCtx) authn_conn.request('GET', authn_redirect_path, None, authn_redirect_ip_hdrs) authn_response = authn_conn.getresponse() authn_conn.close() # Hack to make httplib response urllib2.Response-like authn_response.info = lambda : authn_response.msg cookie_jar.extract_cookies(authn_response, authn_redirect_req) if authn_response.status == httplib.FOUND: # Get redirect location return_uri = authn_response.getheader('Location') if return_uri is None: log.error('_handleSecuredRedirect: no redirect location set ' 'for %r response from %r', httplib.FOUND, authn_redirect_uri) # Return the response and let the client decide what to do with # it return authn_response # Check URI for HTTP scheme parsed_return_uri = urlparse(return_uri) if parsed_return_uri.scheme != 'http': # Expecting http - don't process but instead return to client log.error('_handleSecuredRedirect: return URI %r is not HTTP, ' 'passing back original response', return_uri) return # Make path return_uri_path = self.__class__._make_uri_path(parsed_return_uri) # Get host and port number (return_uri_host, return_uri_port_str) = parsed_return_uri.netloc.split(':', 1) return_uri_port = int(return_uri_port_str) # Add any cookies to header return_req = FakeUrllib2HTTPRequest(parsed_return_uri) cookie_jar.add_cookie_header(return_req) return_headers = return_req.get_headers() # Invoke return URI passing headers return_conn = httplib.HTTPConnection(return_uri_host, port=return_uri_port) return_conn.request('GET', return_uri_path, None, return_headers) return_uri_res = return_conn.getresponse() return_conn.close() return return_uri_res
def __call__(self, environ, start_response): if (self.allowed_request_methods and environ['REQUEST_METHOD' ].lower() not in self.allowed_request_methods): disallowedRequest = httpexceptions.HTTPBadRequest("Disallowed") return disallowedRequest(environ, start_response) if not self.__environSessionKeyName: sslCtx = None else: session = environ.get(self.__environSessionKeyName) if session is None: msg = "No session in environ" http500Error = httpexceptions.HTTPInternalServerError(msg) return http500Error(environ, start_response) sslCtx = session[self.__ctxSessionKeyName] if self.scheme == 'http': conn = httplib.HTTPConnection(self.host) elif self.scheme == 'https': conn = HTTPSConnection(self.host, ssl_context=sslCtx) else: raise ValueError( "Unknown scheme for %r: %r" % (self.address, self.scheme)) headers = {} for key, value in environ.items(): if key.startswith('HTTP_'): key = key[5:].lower().replace('_', '-') if key == 'host' or key in self.suppress_http_headers: continue headers[key] = value headers['host'] = self.host if 'REMOTE_ADDR' in environ: headers['x-forwarded-for'] = environ['REMOTE_ADDR'] if environ.get('CONTENT_TYPE'): headers['content-type'] = environ['CONTENT_TYPE'] if environ.get('CONTENT_LENGTH'): if environ['CONTENT_LENGTH'] != '-1': headers['content-length'] = environ['CONTENT_LENGTH'] path_info = urllib.quote(environ['PATH_INFO']) if self.path: request_path = path_info if request_path and request_path[0] == '/': request_path = request_path[1:] path = urljoin(self.path, request_path) else: path = path_info if environ.get('QUERY_STRING'): path += '?' + environ['QUERY_STRING'] conn.request(environ['REQUEST_METHOD'], path, environ['wsgi.input'], headers) res = conn.getresponse() conn.close() # Handle a security redirect - if not handled it returns None and the # original response is returned redirectRes = self._handleSecuredRedirect(res, sslCtx) if redirectRes is None: _res = res else: _res = redirectRes headers_out = parse_headers(_res.msg) status = '%s %s' % (_res.status, _res.reason) start_response(status, headers_out) length = int(_res.getheader('content-length', '-1')) response = FileObjResponseIterator(_res.fp, file_size=length) return response