Beispiel #1
0
 def delete_rule(name):
     L.info("Deleting firewall rule {}".format(name))
     cmd = [
         'netsh', 'advfirewall', 'firewall', 'delete', 'rule',
         "name={}".format(name)
     ]
     check_subprocess(cmd)
Beispiel #2
0
 def set_interface_metric(self, value=0):
     cmd = [
         windows_safe_path(
             "C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe"
         ), "Set-NetIPInterface", "-InterfaceIndex",
         self.data['InterfaceIndex'], "-InterfaceMetric",
         str(value)
     ]
     check_subprocess(cmd)
     self.data['IPConnectionMetric'] = str(value)
Beispiel #3
0
 def disable(self):
     if not self.enabled():
         return
     try:
         check_subprocess([
             'netsh', 'interface', 'set', 'interface',
             self.net_connection_id(), 'disabled'
         ])
         self.data['NetEnabled'] = 'FALSE'
     except XVProcessException as ex:
         raise XVEx("Failed to disable interface {}: {}".format(
             self.net_connection_id(), ex))
Beispiel #4
0
    def pingable(self):
        if not self.enabled():
            L.verbose("{} not enabled".format(self.name()))
            return False
        ips = self.ip_addresses()
        if not ips:
            L.verbose("{} has no IP address".format(self.name()))
            return False
        cmd = ['ping', '-n', '1', '-w', '2', '-S', ips[0].exploded, '8.8.8.8']
        try:
            output = check_subprocess(cmd)[0]
            if 'Received = 1' in output:
                return True
            else:
                # Consider this a real error and propagate. It's likely a code issue.
                raise XVEx(
                    "Don't know how to parse ping output: {}".format(output))
        except XVProcessException as ex:
            if 'Lost = 1' in ex.stderr:
                L.debug("Couldn't ping on adapter {}".format(self))
                return False
            L.warning("Ping failed unexpectedly with error '{}'. "
                      "Assuming adapter {} un-pingable.".format(
                          ex.stderr, self))

            return False
Beispiel #5
0
def wmic_rows():
    rows = []
    nic_rows = parse_wmic_output(check_subprocess(['wmic', 'nic'])[0])
    nicconfig_rows = parse_wmic_output(
        check_subprocess(['wmic', 'nicconfig'])[0])
    # We're effectively performing a join on SettingID and GUID here.
    for nic_row in nic_rows:
        if nic_row['GUID'] == "":
            L.verbose("Network adapter '{}' has no GUID. Ignoring it!".format(
                nic_row['Name']))
            continue
        for nicconfig_row in nicconfig_rows:
            if nicconfig_row['SettingID'] == nic_row['GUID']:
                rows.append(merge_two_dicts(nic_row, nicconfig_row))
                break
    return rows
Beispiel #6
0
 def describe_rule(name):
     # TODO: Probably don't need this
     out = check_subprocess([
         'netsh', 'advfirewall', 'firewall', 'show', 'rule',
         "name={}".format(name)
     ])[0]
     return out.splitlines()
 def _ns_dns_servers(self):
     dns_servers = check_subprocess(
         ['networksetup', '-getdnsservers', self._name])
     dns_servers = dns_servers[0].strip().split('\n')
     if "There aren't any DNS Servers set on" in dns_servers[0]:
         return []
     return [ipaddress.ip_address(ip) for ip in dns_servers]
Beispiel #8
0
 def _git_branch():
     '''Return the git branch we're currently on. This is designed to run on the test
     orchestration device, i.e. localhost. We use it to ensure that all devices are checked out
     to the same revision'''
     # TODO: Consider making this configurable as well, with the default being this.
     return check_subprocess(['git', 'rev-parse', '--abbrev-ref',
                              'HEAD'])[0].strip()
    def dns_servers_in_priority_order():
        lines = check_subprocess(['scutil', '--dns'])[0].splitlines()
        istart = None
        for iline in range(0, len(lines)):
            if 'DNS configuration (for scoped queries)' in lines[iline]:
                istart = iline + 1
                break

        return list(set(_SCUtil._parse_resolvers(lines[istart:])))
Beispiel #10
0
    def create_rule(action, **kwargs):
        rule_name = WindowsAdvFirewall._generate_rule_name()
        cmd = [
            'netsh',
            'advfirewall',
            'firewall',
            'add',
            'rule',
            "name={}".format(rule_name),
            "action={}".format(action),
            "profile=any",
            "interfacetype=any",
        ]

        for key, value in list(kwargs.items()):
            cmd.append("{}={}".format(key, value))

        L.debug("Creating firewall rule with command {}".format(cmd))
        check_subprocess(cmd)
        return rule_name
 def _getinfo(self):
     cmd = ['networksetup', '-getinfo', self._name]
     lines = check_subprocess(cmd)[0].splitlines()
     L.verbose("{} returned:\n{}".format(' '.join(cmd), lines))
     info = {}
     for line in lines:
         match = NetworkService.PROG_INFO_LINE.match(line)
         if not match:
             continue
         info[match.group(1).strip()] = match.group(2).strip()
     return info
Beispiel #12
0
 def set_dns_servers(self, *ips):
     if len(ips) > 2:
         raise XVEx("There is only space for two DNS servers per adapter")
     cmd_set = [
         'netsh', 'interface', 'ip', 'set', 'dns',
         self.net_connection_id()
     ]
     if not ips:
         cmd_set.append('dhcp')
         L.debug("Setting DNS on {} via DHCP".format(
             self.net_connection_id()))
         check_subprocess(cmd_set)
     else:
         # TODO: this breaks if we set a server that's already set. Not sure
         # if that's a problem.
         L.debug("Setting primary DNS on {} to {}".format(
             self.net_connection_id(), ips[0]))
         check_subprocess(cmd_set + ['static', ips[0], 'index=1'])
         if len(ips) == 2:
             cmd_add = [
                 'netsh', 'interface', 'ip', 'add', 'dns',
                 self.net_connection_id()
             ]
             L.debug("Setting secondary DNS on {} to {}".format(
                 self.net_connection_id(), ips[1]))
             check_subprocess(cmd_add + [ips[1], 'index=2'])
Beispiel #13
0
    def adapters():
        adapters = []
        # This is an optimization. Calling windump is slow. So we do it once to save waiting for
        # each adapter to do it.
        windump_lines = check_subprocess(['windump', '-D'])[0].splitlines()
        for row in wmic_rows():
            if row['PhysicalAdapter'] == "FALSE":
                continue
            row['windump_index'] = WindowsNetwork._windump_index(
                row['GUID'], windump_lines)
            adapters.append(WindowsAdapter(row))

        return adapters
Beispiel #14
0
    def list_xv_rules():
        rules = []
        stdout = check_subprocess(
            ['netsh', 'advfirewall', 'firewall', 'show', 'rule',
             'name=all'])[0]

        for line in stdout.splitlines():
            matches = WindowsAdvFirewall.PROG_RULE_NAME.match(line)
            if not matches:
                continue
            name = matches.group(1)
            if WindowsAdvFirewall.RULE_PREFIX not in name:
                continue
            rules.append(name)

        return rules
    def wifi_has_power(self):
        self._ensure_service_is_wifi()

        # TODO: Find a programmatic way of doing this. The data is definitely in
        # /Library/Preferences/SystemConfiguration/preferences.plist
        # but all the Airport keys are deprecated:
        # https://developer.apple.com/documentation/systemconfiguration/scschemadefinitions/airport_dictionary_keys?language=objc
        cmd = ['networksetup', '-getairportpower', self.interface()]
        try:
            output = check_subprocess(cmd)[0]
            if ": Off" in output[0]:
                return False
            elif ": On" in output[0]:
                return True
            else:
                raise XVEx(
                    "Don't know how to parse '{}'' from 'networksetup -getairportpower'"
                    .format(output[0]))
        except:
            raise XVEx(
                "Can't get Wi-Fi power status for network service '{}' as it is not a Wi-Fi "
                "service.".format(self))
    def pingable(self):
        if not self.active():
            return False
        cmd = ['ping', '-c1', '-W1', '8.8.8.8', '-b', self.interface()]
        output = ""
        try:
            output = check_subprocess(cmd)[0]
            if '1 packets received' in output:
                return True
            else:
                # Consider this a real error and propagate. It's likely a code issue.
                raise XVEx(
                    "Don't know how to parse ping output: {}".format(output))
        except XVProcessException as ex:
            if 'No route to host' in ex.stderr:
                L.debug("Ping failed due to 'No route to host'")
                return False
            if '0 packets received' in ex.stderr:
                L.debug("Ping failed due to '0 packets received'")
                return False
            L.warning("Ping failed unexpectedly with error '{}'. "
                      "Assuming interface un-pingable.".format(ex.stderr))

            return False
 def enable(self):
     L.debug("Enabling connection {}".format(self.name()))
     check_subprocess(['nmcli', 'connection', 'up', self.name()])
Beispiel #18
0
 def _get_vm_ip(vmx_path):
     cmd = [VMWareDeviceDiscoverer._vmrun_path(), 'getGuestIPAddress', vmx_path]
     return check_subprocess(cmd)[0].strip()
 def _set_wifi_power(self, on_or_off):
     self._ensure_service_is_wifi()
     # TODO: Find a programmatic way of doing this.
     check_subprocess(
         ['networksetup', '-setairportpower',
          self.interface(), on_or_off])
 def enable_interface(self):
     check_subprocess(['ifconfig', self.interface(), 'up'])
Beispiel #21
0
 def _pfctl(cmd):
     if not is_root_user():
         raise XVEx("root required to manipulate pf firewall rules")
     cmd = ['pfctl'] + cmd
     L.debug("Executing pfctl command: {}".format(" ".join(cmd)))
     return check_subprocess(cmd)
 def disable_ipv6(self):
     # TODO: Try to find a programmatic way of doing this
     check_subprocess(['networksetup', '-setv6off', self.name()])
Beispiel #23
0
 def _revert_vm_to_snapshot(vmx_path, snapshot):
     cmd = [VMWareDeviceDiscoverer._vmrun_path(), 'revertToSnapshot', vmx_path, snapshot]
     check_subprocess(cmd)
Beispiel #24
0
 def allow_all_outbound_traffic():
     L.info('Allowing all outbound traffic')
     check_subprocess([
         'netsh', 'advfirewall', 'set', 'allprofiles', 'firewallpolicy',
         'blockinbound,allowoutbound'
     ])
 def disable(self):
     L.debug("Disabling connection {}".format(self.name()))
     check_subprocess(['nmcli', 'connection', 'down', self.name()])
 def set_dns_servers(self, ips):
     ips = ip_addresses_to_strings(ips)
     L.info('Setting DNS servers for {} to {}'.format(self._name, ips))
     check_subprocess(['networksetup', '-setdnsservers', self._name] + ips)
 def disable_interface(self):
     L.debug("Disabling interface {}".format(self.interface()))
     # TODO: Move to unix tools or use "ip link set dev iface up"?
     check_subprocess(['ifconfig', self.interface(), 'down'])
 def disable_interface(self):
     check_subprocess(['ifconfig', self.interface(), 'down'])
Beispiel #29
0
 def _vm_state(vmx_path):
     cmd = [VMWareDeviceDiscoverer._vmrun_path(), 'checkToolsState', vmx_path]
     return check_subprocess(cmd)[0].strip()
Beispiel #30
0
 def set_rule_enable(name, enabled):
     enable = 'yes' if enabled else 'no'
     check_subprocess([
         'netsh', 'advfirewall', 'firewall', 'set', 'rule',
         "name={}".format(name), 'new', "enable={}".format(enable)
     ])