Beispiel #1
0
    def _win_set_dns_config(self, ipv, config):
        """Configure the hosts DNS settings.

        Set the DNS configuration for the given IP version to match that which
        is given in the 'config' argument which is a dictionary of the same
        structure as the one returned by _win_get_dns_config().
        """
        commands = []
        for ifc, conf in config.items():
            if conf['source'] == u'dhcp':
                cmd = ('netsh interface {} set dns name={} '
                       'source=dhcp validate=no')
                commands.append(cmd.format(ipv, ifc))
            elif conf['source'] == u'static':
                cmd = ('netsh interface {} {} dns name={} '
                       'source=static addr={} validate=no')
                if len(conf['servers']) == 0:
                    commands.append(cmd.format(ipv, 'set', ifc, 'none'))
                else:
                    commands.append(
                        cmd.format(ipv, 'set', ifc, conf['servers'][0]))

                    cmd = ('netsh interface {} {} dns name={} '
                           'addr={} validate=no')
                    for server in conf['servers'][1:]:
                        commands.append(cmd.format(ipv, 'add', ifc, server))

        for command in commands:
            try:
                proc.run_assert_ok(command.split())
            except RuntimeError as e:
                # If the "DNS Client" service is off setting the dns will work,
                # but netsh will still quit with exit code 1
                self.log.warning('Setting DNS via netsh gave an error: %s', e)
Beispiel #2
0
 def _run_route_add(self, command):
     if platform.system() == 'Linux':
         # TODO(linus) make sure this works. Sadly we can't rely on
         # exit code or output. Maybe get a routing lib for python?
         proc.run(command)
     else:
         proc.run_assert_ok(command)
Beispiel #3
0
 def unblock_ipv6(self):
     if 'Darwin' in platform.platform():
         command = 'route delete -inet6 -net {} ::1 -reject'
         proc.run_assert_ok(command.format('0000::/1').split())
     else:
         command = 'route -6 del {} dev lo'
         for net in _IPV6_BLOCK_NETS:
             self._run_route_del(command.format(net).split())
Beispiel #4
0
 def __init__(self, pf_conf_file):
     if not os.path.exists(pf_conf_file):
         raise OSError('No pf config at {}'.format(pf_conf_file))
     proc.run_assert_ok([self.pfctl, self.pfctl_test_permission])
     self.pf_conf_file = pf_conf_file
     self.interfaces = interfaces.get_parser()
     self.allowed_ip = None
     self.block_incoming_udp_state = False
     self.block_traffic_state = False
Beispiel #5
0
 def block_ipv6(self):
     if 'Darwin' in platform.platform():
         command = 'route add -inet6 -net {} ::1 -reject'
         # Only blocks the first half of the address space which includes
         # the Global Unicast addresses
         proc.run_assert_ok(command.format('0000::/1').split())
     else:
         command = 'route -6 add {} dev lo'
         for net in _IPV6_BLOCK_NETS:
             self._run_route_add(command.format(net).split())
Beispiel #6
0
    def delete_route(self, destination, mask, gateway, interface=None):
        """Delete a route from the routing table.

        Args:
            destination (str): The routes target IP address.
            mask (str): The subnet mask for the route.
            gateway (str): The routes gateway.
            interface (Optional[int]): The interface index for the route.

        """
        command = 'route delete {} mask {} {}'.format(
            destination, mask, gateway)
        if interface:
            command += ' if {}'.format(interface)
        proc.run_assert_ok(command.split())
Beispiel #7
0
    def _win_get_dns_config(self, ipv):
        """Return the DNS configuration for the given protocol family.

        Create a dictionary for the given IP version containing the hosts
        configured DNS servers for each interface supporting that version. Each
        entry will contain the type of DNS configuration for that interface
        (dhcp or static) as well as a list of the DNS servers which the
        interface is configured to use.
        """

        interfaces = self._win_get_interfaces(ipv)

        confs = {}
        for ifc in interfaces:
            command = u'netsh interface {0} show dns name={1}'.format(ipv, ifc)
            out = proc.run_assert_ok(command.split())

            conf = {'source': u'static', 'servers': []}
            for line in out.splitlines():
                if u'DHCP' in line:
                    conf['source'] = u'dhcp'

                match = re.search(self.ip_regex[ipv], line)
                if match is not None:
                    conf['servers'].append(match.group(1))

            confs[ifc] = conf

        return confs
Beispiel #8
0
 def _osx_get_dns_servers(self, service):
     """
     Return a list of the DNS servers used by the given network service.
     """
     out = proc.run_assert_ok(['networksetup', '-getdnsservers', service])
     if 'DNS' in out:
         return ['empty']
     else:
         servers = out.splitlines()
         return [s for s in servers if 'currently disabled' not in s]
Beispiel #9
0
    def add_route(self, destination, mask, gateway, interface=None,
                  persistent=False):
        """Add a route to the routing table.

        Args:
            destination (str): The routes target IP address.
            mask (str): The subnet mask for the route.
            gateway (str): The routes gateway.
            interface (Optional[int]): The interface index for the route.
            persistent (Optional[boolean]): If the route should survive reboots

        """
        command = ['route']
        if persistent:
            command += ['-p']
        command += ['add', destination, 'mask', mask, gateway]
        if interface:
            command += ['if', str(interface)]
        proc.run_assert_ok(command)
Beispiel #10
0
    def _apply_rules_to_pf(self):
        """Compute and apply the correct pf rules."""
        if self.block_traffic_state or self.block_incoming_udp_state:
            rules = []
            for iface in self.interfaces.get_loopback_interfaces():
                rules.append(self._PASS_IFACE_TEMPLATE.format(iface))
            for iface in self.interfaces.get_tunnel_interfaces():
                rules.append(self._PASS_IFACE_TEMPLATE.format(iface))
            if self.allowed_ip is not None:
                rules.append(self._PASS_IP_TEMPLATE.format(self.allowed_ip))

            if self.block_traffic_state:
                rules.append(self._BLOCK_ALL_RULE)
            elif self.block_incoming_udp_state:
                for net in _PRIVATE_NETS:
                    rules.append(self._PASS_IN_LOCAL_UDP_TEMPLATE.format(net))
                rules.append(self._BLOCK_INCOMING_UDP_RULE)

            rules_str = '\n'.join(rules) + '\n'  # Need end \n
            proc.run_assert_ok([self.pfctl] + self.pfctl_update_mullvad_rules,
                               rules_str)
        else:
            # No block is active, clear all rules
            proc.run_assert_ok([self.pfctl] + self.pfctl_update_mullvad_rules)
Beispiel #11
0
 def _win_get_interfaces(self, ipv):
     """
     Get the index num of all interfaces supporting the given IP version.
     """
     ret = []
     command = u'netsh interface {} show interfaces'.format(ipv)
     out = proc.run_assert_ok(command.split())
     for line in out.splitlines():
         if 'isatap' not in line and 'Teredo' not in line:
             try:
                 if_idx = int(line.split()[0])
             except (IndexError, ValueError):
                 continue
             if if_idx != 1:
                 ret.append(if_idx)
     return ret
Beispiel #12
0
    def _get_ip2idx_mapping():
        """Create an IP to Idx mapping.

        Produce a mapping between IP addresses and the interface ID of the
        interface that uses those addresses.
        """
        out = proc.run_assert_ok(
            'netsh interface ipv4 show ipaddresses'.split())
        mapping = {}
        current_interface = 0
        for line in out.splitlines():
            if not line or line.startswith('-'):
                continue
            header_match = re.match(r'^.* (\d+)\s*:(.*)$', line)
            if header_match is not None:
                current_interface = int(header_match.group(1))
            else:
                ip_match = re.match(
                    r'^(\d+)\.(\d+)\.(\d+)\.(\d+)$', line.split()[-1])
                if ip_match is not None:
                    mapping[ip_match.group(0)] = current_interface
        return mapping
Beispiel #13
0
 def _setup_chain(self):
     chain = LinuxFirewall._CHAIN_NAME
     cmds = [self.iptables]
     if self.has_ipv6:
         cmds.append(self.ip6tables)
     for cmd in cmds:
         if proc.run_get_exit(cmd + ['-F', chain]) != 0:  # Flush
             proc.run_assert_ok(cmd + ['-N', chain])  # Create new
         for default_chain in ['INPUT', 'FORWARD', 'OUTPUT']:
             while proc.run_get_exit(
                     cmd + ['-D', default_chain, '-j', chain]) == 0:
                 pass
             proc.run_assert_ok(cmd + ['-I', default_chain, '-j', chain])
         default_allow_rules = [
             # Allow traffic within loopback interfaces
             '-i lo+ -j ACCEPT',
             '-o lo+ -j ACCEPT',
             # Allow traffic within VPN tunnels
             '-i tun+ -j ACCEPT',
             '-o tun+ -j ACCEPT',
         ]
         for rule in default_allow_rules:
             proc.run_assert_ok(cmd + ['-A', chain] + rule.split())
Beispiel #14
0
 def _osx_set_config(self, config):
     """Set the hosts DNS configuration to match the given configuration."""
     for service, servers in config.items():
         command = ['networksetup', '-setdnsservers', service] + servers
         proc.run_assert_ok(command)
Beispiel #15
0
 def set(self, servers):
     self.log.debug('Settings DNS servers to {}'.format(str(servers)))
     for service in osx_net_services.get_services():
         command = ['networksetup', '-setdnsservers', service]
         command += servers if len(servers) > 0 else ['empty']
         proc.run_assert_ok(command)
Beispiel #16
0
 def block_ipv6(self):
     """Add routes that blocks all IPv6 traffic."""
     command = 'route add {} ::0 if {}'
     for net in _IPV6_BLOCK_NETS:
         proc.run_assert_ok(command.format(net, _WIN_LO_INTERFACE).split())
Beispiel #17
0
 def _run_route_del(self, command):
     if platform.system() == 'Linux':
         # TODO(linus) Same as _run_route_add, better handling.
         proc.run(command)
     else:
         proc.run_assert_ok(command)
Beispiel #18
0
 def unblock_ipv6(self):
     """Remove routes blocking IPv6 traffic."""
     command = 'route delete {} ::0 if {}'
     for net in _IPV6_BLOCK_NETS:
         proc.run_assert_ok(command.format(net, _WIN_LO_INTERFACE).split())
Beispiel #19
0
 def get_interfaces(self, starts_with=None):
     if starts_with is None:
         starts_with = ''
     out = proc.run_assert_ok(self._COMMAND)
     interfaces = self._REGEX.findall(out)
     return [i for i in interfaces if i.startswith(starts_with)]
Beispiel #20
0
def _find_default_gateway():
    routing_table = proc.run_assert_ok(['netstat', '-r', '-n'])
    if 'Darwin' in platform.platform():
        return _find_default_gateway_mac(routing_table)
    else:
        return _find_default_gateway_linux(routing_table)
Beispiel #21
0
 def flush_pf_conf(self):
     """Make pf flush its rules and re-read them from the config"""
     proc.run_assert_ok([self.pfctl, self.pfctl_flush, self.pf_conf_file])
Beispiel #22
0
def get_services():
    """Return a list of the network services."""
    out = proc.run_assert_ok(['networksetup', '-listallnetworkservices'])
    services = out.splitlines()[1:]
    services = [s if not s.startswith('*') else s[1:] for s in services]
    return services
Beispiel #23
0
 def unblock_ipv6(self):
     for ns in osx_net_services.get_services():
         proc.run_assert_ok(['networksetup', '-setv6automatic', ns])
Beispiel #24
0
 def _run_iptables(self, args, skip_ipv6=False):
     proc.run_assert_ok(self.iptables + args)
     if not skip_ipv6 and self.has_ipv6:
         proc.run_assert_ok(self.ip6tables + args)
Beispiel #25
0
 def block_ipv6(self):
     self.block_ipv6_state = True
     if self.has_ipv6:
         proc.run_assert_ok(self.ip6tables + ['-A'] +
                            LinuxFirewall._BLOCK_TRAFFIC_RULE)