Пример #1
0
    def _run_worker_thread(self):
        """Runs the worker thread that waits for network events."""
        from Foundation import (
            CFRunLoopAddSource,
            CFRunLoopGetCurrent,
            kCFRunLoopCommonModes,
            CFRunLoopRun,
        )
        from SystemConfiguration import (
            SCDynamicStoreCreate,
            SCDynamicStoreSetNotificationKeys,
            SCDynamicStoreCreateRunLoopSource,
        )

        store = SCDynamicStoreCreate(None, "global-network-watcher",
                                     self._on_network_changed, None)
        SCDynamicStoreSetNotificationKeys(
            store, None,
            ["State:/Network/Global/IPv4", "State:/Network/Global/IPv6"])

        CFRunLoopAddSource(
            CFRunLoopGetCurrent(),
            SCDynamicStoreCreateRunLoopSource(None, store, 0),
            kCFRunLoopCommonModes,
        )

        CFRunLoopRun()
Пример #2
0
def AddKnownEvents():
    """Here we add all the events that we know of to the dictionary"""

    # Add a bunch of dynamic events
    store = SCDynamicStoreCreate(None, "generate_event_plist", None, None)
    AddCategoryOfEvents(u"SystemConfiguration",
                        SCDynamicStoreCopyKeyList(store, ".*"))

    # Add some standard NSWorkspace events
    AddCategoryOfEvents(
        u"NSWorkspace", u'''
        NSWorkspaceDidLaunchApplicationNotification
        NSWorkspaceDidMountNotification
        NSWorkspaceDidPerformFileOperationNotification
        NSWorkspaceDidTerminateApplicationNotification
        NSWorkspaceDidUnmountNotification
        NSWorkspaceDidWakeNotification
        NSWorkspaceSessionDidBecomeActiveNotification
        NSWorkspaceSessionDidResignActiveNotification
        NSWorkspaceWillLaunchApplicationNotification
        NSWorkspaceWillPowerOffNotification
        NSWorkspaceWillSleepNotification
        NSWorkspaceWillUnmountNotification
                        '''.split())

    AddCategoryOfEvents(u'NSDistributed', (
        u'com.apple.iTunes.playerInfo',
        u'net.frozensilicon.pandoraBoy.playerInfo',
    ))

    AddCategoryOfEvents(u'FSEvents', (u'/tmp/', ))

    AddCategoryOfEvents(u'NSNetService', (u'_ssh._tcp.', ))
Пример #3
0
def fact():
    '''Returns the cidr of the current vlan'''

    result = 'None'

    net_config = SCDynamicStoreCreate(None, 'net', None, None)
    ip, primary_interface, netmask = '', '', ''

    primary_interface = get_iface(net_config)

    if primary_interface:
        ip = ip_address(primary_interface, net_config)

    if ip:
        try:
            proc = subprocess.Popen(['/sbin/ifconfig', primary_interface],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            stdout, _ = proc.communicate()
        except (IOError, OSError):
            stdout = None

        if stdout:
            for line in stdout.splitlines():
                if ip in line:
                    netmask = line.split(' ')[3].lower()
            count = int(0)
            count += int(netmask.count('f')) * 4
            count += int(netmask.count('e')) * 3
            count += int(netmask.count('c')) * 2
            count += int(netmask.count('8')) * 1

            result = '%s.%s/%s' % ('.'.join(ip.split('.')[0:3]), '0', count)

    return {factoid: result}
Пример #4
0
def get_domain_dns():
    net_config = SCDynamicStoreCreate(None, 'active-directory', None, None)
    ad_info = SCDynamicStoreCopyValue(
        net_config, 'com.apple.opendirectoryd.ActiveDirectory')
    if ad_info is not None:
        return ad_info.get('DomainNameDns')
    else:
        raise NotBound
Пример #5
0
def fact():
    """Returns the value of the hostname of this Mac"""
    result = "None"

    net_config = SCDynamicStoreCreate(None, "net", None, None)
    sys_info = SCDynamicStoreCopyValue(net_config, "Setup:/System")
    result = sys_info["HostName"]

    return {factoid: result}
Пример #6
0
def searchnodes():
    if not bound():
        raise NotBound
    net_config = SCDynamicStoreCreate(None, 'directory-nodes', None, None)
    nodes = SCDynamicStoreCopyValue(net_config, 'com.apple.opendirectoryd.node:/Search')
    if nodes:
        return list(nodes)
    else:
        return None
Пример #7
0
    def applicationDidFinishLaunching_(self, notification):
        # load icon files
        self.active_image = NSImage.imageNamed_("active")
        self.inactive_image = NSImage.imageNamed_("inactive")

        # make status bar item
        self.statusitem = NSStatusBar.systemStatusBar().statusItemWithLength_(
            NSVariableStatusItemLength)
        self.statusitem.retain()
        self.statusitem.setHighlightMode_(False)
        self.statusitem.setEnabled_(True)

        # insert a menu into the status bar item
        self.menu = NSMenu.alloc().init()
        self.statusitem.setMenu_(self.menu)

        # open connection to the dynamic (configuration) store
        self.store = SCDynamicStoreCreate(None, "name.klep.toggleproxy",
                                          self.dynamicStoreCallback, None)

        proxyRef = SCNetworkServiceCopyProtocol(self.service,
                                                kSCNetworkProtocolTypeProxies)
        prefDict = SCNetworkProtocolGetConfiguration(proxyRef)

        hasProxies = False

        # For each of the proxies we are concerned with, check to see if any
        # are configured. If so (even if not enabled), create a menuitem for
        # that proxy type.

        for proxy in self.proxies.values():
            enabled = CFDictionaryGetValue(prefDict, proxy['pref'])
            if enabled is not None:
                proxy[
                    'menuitem'] = self.menu.addItemWithTitle_action_keyEquivalent_(
                        proxy['title'], proxy['action'],
                        proxy['keyEquivalent'])
                hasProxies = True
            else:
                proxy['menuitem'] = None

        if hasProxies:
            self.menu.addItem_(NSMenuItem.separatorItem())
            self.enableallmi = self.menu.addItemWithTitle_action_keyEquivalent_(
                'Enable All', 'enableall', '')
            self.disableallmi = self.menu.addItemWithTitle_action_keyEquivalent_(
                'Disable All', 'disableall', '')
            self.menu.addItem_(NSMenuItem.separatorItem())

        # Need a way to quit
        self.menu.addItemWithTitle_action_keyEquivalent_(
            "Quit", "quitApp:", "")

        # Start working
        # self.loadNetworkServices()
        self.watchForProxyChanges()
        self.updateProxyStatus()
Пример #8
0
def fact():
    '''Returns the ComputerName'''
    result = 'None'

    net_config = SCDynamicStoreCreate(None, "net", None, None)
    sys_info = SCDynamicStoreCopyValue(net_config, "Setup:/System")
    result = sys_info['ComputerName']

    return {factoid: result}
Пример #9
0
def fact():
    """Returns the ComputerName"""
    result = "None"

    net_config = SCDynamicStoreCreate(None, "net", None, None)
    sys_info = SCDynamicStoreCopyValue(net_config, "Setup:/System")
    result = sys_info["ComputerName"]

    return {factoid: result}
Пример #10
0
def fact():
    '''Returns the value of the hostname of this Mac'''
    result = 'None'

    net_config = SCDynamicStoreCreate(None, "net", None, None)
    sys_info = SCDynamicStoreCopyValue(net_config, "Setup:/System")
    result = sys_info['HostName']

    return {factoid: result}
Пример #11
0
def fact():
    '''Check to see if GlobalProtect VPN is active.'''
    result = False

    net_config = SCDynamicStoreCreate(None, "net", None, None)
    vpn = SCDynamicStoreCopyValue(net_config, 'State:/Network/Service/gpd.pan/DNS')
    if vpn is not None:
        result = True

    return {factoid: result}
def fact():
    """Returns the directory search node info"""
    result = "None"
    net_config = SCDynamicStoreCreate(None, "net", None, None)

    search_node = SCDynamicStoreCopyValue(
        net_config, "com.apple.opendirectoryd.node:/Contacts")
    result = search_node[0]

    return {factoid: result}
Пример #13
0
def fact():
    '''Returns the mac address of this Mac'''
    net_config = SCDynamicStoreCreate(None, "net", None, None)
    states = SCDynamicStoreCopyValue(net_config, "State:/Network/Global/IPv4")
    primary_interface = states["PrimaryInterface"]
    primary_device = [
        x for x in SCNetworkInterfaceCopyAll()
        if SCNetworkInterfaceGetBSDName(x) == primary_interface
    ][0]
    primary_MAC = SCNetworkInterfaceGetHardwareAddressString(primary_device)
    return {factoid: primary_MAC}
Пример #14
0
def fact():
    '''Returns the primary interface of this Mac'''
    primary_interface = None
    net_config = SCDynamicStoreCreate(None, "net", None, None)
    try:
        states = SCDynamicStoreCopyValue(net_config, "State:/Network/Global/IPv4")
        primary_interface = states['PrimaryInterface']
    except TypeError:
        pass

    return {factoid: primary_interface}
Пример #15
0
def fact():
    '''Returns Active Directory trust account'''
    result = 'None'

    net_config = SCDynamicStoreCreate(None, 'net', None, None)
    d = SCDynamicStoreCopyValue(net_config,
                                'com.apple.opendirectoryd.ActiveDirectory')

    if d:
        result = d.get('TrustAccount', None)

    return {factoid: result}
def fact():
    """Returns Active Directory forest"""
    result = "None"

    net_config = SCDynamicStoreCreate(None, "net", None, None)
    d = SCDynamicStoreCopyValue(net_config,
                                "com.apple.opendirectoryd.ActiveDirectory")

    if d:
        result = d.get("DomainForestName", None)

    return {factoid: result}
Пример #17
0
def fact():
    """Returns Active Directory trust account"""
    result = "None"

    net_config = SCDynamicStoreCreate(None, "net", None, None)
    d = SCDynamicStoreCopyValue(net_config,
                                "com.apple.opendirectoryd.ActiveDirectory")

    if d:
        result = d.get("TrustAccount", None)

    return {factoid: result}
Пример #18
0
def fact():
    '''Returns Active Directory forest'''
    result = 'None'

    net_config = SCDynamicStoreCreate(None, 'net', None, None)
    d = SCDynamicStoreCopyValue(net_config,
                                'com.apple.opendirectoryd.ActiveDirectory')

    if d:
        result = d.get('DomainForestName', None)

    return {factoid: result}
Пример #19
0
def fact():
    """Returns the current dns domain"""
    result = "None"

    net_config = SCDynamicStoreCreate(None, "net", None, None)
    dns_info = SCDynamicStoreCopyValue(net_config, "State:/Network/Global/DNS")
    if dns_info:
        try:
            result = dns_info.get("DomainName", None)
        except KeyError:
            pass

    return {factoid: str(result)}
Пример #20
0
def fact():
    '''Returns the directory search node info'''
    result = 'None'
    net_config = SCDynamicStoreCreate(None, "net", None, None)

    contacts_node = SCDynamicStoreCopyValue(
            net_config,
           "com.apple.opendirectoryd.node:/Contacts"
           )
    if contacts_node:
        result = contacts_node[0]

    return {factoid: result}
Пример #21
0
def fact():
    """Returns the current dns servers"""
    proxies = "None"

    net_config = SCDynamicStoreCreate(None, "net", None, None)
    proxy_info = SCDynamicStoreCopyValue(net_config,
                                         "State:/Network/Global/Proxies")
    if proxy_info and proxy_info.get("ProxyAutoConfigURLString"):
        try:
            proxies = proxy_info["ProxyAutoConfigURLString"]
        except KeyError:
            pass

    return {factoid: proxies}
Пример #22
0
def fact():
    '''Returns the current dns servers'''
    proxies = 'None'

    net_config = SCDynamicStoreCreate(None, "net", None, None)
    proxy_info = SCDynamicStoreCopyValue(net_config,
                                         "State:/Network/Global/Proxies")
    if proxy_info and proxy_info.get('ProxyAutoConfigURLString'):
        try:
            proxies = proxy_info['ProxyAutoConfigURLString']
        except KeyError as err:
            pass

    return {factoid: proxies}
Пример #23
0
def fact():
    '''Returns the current dns servers'''
    result = []

    net_config = SCDynamicStoreCreate(None, "net", None, None)
    dns_info = SCDynamicStoreCopyValue(net_config, "State:/Network/Global/DNS")
    if dns_info and dns_info.get('ServerAddresses'):
        try:
            for i in dns_info['ServerAddresses']:
                result.append(i)
        except KeyError as err:
            pass

    return {factoid: result}
Пример #24
0
def fact():
    """Returns the current search domains"""
    search_domains = None

    net_config = SCDynamicStoreCreate(None, "net", None, None)
    search_domains = []
    dns_info = SCDynamicStoreCopyValue(net_config, "State:/Network/Global/DNS")
    if dns_info and dns_info.get("SearchDomains"):
        try:
            for i in dns_info["SearchDomains"]:
                search_domains.append(i)
        except KeyError:
            pass

    return {factoid: search_domains}
Пример #25
0
def fact():
    '''Returns the IP of this Mac'''
    ip = None

    net_config = SCDynamicStoreCreate(None, "net", None, None)
    iface = primary_interface()
    addresses = SCDynamicStoreCopyValue(
        net_config, "State:/Network/Interface/%s/IPv4" % iface)

    if addresses:
        try:
            ip = addresses['Addresses'][0]
        except TypeError:
            ip = None

    return {factoid: ip}
Пример #26
0
def main():
    # Setup a dynamic store controller that monitors all keys:
    store = SCDynamicStoreCreate(None, "demo.controller", dynamicStoreChanged, None)
    SCDynamicStoreSetNotificationKeys(store, None, [".*"])
    source = SCDynamicStoreCreateRunLoopSource(None, store, 0)

    # Setup a preferences controller
    prefs = SCPreferencesCreate(None, "demo.prefs", None)
    SCPreferencesSetCallback(prefs, prefsChanged, None)

    # Set up a run loop and add all controllers to that.
    loop = CFRunLoopGetCurrent()
    CFRunLoopAddSource(loop, source, kCFRunLoopCommonModes)
    SCPreferencesScheduleWithRunLoop(prefs, loop, kCFRunLoopCommonModes)

    signal.signal(signal.SIGINT, sigint)
    CFRunLoopRun()
Пример #27
0
def macOSLAPS_Utility(choice, ad_user_name, ad_password, computer_name):
        '''Function to connect and pull information from Active Directory
        some code borrowed from AD PassMon - Thanks @macmuleblog'''
        # Active Directory Connection and Extraction of Data
        try:
            # Create Net Config
            net_config = SCDynamicStoreCreate(None, "net", None, None)
            # Get Active Directory Info
            ad_info = dict(
                SCDynamicStoreCopyValue(
                    net_config, 'com.apple.opendirectoryd.ActiveDirectory'))
            # Create Active Directory Path
            adpath = '{0:}/{1:}'.format(ad_info['NodeName'],
                                        ad_info['DomainNameDns'])
            # Use Open Directory To Connect to Active Directory
            node, error = ODNode.nodeWithSession_name_error_(
                ODSession.defaultSession(), adpath, None)
            node.setCredentialsWithRecordType_recordName_password_error_(
                None, ad_user_name, ad_password, None)
            # Grab the Computer Record
            computer_record, error = node.\
                recordWithRecordType_name_attributes_error_(
                    kODRecordTypeComputers,
                    "{0:}$".format(computer_name), None, None)
            # Convert to Readable Values
            values, error = computer_record.\
                recordDetailsForAttributes_error_(None, None)
            # Get LAPS Password for machine
            if choice == "1":
                print "Password: {0:}{1:}{2:}".format(
                    color.BOLD,
                    values['dsAttrTypeNative:ms-Mcs-AdmPwd'][0],
                    color.END)
                raw_input("\n\nPress any key to continue....")
            elif choice == "2":
                computer_record.setValue_forAttribute_error_(
                    '126227988000000000',
                    'dsAttrTypeNative:ms-Mcs-AdmPwdExpirationTime',
                    None)
                raw_input("\n\nForce Expire time Set. Keep in mind that"
                          " macOSLAPS will need to run on the system before"
                          " the password is changed."
                          " Press any key to continue...")
        except StandardError as error:
            print error
Пример #28
0
def main():
    net_config = SCDynamicStoreCreate(None, "net", None, None)
    print SCDynamicStoreCopyValue(net_config, "State:/Network/Global/DNS")
    interface = get_interface(net_config)
    ip = get_ip(net_config, interface)

    output = subprocess.check_output(['/sbin/ifconfig', interface])
    for line in output.splitlines():
        if ip in line:
            netmask = line.split(' ')[3].lower()

    count = int(0)
    count += int(netmask.count('f')) * 4
    count += int(netmask.count('e')) * 3
    count += int(netmask.count('c')) * 2
    count += int(netmask.count('8')) * 1

    print '%s.%s/%s' % ('.'.join(ip.split('.')[0:3]), '0', count)
Пример #29
0
def fact():
    """Returns the cidr of the current vlan"""

    result = "None"

    net_config = SCDynamicStoreCreate(None, "net", None, None)
    ip, primary_interface, netmask = "", "", ""

    primary_interface = get_iface(net_config)

    if primary_interface:
        ip = ip_address(primary_interface, net_config)

    if ip:
        try:
            proc = subprocess.Popen(
                ["/sbin/ifconfig", primary_interface],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            stdout, _ = proc.communicate()
        except (IOError, OSError):
            stdout = None

        if stdout:
            for line in stdout.splitlines():
                if ip in line:
                    netmask = line.split(" ")[3].lower()
            count = int(0)
            count += int(netmask.count("f")) * 4
            count += int(netmask.count("e")) * 3
            count += int(netmask.count("c")) * 2
            count += int(netmask.count("8")) * 1

            result = "%s.%s/%s" % (".".join(ip.split(".")[0:3]), "0", count)

    return {factoid: result}
Пример #30
0
def scan_darwin(scan, options):
    """
    Darwin scan
    :param options:
    :param scan:
    :return:
    """

    scan.add_command_output(
        ["/usr/sbin/ioreg", "-a", "-rd1", "-c", "IOPlatformExpertDevice"],
        "IOPlatformExpertDevice.xml")

    scan.add_command_output([
        "/usr/sbin/sysctl",
        "-a",
    ], "sysctl.properties")

    scan.add_command_output([
        "/usr/sbin/system_profiler", "-xml", "SPApplicationsDataType",
        "SPSoftwareDataType", "SPMemoryDataType", "SPHardwareDataType",
        "SPDiagnosticsDataType", "SPDisplaysDataType", "SPDiscBurningDataType",
        "SPEthernetDataType", "SPPrintersDataType", "SPNetworkDataType",
        "SPSerialATADataType"
    ], "system_profiler.xml")

    # active directory information for macs joined to AD (if avaliable)
    dynamic_store = SCDynamicStoreCreate(None, "net", None, None)

    stores = {
        "com.apple.opendirectoryd.ActiveDirectory": "active_directory",
        "State:/Network/NetBIOS": "netbios",
        "com.apple.smb": "smb"
    }

    for store in stores.keys():
        sc = SCDynamicStoreCopyValue(dynamic_store, store)
        if sc:
            elem = scan.create_element(stores[store])
            for key in sc:
                # noinspection PyCompatibility,PyUnresolvedReferences
                scan.append_info_element(elem, key, "S", unicode(sc[key]))
            scan.append_child(elem)

    # add os level user information
    user_elem = scan.create_element('user')
    scan.append_info_element(user_elem, 'login', 'S', os.getlogin())
    scan.append_info_element(user_elem, 'user_id', 'I', str(os.getuid()))

    # simplistic test to see if the user is Kerberos (Active Directory) enabled
    # this needs to be more elaborate in scenarios with multiple directories
    # multiple domains etc.

    try:

        authority = subprocess.check_output([
            "/usr/bin/dscl",
            ".",
            "read",
            "/Users/" + os.getlogin(),
            "AuthenticationAuthority",
        ],
                                            stderr=subprocess.STDOUT)

        if 'Kerberosv5' in authority:
            scan.append_info_element(user_elem, 'kerberos', 'B', 'true')

    except subprocess.CalledProcessError as e:
        pass

    scan.append_child(user_elem)

    if scan.command_exists('brew'):
        scan.add_command_output(['brew', 'info', '--json=v1', '--installed'],
                                'cmd/brew.json')

    scan_darwin_java(scan, options)

    scan_darwin_apps(scan, options)