Beispiel #1
0
    def validForIp(self, ipStr: str) -> bool:
        """
        Checks if this transport is valid for the specified IP.

        Args:
           ip: Numeric ip address to check validity for. (xxx.xxx.xxx.xxx).

        Returns:
            True if the ip can access this Transport.

            False if the ip can't access this Transport.

            The ip check is done this way:
            * If The associated network is empty, the result is always True
            * If the associated network is not empty, and nets_positive (field) is True, the result will be True if
            the ip is contained in any subnet associated with this transport.
            * If the associated network is empty, and nets_positive (field) is False, the result will be True if
            the ip is NOT contained in ANY subnet associated with this transport.

        Raises:

        :note: Ip addresses has been only tested with IPv4 addresses
        """
        if self.networks.count() == 0:
            return True
        ip = net.ipToLong(ipStr)
        if self.nets_positive:
            return self.networks.filter(net_start__lte=ip,
                                        net_end__gte=ip).count() > 0
        return self.networks.filter(net_start__lte=ip,
                                    net_end__gte=ip).count() == 0
Beispiel #2
0
    def validForIp(self, ip):
        '''
        Checks if this transport is valid for the specified IP.

        Args:
           ip: Numeric ip address to check validity for. (xxx.xxx.xxx.xxx).

        Returns:
            True if the ip can access this Transport.

            False if the ip can't access this Transport.

            The ip check is done this way:
            * If The associated network is empty, the result is always True
            * If the associated network is not empty, and nets_positive (field) is True, the result will be True if
            the ip is contained in any subnet associated with this transport.
            * If the associated network is empty, and nets_positive (field) is False, the result will be True if
            the ip is NOT contained in ANY subnet associated with this transport.

        Raises:

        :note: Ip addresses has been only tested with IPv4 addresses
        '''
        if self.networks.count() == 0:
            return True
        ip = net.ipToLong(ip)
        if self.nets_positive:
            return self.networks.filter(net_start__lte=ip, net_end__gte=ip).count() > 0
        else:
            return self.networks.filter(net_start__lte=ip, net_end__gte=ip).count() == 0
Beispiel #3
0
    def getIp(self) -> str:
        # If single machine, ip is IP~counter,
        # If multiple and has a ';' on IP, the values is IP;MAC
        ip = self._ip.split('~')[0].split(';')[0]
        # If ip is in fact a hostname...
        if not net.ipToLong(ip):
            # Try to resolve name...
            try:
                res = dns.resolver.resolve(ip)
                ip = res[0].address
            except Exception:
                self.service().parent().doLog(
                    log.WARN, f'User service could not resolve Name {ip}.')

        return ip
Beispiel #4
0
    def wolURL(self, ip: str, mac: str) -> str:
        """Tries to get WOL server for indicated IP

        Args:
            ip (str): ip of target machine

        Returns:
            str: URL of WOL server or empty ('') if no server for the ip is found
        """
        if not self.config.value or not ip or not mac:
            return ''

        # If ip is in fact a hostname...
        if not net.ipToLong(ip):
            # Try to resolve name...
            try:
                res = dns.resolver.resolve(ip)
                ip = res[0].address
            except Exception:
                self.doLog(log.WARN, f'Name {ip} could not be resolved')
                logger.warning('Name %s could not be resolved', ip)
                return ''

        url = ''
        try:
            config = configparser.ConfigParser()
            config.read_string(self.config.value)
            for key in config['wol']:
                if net.ipInNetwork(ip, key):
                    return (config['wol'][key].replace('{MAC}', mac).replace(
                        '{IP}', ip))

        except Exception as e:
            logger.error('Error parsing advanced configuration: %s', e)

        return ''
Beispiel #5
0
 def networksFor(ip):
     """
     Returns the networks that are valid for specified ip in dotted quad (xxx.xxx.xxx.xxx)
     """
     ip = net.ipToLong(ip)
     return Network.objects.filter(net_start__lte=ip, net_end__gte=ip)
Beispiel #6
0
 def networksFor(ip: str) -> typing.Iterable['Network']:
     """
     Returns the networks that are valid for specified ip in dotted quad (xxx.xxx.xxx.xxx)
     """
     ipInt = net.ipToLong(ip)
     return Network.objects.filter(net_start__lte=ipInt, net_end__gte=ipInt)
Beispiel #7
0
 def networksFor(ip):
     '''
     Returns the networks that are valid for specified ip in dotted quad (xxx.xxx.xxx.xxx)
     '''
     ip = net.ipToLong(ip)
     return Network.objects.filter(net_start__lte=ip, net_end__gte=ip)
Beispiel #8
0
    def get(self) -> typing.MutableMapping[str, typing.Any]:
        """
        Processes get requests, currently none
        """
        logger.debug(
            'Tunnel parameters for GET: %s (%s) from %s', self._args, self._params, self._request.ip
        )

        if (
            not isTrustedSource(self._request.ip)
            or len(self._args) != 2
            or len(self._args[0]) != 48
        ):
            # Invalid requests
            raise AccessDenied()

        # Try to get ticket from DB
        try:
            user, userService, host, port, extra = models.TicketStore.get_for_tunnel(
                self._args[0]
            )
            data = {}
            if self._args[1][:4] == 'stop':
                sent, recv = self._params['sent'], self._params['recv']
                # Ensures extra exists...
                extra = extra or {}
                now = models.getSqlDatetimeAsUnix()
                totalTime = now - extra.get('b', now-1)               
                msg = f'User {user.name} stopped tunnel {extra.get("t", "")[:8]}... to {host}:{port}: u:{sent}/d:{recv}/t:{totalTime}.'
                log.doLog(user.manager, log.INFO, msg)
                log.doLog(userService, log.INFO, msg)
            else:
                if net.ipToLong(self._args[1][:32]) == 0:
                    raise Exception('Invalid from IP')
                events.addEvent(
                    userService.deployed_service,
                    events.ET_TUNNEL_ACCESS,
                    username=user.pretty_name,
                    srcip=self._args[1],
                    dstip=host,
                    uniqueid=userService.unique_id,
                )
                msg = f'User {user.name} started tunnel {self._args[0][:8]}... to {host}:{port} from {self._args[1]}.'
                log.doLog(user.manager, log.INFO, msg)
                log.doLog(userService, log.INFO, msg)
                # Generate new, notify only, ticket
                rstr = managers.cryptoManager().randomString(length=8)
                notifyTicket = models.TicketStore.create_for_tunnel(
                    userService=userService,
                    port=port,
                    host=host,
                    extra={'t': self._args[0], 'b': models.getSqlDatetimeAsUnix()},
                    validity=MAX_SESSION_LENGTH)
                data = {
                    'host': host,
                    'port': port,
                    'notify': notifyTicket
                }

            return data
        except Exception as e:
            logger.info('Ticket ignored: %s', e)
            raise AccessDenied()