Exemple #1
0
def test_is_ipaddress_false(addr):
    assert not ssl_.is_ipaddress(addr)
Exemple #2
0
def test_is_ipaddress_true(addr):
    assert ssl_.is_ipaddress(addr)
Exemple #3
0
 def test_is_ipaddress_false(self, addr):
     assert not ssl_.is_ipaddress(addr)
Exemple #4
0
 def test_is_ipaddress_true(self, addr):
     assert ssl_.is_ipaddress(addr)
Exemple #5
0
 def test_is_ipaddress_false(self, addr: Union[bytes, str]) -> None:
     assert not ssl_.is_ipaddress(addr)
Exemple #6
0
    def __init__(self,
                 hostname,
                 username=None,
                 password=None,
                 authinfo=None,
                 protocol=None,
                 port=None,
                 verify_ssl=None):
        super(Session, self).__init__()

        # Determine whether or not server SSL certificates should be verified.
        if verify_ssl is None:
            verify_ssl = os.environ.get('SSLREQCERT', 'yes')
            verify_ssl = str(verify_ssl).lower() not in ('no', 'false')

        self._id = uuid4().hex
        self.message_log = logger.getChild('session.%s' % self._id)

        # If certificate path has already been set for SWAT package, make
        # Requests module reuse it.
        for k in ['SSLCALISTLOC', 'CAS_CLIENT_SSL_CA_LIST']:
            if k in os.environ:
                os.environ['REQUESTS_CA_BUNDLE'] = os.environ[k]
                break

        # If certificate path hasn't been specified in either environment
        # variable, replace the default adapter with one that will use the
        # machine's default SSL _settings.
        if 'REQUESTS_CA_BUNDLE' not in os.environ:
            if verify_ssl:
                # Skip hostname verification if IP address specified instead
                # of DNS name.  Prevents error from urllib3.
                try:
                    from urllib3.util.ssl_ import is_ipaddress
                except ImportError:
                    # is_ipaddres not present in older versions of urllib3
                    def is_ipaddress(hst):
                        return re.match(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$",
                                        hst)

                verify_hostname = not is_ipaddress(hostname)
                adapter = SSLContextAdapter(assert_hostname=verify_hostname)

                self.mount('https://', adapter)

            else:
                # Every request will generate an InsecureRequestWarning
                from urllib3.exceptions import InsecureRequestWarning
                warnings.simplefilter('default', InsecureRequestWarning)

        self.filters = DEFAULT_FILTERS

        # Used for context manager
        self._old_session = None

        # Reuse an existing CAS connection if possible
        if swat and isinstance(hostname, swat.CAS):
            if isinstance(hostname._sw_connection,
                          swat.cas.rest.connection.REST_CASConnection):
                import base64

                # Use the httpAddress action to retieve information about
                # REST endpoints
                httpAddress = hostname.get_action('builtins.httpAddress')
                address = httpAddress()
                domain = address.virtualHost
                # httpAddress action may return virtualHost = ''
                # if this happens, try the CAS host
                if not domain:
                    domain = hostname._sw_connection._current_hostname
                protocol = address.protocol
                port = address.port
                auth = hostname._sw_connection._auth.decode('utf-8').replace(
                    'Basic ', '')
                username, password = base64.b64decode(auth).decode(
                    'utf-8').split(':')
            else:
                raise ValueError("A 'swat.CAS' session can only be reused "
                                 "when it's connected via the REST APIs.")
        else:
            url = urlsplit(hostname)

            # Extract http/https from domain name if present and protocl not
            # explicitly given
            protocol = protocol or url.scheme

            domain = url.hostname or str(hostname)

        self._settings = {
            'protocol': protocol or 'https',
            'domain': domain,
            'port': port,
            'username': username,
            'password': password
        }

        if self._settings['password'] is None:
            # Try to get credentials from .authinfo or .netrc files.
            # If no file path was specified, the default locations will
            # be checked.
            if 'swat' in sys.modules:
                auth = swat.utils.authinfo.query_authinfo(domain,
                                                          user=username,
                                                          path=authinfo)
                self._settings['username'] = auth.get('user')
                self._settings['password'] = auth.get('password')

            # Not able to load credentials using SWAT.  Try Netrc.
            # TODO: IF a username was specified, verify that the credentials
            #       found are for that username.
            if self._settings['password'] is None:
                try:
                    parser = netrc.netrc(authinfo)
                    values = parser.authenticators(domain)
                    if values:
                        self._settings['username'], \
                        _, \
                        self._settings['password'] = values
                except (OSError, IOError):
                    pass  # netrc throws if $HOME is not set

        self.verify = verify_ssl
        self.auth = HTTPBearerAuth(self.get_token())

        if current_session() is None:
            current_session(self)