def ctSSL_initialize(multithreading=False): """ Initialize ctSSL's ctypes bindings, and OpenSSL libraries and error strings. Optionally initializes OpenSSL multithreading support. Should always be called before any other ctSSL function. """ # Initialize multithreading multithreading=False # TODO: Clean start. Disabled for now, causes issues # Might not be required ? if multithreading: openSSL_threading_init() openSSL_threading = True # Initialize libraries and error strings libssl.SSL_library_init() libssl.SSL_load_error_strings() if libcrypto.RAND_status() != 1: raise ctSSLInitError('OpenSSL PRNG not seeded with enough data.') # Tell ctypes the arguments and return types for every C function that is exposed BIO.init_BIO_functions() SSL_CTX.init_SSL_CTX_functions() SSL.init_SSL_functions() SSL_SESSION.init_SSL_SESSION_functions() X509.init_X509_functions() errors.init_ERR_functions()
def ctSSL_initialize(multithreading=False, zlib=False): """ Initialize ctSSL's ctypes bindings, and OpenSSL libraries and error strings. Should always be called before any other ctSSL function. @type multithreading: boolean @param multithreading: Initialize OpenSSL multithreading support. TODO: This actually doesn't do anything ATM. @type zlib: boolean @param zlib: Initialize support for Zlib compression. """ # Initialize multithreading multithreading = False # TODO: Clean start. Disabled for now, causes issues # Might not be required ? if multithreading: openSSL_threading_init() openSSL_threading = True # Initialize libraries and error strings libssl.SSL_library_init() libssl.SSL_load_error_strings() if libcrypto.RAND_status() != 1: raise ctSSLInitError("OpenSSL PRNG not seeded with enough data.") # Tell ctypes the arguments and return types for every C function that is exposed BIO.init_BIO_functions() SSL_CTX.init_SSL_CTX_functions() SSL.init_SSL_functions() SSL_SESSION.init_SSL_SESSION_functions() X509.init_X509_functions() errors.init_ERR_functions() if zlib: # Enable Zlib compression. Can only be done globally. try: libcrypto.COMP_zlib.argtypes = [] libcrypto.COMP_zlib.restype = c_void_p libssl.SSL_COMP_add_compression_method.argtypes = [c_int, c_void_p] libssl.SSL_COMP_add_compression_method.restype = c_int zlib_comp_p = libcrypto.COMP_zlib() has_zlib = libssl.SSL_COMP_add_compression_method(1, zlib_comp_p) except AttributeError: # OpenSSL is super old and COMP_XX() is not defined ? raise errors.ctSSLFeatureNotAvailable( "Could not enable Zlib compression: not supported by the version of the OpenSSL library that was loaded ?" ) except: # TODO: Check for common errors here and add meaningful error message raise if has_zlib != 0: raise errors.ctSSLFeatureNotAvailable( "Could not enable Zlib compression: OpenSSL was not built with Zlib support ?" ) features_not_available.ZLIB_NOT_AVAIL = False
def ctSSL_initialize(multithreading=False, zlib=False): """ Initialize ctSSL's ctypes bindings, and OpenSSL libraries and error strings. Should always be called before any other ctSSL function. @type multithreading: boolean @param multithreading: Initialize OpenSSL multithreading support. TODO: This actually doesn't do anything ATM. @type zlib: boolean @param zlib: Initialize support for Zlib compression. """ # Initialize multithreading multithreading = False # TODO: Clean start. Disabled for now, causes issues # Might not be required ? if multithreading: openSSL_threading_init() openSSL_threading = True # Initialize libraries and error strings libssl.SSL_library_init() libssl.SSL_load_error_strings() if libcrypto.RAND_status() != 1: raise ctSSLInitError('OpenSSL PRNG not seeded with enough data.') # Tell ctypes the arguments and return types for every C function that is exposed BIO.init_BIO_functions() SSL_CTX.init_SSL_CTX_functions() SSL.init_SSL_functions() SSL_SESSION.init_SSL_SESSION_functions() X509.init_X509_functions() errors.init_ERR_functions() if zlib: # Enable Zlib compression. Can only be done globally. try: libcrypto.COMP_zlib.argtypes = [] libcrypto.COMP_zlib.restype = c_void_p libssl.SSL_COMP_add_compression_method.argtypes = [c_int, c_void_p] libssl.SSL_COMP_add_compression_method.restype = c_int zlib_comp_p = libcrypto.COMP_zlib() has_zlib = libssl.SSL_COMP_add_compression_method(1, zlib_comp_p) except AttributeError: # OpenSSL is super old and COMP_XX() is not defined ? raise errors.ctSSLFeatureNotAvailable( "Could not enable Zlib compression: not supported by the version of the OpenSSL library that was loaded ?" ) except: # TODO: Check for common errors here and add meaningful error message raise if has_zlib != 0: raise errors.ctSSLFeatureNotAvailable( "Could not enable Zlib compression: OpenSSL was not built with Zlib support ?" ) features_not_available.ZLIB_NOT_AVAIL = False
def test(): context = SSL.Context(SSL.TLSv1_METHOD) sock = socket.create_connection(('www.google.com', 443), timeout=2) connection = SSL.Connection(context, sock) connection.set_connect_state() connection.do_handshake() connection.send('GET / HTTP/1.1\r\n\r\n') print(connection.recv(1024))
def process_config_value(key, value, config, LOG): """ Handles configuration values, checking for correctness and storing the appropriate settings in the config dictionary """ boolean_keys = ['tsi.open_user_sessions', 'tsi.switch_uid', 'tsi.enforce_os_gids', 'tsi.fail_on_invalid_gids', 'tsi.use_id_to_resolve_gids', 'tsi.use_syslog', 'tsi.debug' ] for bool_key in boolean_keys: if bool_key == key: config[key] = value.lower() in ["1", "true"] return if key.startswith('tsi.acl'): if 'NONE' == value or 'POSIX' == value or 'NFS' == value: path = key[8:] acl = config.get('tsi.acl', {}) acl[path] = value config['tsi.acl'] = acl else: raise KeyError("Invalid value '%s' for parameter '%s', " "must be 'NONE', 'POSIX' or 'NFS'" % (value, key)) elif key.startswith('tsi.allowed_dn.'): allowed_dns = config.get('tsi.allowed_dns', []) dn = SSL.convert_dn(value) LOG.info("Allowing SSL connections for %s" % value) allowed_dns.append(dn) config['tsi.allowed_dns'] = allowed_dns else: config[key] = value
def __init__(self, ssl_context=None): AbstractHTTPHandler.__init__(self) if ssl_context is not None: self.ctx = ssl_context else: self.ctx = SSL.Context()
def connect(self): "Connect to a host on a given (SSL) port" results = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM) for r in results: af, socktype, proto, canonname, sa = r try: sock = socket.socket(af, socktype, proto) except socket.error: sock = None continue try: sock.connect((self.host, self.port)) sock.settimeout(self.timeout) except socket.error: sock.close() sock = None continue break if sock is None: raise socket.error("Unable to connect to the host and port specified") self.sock = SSL.SSLSocket(sock, self.trusted_certs) self.sock.init_ssl()
def connect(self): error = None # We ignore the returned sockaddr because SSL.Connection.connect needs # a host name. for (family, _, _, _, _) in \ socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): sock = None try: try: sock = SSL.Connection(self.ssl_ctx, family=family) if self.session is not None: sock.set_session(self.session) sock.connect((self.host, self.port)) self.sock = sock sock = None return except socket.error, e: # Other exception are probably SSL-related, in that case we # abort and the exception is forwarded to the caller. error = e finally: if sock is not None: sock.close() if error is None: raise AssertionError("Empty list returned by getaddrinfo") raise error
def connect(self): # Set the connection with the proxy HTTPProxyConnection.connect(self) # Use the stock HTTPConnection putrequest host = "%s:%s" % (self._host, self._port) HTTPConnection.putrequest(self, "CONNECT", host) # Add proxy-specific stuff self._add_proxy_headers() # And send the request HTTPConnection.endheaders(self) # Save the response class response_class = self.response_class # And replace the response class with our own one, which does not # close the connection after self.response_class = HTTPSProxyResponse response = HTTPConnection.getresponse(self) # Restore the response class self.response_class = response_class # Close the response object manually response.close() if response.status != 200: # Close the connection manually self.close() raise xmlrpclib.ProtocolError(host, response.status, response.reason, response.msg) self.sock.settimeout(SSL.DEFAULT_TIMEOUT) self.sock = SSL.SSLSocket(self.sock, self.trusted_certs) self.sock.init_ssl()
def __init__(self, ssl_context=None, *args, **kw): if getattr(Transport, '__init__', None) is not None: Transport.__init__(self, *args, **kw) if ssl_context is None: self.ssl_ctx = SSL.Context('sslv23') else: self.ssl_ctx = ssl_context
def __init__(self, host='', port=None, strict=None, **ssl): HTTP.__init__(self, host, port, strict) try: self.ssl_ctx = ssl['ssl_context'] except KeyError: self.ssl_ctx = SSL.Context('sslv23') assert isinstance(self._conn, HTTPSConnection) self._conn.ssl_ctx = self.ssl_ctx
def __init__(self, ssl_context=None): AbstractHTTPHandler.__init__(self) if ssl_context is not None: assert isinstance(ssl_context, SSL.Context), ssl_context self.ctx = ssl_context else: self.ctx = SSL.Context()
def __init__(self, host=None, ssl_ctx=None): """Initialise the client. If 'host' is supplied, connect to it.""" if ssl_ctx is not None: self.ssl_ctx = ssl_ctx else: self.ssl_ctx = SSL.Context(DEFAULT_PROTOCOL) FTP.__init__(self, host) self.prot = 0
def auth_tls(self): """Secure the control connection per AUTH TLS, aka AUTH TLS-C.""" self.voidcmd('AUTH TLS') s = SSL.Connection(self.ssl_ctx, self.sock) s.setup_ssl() s.set_connect_state() s.connect_ssl() self.sock = s self.file = self.sock.makefile()
def ntransfercmd(self, cmd, rest=None): """Initiate a data transfer.""" conn, size = FTP.ntransfercmd(self, cmd, rest) if self.prot: conn = SSL.Connection(self.ssl_ctx, conn) conn.setup_ssl() conn.set_connect_state() conn.set_session(self.sock.get_session()) conn.connect_ssl() return conn, size
def open_https(self, url, data=None, ssl_context=None): if ssl_context is not None and isinstance(ssl_context, SSL.Context): self.ctx = ssl_context else: self.ctx = SSL.Context(DEFAULT_PROTOCOL) user_passwd = None if type(url) is type(""): host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) realhost = host else: host, selector = url urltype, rest = splittype(selector) url = rest user_passwd = None if string.lower(urltype) != 'http': realhost = None else: realhost, rest = splithost(rest) if realhost: user_passwd, realhost = splituser(realhost) if user_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) #print "proxy via http:", host, selector if not host: raise IOError, ('http error', 'no host given') if user_passwd: import base_64 auth = string.strip(base_64.encodestring(user_passwd)) else: auth = None # Start here! h = httpslib.HTTPSConnection(host=host, ssl_context=self.ctx) #h.set_debuglevel(1) # Stop here! if data is not None: h.putrequest('POST', selector) h.putheader('Content-type', 'application/x-www-form-urlencoded') h.putheader('Content-length', '%d' % len(data)) else: h.putrequest('GET', selector) if auth: h.putheader('Authorization', 'Basic %s' % auth) for args in self.addheaders: apply(h.putheader, args) h.endheaders() if data is not None: h.send(data + '\r\n') # Here again! resp = h.getresponse() fp = resp.fp return urllib.addinfourl(fp, resp.msg, "https:" + url)
def connect(self, host, port=None): # Cribbed from httplib.HTTP. if not port: i = string.find(host, ':') if i >= 0: host, port = host[:i], host[i+1:] try: port = string.atoi(port) except string.atoi_error: raise socket.error, "nonnumeric port" if not port: port = HTTPS_PORT self.sock = SSL.Connection(self.ssl_ctx) if self.debuglevel > 0: print 'connect:', (host, port) self.sock.connect((host, port))
def connect(self): """Connect (using SSL) to the host and port specified in __init__ (through a proxy).""" import socket # Set the connection with the proxy HTTPProxyConnection.connect(self) # Use the stock HTTPConnection putrequest host = "%s:%s" % (self._host, self._port) HTTPConnection.putrequest(self, "CONNECT", host) # Add proxy-specific stuff self._add_auth_proxy_header() # And send the request HTTPConnection.endheaders(self) # Save the response class response_class = self.response_class # And replace the response class with our own one, which does not # close the connection self.response_class = HTTPSProxyResponse response = HTTPConnection.getresponse(self) # Restore the response class self.response_class = response_class # Close the response object manually response.close() if response.status != 200: # Close the connection manually self.close() # XXX Find the appropriate error code raise socket.error(1001, response.status, response.value) # NgPS: I haven't read the code recently, but I think it is # reasonable to assume that self.sock is a connected TCP socket at # this point. # Use the real stuff. ;-) if self.ssl_ctx and isinstance(self.ssl_ctx, SSL.Context): self.sock = SSL.Connection(self.ssl_ctx) self.sock.connect((self.host, self.port)) else: # Fake the socket ssl = socket.ssl(self.sock, self.key_file, self.cert_file) self.sock = FakeSocket(self.sock, ssl) if self.debuglevel > 0: print('socket type:', self.sock)
def __init__(self, host, port=None, **ssl): keys = ssl.keys() try: keys.remove('key_file') except ValueError: pass try: keys.remove('cert_file') except ValueError: pass try: keys.remove('ssl_context') except ValueError: pass if keys: raise ValueError() try: self.ssl_ctx = ssl['ssl_context'] assert isinstance(self.ssl_ctx, SSL.Context) except KeyError: self.ssl_ctx = SSL.Context('sslv23') HTTPConnection.__init__(self, host, port)
def __init__(self, host, port=None, strict=None, **ssl): self.session = None keys = ssl.keys() try: keys.remove('key_file') except ValueError: pass try: keys.remove('cert_file') except ValueError: pass try: keys.remove('ssl_context') except ValueError: pass if keys: raise ValueError('unknown keyword argument') try: self.ssl_ctx = ssl['ssl_context'] assert isinstance(self.ssl_ctx, SSL.Context), self.ssl_ctx except KeyError: self.ssl_ctx = SSL.Context('sslv23') HTTPConnection.__init__(self, host, port, strict)
def __init__(self, host='', port=None, **ssl): HTTP.__init__(self, host, port) try: self.ssl_ctx = ssl['ssl_context'] except KeyError: self.ssl_ctx = SSL.Context('sslv23')
def connect(self): self.sock = SSL.Connection(self.ssl_ctx) self.sock.connect((self.host, self.port))
def __init__(self, *args): self._ssl_conn = _ssl.Connection(*args) self._lock = _RLock()
def connect(self): self.sock = SSL.Connection(self.ssl_ctx) if self.session: self.sock.set_session(self.session) self.sock.connect((self.host, self.port))
def __init__(self, ssl_context=None): if ssl_context is None: self.ssl_ctx=SSL.Context('sslv23') else: self.ssl_ctx=ssl_context
def _start_ssl(self): """ Make this connection's socket SSL-aware. """ self.sock = SSL.Connection(self.ssl_ctx, self.sock) self.sock.setup_ssl() self.sock.set_connect_state() self.sock.connect_ssl()
sock.settimeout(SSL.DEFAULT_TIMEOUT) try: sock.connect((self.host, self.port)) except socket.error, e: sock.close() sock = None continue break if sock is None: raise socket.error( "Unable to connect to the host and port specified") self.sock = SSL.SSLSocket(sock, self.trusted_certs) self.sock.init_ssl() class HTTPSProxyResponse(HTTPResponse): def begin(self): HTTPResponse.begin(self) self.will_close = 0 class HTTPSProxyConnection(HTTPProxyConnection): default_port = HTTPSConnection.default_port def __init__(self, proxy, host,