def __call__(self, context, event, *args, **kwargs):
        ip = IPAddress(
            self.evaluate(self.Value, context, event, *args, **kwargs))

        if self.Format == "ipv6":
            return str(ip.ipv6())
        elif self.Format == "ipv4":
            return str(ip.ipv4())
        else:  # auto
            if (0xffff00000000 & ip.ipv6().value) == 0xffff00000000:
                return str(ip.ipv4())
            else:
                return str(ip.ipv6())
    def validate_ip(self, request, remote_ip):
        # When we aren't configured to restrict on IP address
        if not getattr(settings, 'RESTRICTEDSESSIONS_RESTRICT_IP', True):
            return True
        # When the IP address key hasn't yet been set on the request session
        if SESSION_IP_KEY not in request.session:
            return True
        # When there is no remote IP, check if one has been set on the session
        session_ip = request.session[SESSION_IP_KEY]
        if not remote_ip:
            if session_ip:  # session has remote IP value so validate :-(
                return False
            else:  # Session doesn't have remote IP value so possibly :-)
                return True

        # Compute fuzzy IP compare based on settings on compare sensitivity
        session_network = IPNetwork(session_ip)
        remote_ip = IPAddress(remote_ip)
        try:
            session_network = session_network.ipv4()
            remote_ip = remote_ip.ipv4()
            session_network.prefixlen = getattr(
                settings, 'RESTRICTEDSESSIONS_IPV4_LENGTH', 32)
        except AddrConversionError:
            try:
                session_network.prefixlen = getattr(
                    settings, 'RESTRICTEDSESSIONS_IPV6_LENGTH', 64)
            except AddrFormatError:
                # session_network must be IPv4, but remote_ip is IPv6
                return False
        return remote_ip in session_network
Example #3
0
    def _genRegionIps(
        self, connections, bracket_ipv6=False, include_name=False
    ):
        """Generate IP addresses for all region controllers this rack
        controller is connected to."""

        def _getNameFromEventloop(eventloop):
            if ":" in eventloop:
                return eventloop.split(":", 1)[0]
            else:
                return eventloop

        # Filter the connects by region.
        conn_per_region = defaultdict(set)
        for eventloop, connection in connections.items():
            conn_per_region[eventloop.split(":")[0]].add(connection)
        for eventloop, connections in conn_per_region.items():
            # Sort the connections so the same IP is always picked per
            # region controller. This ensures that the HTTP configuration
            # is not reloaded unless its actually required to reload.
            conn = list(sorted(connections, key=lambda conn: conn.address[0]))[
                0
            ]
            addr = IPAddress(conn.address[0])
            if addr.is_ipv4_mapped():
                addr = str(addr.ipv4())
            elif addr.version == 6 and bracket_ipv6:
                addr = "[%s]" % addr
            else:
                addr = str(addr)
            if include_name:
                yield (_getNameFromEventloop(eventloop), addr)
            else:
                yield addr
Example #4
0
    def same_ip(cls, orig_remote_ip, remote_ip):
        # Check is disabled -- always return true
        if not getattr(settings, 'RESTRICTEDSESSIONS_RESTRICT_IP', True):
            return True

        # No original IP or current IP is unknown
        if not orig_remote_ip or not remote_ip:
            return True

        session_network = IPNetwork(orig_remote_ip)
        remote_ip = IPAddress(remote_ip)
        try:
            session_network = session_network.ipv4()
            remote_ip = remote_ip.ipv4()
            session_network.prefixlen = getattr(
                settings, 'RESTRICTEDSESSIONS_IPV4_LENGTH', 32)
        except AddrConversionError:
            try:
                session_network.prefixlen = getattr(
                    settings, 'RESTRICTEDSESSIONS_IPV6_LENGTH', 64)
            except AddrFormatError:
                # session_network must be IPv4, but remote_ip is IPv6
                return False

        # IP belongs to the same network
        return remote_ip in session_network
    def validate_ip(self, request, remote_ip):
        # When we aren't configured to restrict on IP address
        if not getattr(settings, 'RESTRICTEDSESSIONS_RESTRICT_IP', True):
            return True
        # When the IP address key hasn't yet been set on the request session
        if SESSION_IP_KEY not in request.session:
            return True
        # When there is no remote IP, check if one has been set on the session
        session_ip = request.session[SESSION_IP_KEY]
        if not remote_ip:
            if session_ip:  # session has remote IP value so validate :-(
                return False
            else:  # Session doesn't have remote IP value so possibly :-)
                return True

        # Compute fuzzy IP compare based on settings on compare sensitivity
        session_network = IPNetwork(session_ip)
        remote_ip = IPAddress(remote_ip)
        try:
            session_network = session_network.ipv4()
            remote_ip = remote_ip.ipv4()
            session_network.prefixlen = getattr(settings, 'RESTRICTEDSESSIONS_IPV4_LENGTH', 32)
        except AddrConversionError:
            try:
                session_network.prefixlen = getattr(settings, 'RESTRICTEDSESSIONS_IPV6_LENGTH', 64)
            except AddrFormatError:
                # session_network must be IPv4, but remote_ip is IPv6
                return False
        return remote_ip in session_network
Example #6
0
    def _normalize_ip_address(addr):
        """
        When we used mapped ipv4 (starting with ::FFFF/96) we need to
        normalize it to ipv4 in order to compare it with value used
        in commonName in the certificate.
        """
        ip = IPAddress(addr)
        if ip.is_ipv4_mapped():
            addr = str(ip.ipv4())

        return addr
Example #7
0
 def normaliseAddress(address):
     """Normalise an IP address."""
     try:
         address = IPAddress(address)
     except AddrFormatError:
         return address  # Hostname?
     else:
         if address.is_ipv4_mapped():
             return address.ipv4()
         else:
             return address
Example #8
0
    def _normalize_ip_address(addr):
        """
        When we used mapped ipv4 (starting with ::FFFF/96) we need to
        normalize it to ipv4 in order to compare it with value used
        in commonName in the certificate.
        """
        ip = IPAddress(addr)
        if ip.is_ipv4_mapped():
            addr = str(ip.ipv4())

        return addr
Example #9
0
def normalize_mapped_address(ipaddr):
    """
    Converts a IPv4-mapped IPv6 address into a IPv4 address. Handles both the
    ::ffff:192.0.2.128 format as well as the deprecated ::192.0.2.128 format.

    :param ipaddr: IP address [str]
    :return: normalized IP address [str]
    """
    ipaddr = IPAddress(ipaddr)
    if ipaddr.is_ipv4_compat() or ipaddr.is_ipv4_mapped():
        ipaddr = ipaddr.ipv4()
    return str(ipaddr)
Example #10
0
    def get_best_subnet_for_ip(self, ip):
        """Find the most-specific managed Subnet the specified IP address
        belongs to."""
        ip = IPAddress(ip)
        if ip.is_ipv4_mapped():
            ip = ip.ipv4()
        subnets = self.raw(self.find_best_subnet_for_ip_query,
                           params=[str(ip)])

        for subnet in subnets:
            return subnet  # This is stable because the query is ordered.
        else:
            return None
    def validate_ip(self, request, remote_ip):
        if not getattr(settings, 'RESTRICTEDSESSIONS_RESTRICT_IP', True) or not SESSION_IP_KEY in request.session:
            return True

        session_network = IPNetwork(request.session[SESSION_IP_KEY])
        remote_ip = IPAddress(remote_ip)
        try:
            session_network = session_network.ipv4()
            remote_ip = remote_ip.ipv4()
            session_network.prefixlen = getattr(settings, 'RESTRICTEDSESSIONS_IPV4_LENGTH', 32)
        except AddrConversionError:
            session_network.prefixlen = getattr(settings, 'RESTRICTEDSESSIONS_IPV6_LENGTH', 64)
        return remote_ip in session_network
Example #12
0
def normalise_address(address):
    """Normalise an IP address into a form suitable for the `ntp` daemon.

    It seems to prefer non-mapped IPv4 addresses, for example. Hostnames are
    passed through.
    """
    try:
        address = IPAddress(address)
    except AddrFormatError:
        return address  # Hostname.
    else:
        if address.is_ipv4_mapped():
            return address.ipv4()
        else:
            return address
Example #13
0
def is_loopback_address(hostname):
    """Determine if the given hostname appears to be a loopback address.

    :param hostname: either a hostname or an IP address.  No resolution is
        done, but 'localhost' is considered to be loopback.
    :type hostname: str

    :return: True if the address is a loopback address.
    """

    try:
        ip = IPAddress(hostname)
    except AddrFormatError:
        return hostname.lower() in {"localhost", "localhost."}
    return ip.is_loopback() or (ip.is_ipv4_mapped()
                                and ip.ipv4().is_loopback())
    def validate_ip(self, request, remote_ip):
        if not getattr(settings, 'RESTRICTEDSESSIONS_RESTRICT_IP', True) or not SESSION_IP_KEY in request.session:
            return True

        session_network = IPNetwork(request.session[SESSION_IP_KEY])
        remote_ip = IPAddress(remote_ip)
        try:
            session_network = session_network.ipv4()
            remote_ip = remote_ip.ipv4()
            session_network.prefixlen = IPV4_LENGTH
        except AddrConversionError:
            try:
                session_network.prefixlen = IPV6_LENGTH
            except AddrFormatError:
                # session_network must be IPv4, but remote_ip is IPv6
                return False
        return remote_ip in session_network
Example #15
0
File: dns.py Project: zeronewb/maas
 def _genRegionIps(self):
     """Generate IP addresses for all region controllers this rack
     controller is connected to."""
     # Filter the connects by region.
     conn_per_region = defaultdict(set)
     for eventloop, connection in self._rpc_service.connections.items():
         conn_per_region[eventloop.split(':')[0]].add(connection)
     for _, connections in conn_per_region.items():
         # Sort the connections so the same IP is always picked per
         # region controller. This ensures that the HTTP configuration
         # is not reloaded unless its actually required to reload.
         conn = list(sorted(
             connections, key=lambda conn: conn.address[0]))[0]
         addr = IPAddress(conn.address[0])
         if addr.is_ipv4_mapped():
             yield str(addr.ipv4())
         else:
             yield str(addr)
    def validate_ip(self, request, remote_ip):
        if not getattr(settings, 'RESTRICTEDSESSIONS_RESTRICT_IP',
                       True) or not SESSION_IP_KEY in request.session:
            return True

        session_network = IPNetwork(request.session[SESSION_IP_KEY])
        remote_ip = IPAddress(remote_ip)
        try:
            session_network = session_network.ipv4()
            remote_ip = remote_ip.ipv4()
            session_network.prefixlen = getattr(
                settings, 'RESTRICTEDSESSIONS_IPV4_LENGTH', 32)
        except AddrConversionError:
            try:
                session_network.prefixlen = getattr(
                    settings, 'RESTRICTEDSESSIONS_IPV6_LENGTH', 64)
            except AddrFormatError:
                # session_network must be IPv4, but remote_ip is IPv6
                return False
        return remote_ip in session_network
    def same_ip(cls, orig_remote_ip, remote_ip):
        # Check is disabled -- always return true
        if not getattr(settings, 'RESTRICTEDSESSIONS_RESTRICT_IP', True):
            return True

        # No original IP or current IP is unknown
        if not orig_remote_ip or not remote_ip:
            return True

        session_network = IPNetwork(orig_remote_ip)
        remote_ip = IPAddress(remote_ip)
        try:
            session_network = session_network.ipv4()
            remote_ip = remote_ip.ipv4()
            session_network.prefixlen = getattr(settings, 'RESTRICTEDSESSIONS_IPV4_LENGTH', 32)
        except AddrConversionError:
            try:
                session_network.prefixlen = getattr(settings, 'RESTRICTEDSESSIONS_IPV6_LENGTH', 64)
            except AddrFormatError:
                # session_network must be IPv4, but remote_ip is IPv6
                return False

        # IP belongs to the same network
        return remote_ip in session_network
Example #18
0
def proxy_get_login_info():

    global pwd_mgr
    global proxy_ip

    try:

        print '\n{:-<79}'.format('-')
        print '         **** Categorization script for Blue Coat proxies. ****\n\n' + \
              'WARNING: In order to use this script sucessfuly you have to have access to a\n' + \
              'Blue Coat proxy licensed for web filtering.\n\n' + \
              'The script will categorize URLs against all enabled categorization providers.\n\n' + \
              '1. Single URL categorization:\n' + \
              'Show categorization for given URL.\n\n' + \
              '2. URL file categorization:\n' + \
              'Show categorization for each URL inside the provided URL file. URLs in file \n' + \
              'must be one per line. \n\n' + \
              '3. URL crawl and categorize: \n' + \
              'Show categorization for given URL and related categories from URLs contained \n' + \
              'in given URL.'


        print '{:-<79}'.format('-'), '\n'

        ''' Grab login information.
        '''

        raw_pip = IPAddress(raw_input('Proxy ip address: '.ljust(25)))
        dev_ip = str(raw_pip)

        try:
            _ip = re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',dev_ip).group(0))

        except:
            raise ValueError('[-] Err: Enter ip address in the format X.X.X.X. Try again!.')

        if _ip[0] == '0' or _ip[0] == '255':
            raise ValueError('[-] Err: {0} : Enter a valid ip address.'.format(dev_ip))

        proxy_ip = str(raw_pip.ipv4())

        proxy_u  = raw_input('Proxy user name: '.ljust(25))

        if len(proxy_u) == 0:
            raise ValueError('[-] Err: user name can not be blank. Try again!.')

        proxy_p  = getpass.getpass('User password (hiden): '.ljust(25))

        if len(proxy_p) == 0:
            raise ValueError('[-] Err: password can not be blank. Try again!.')

        ''' Create a db to user/password mapping. It will be used in auth
            requests. The 'uri' part of .add_password is composed by blue
            coat proxy ip addr and mgmt port 8082.
        '''
        pwd_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

        ''' Adding URL, username and password to password manager.
        '''

        pwd_mgr.add_password(None, proxy_ip + ':8082', proxy_u, proxy_p)

    except ValueError, Err:
        print '\n', Err
        exit()