Esempio n. 1
0
def GetAppleSUSCatalog():
  """Fetches an Apple Software Update Service catalog from the server."""
  url = GetServerURL()
  try:
    new = updatecheck.getResourceIfChangedAtomically(
        '%s/applesus/' % url, APPLE_SUS_CATALOG)
  except fetch.MunkiDownloadError:
    logging.exception('MunkiDownloadError getting Apple SUS catalog.')
    return

  if new:
    # SUS catalog changed, clear last check date to run softwareupdate soon.
    munkicommon.set_pref('LastAppleSoftwareUpdateCheck', None)

  try:
    sus_catalog = fpl.readPlist(APPLE_SUS_PLIST)
  except fpl.NSPropertyListSerializationException:
    # plist may not exist, but will be created when softwareupdate is run, then
    # the next execution of of this code will set the CatalogURL.
    logging.exception('Failed to read Apple SoftwareUpdate plist.')
    return

  # Update the CatalogURL setting in com.apple.SoftwareUpdate.plist.
  sus_catalog['CatalogURL'] = urlparse.urljoin(
      'file://localhost/', urllib.quote(APPLE_SUS_CATALOG))
  fpl.writePlist(sus_catalog, APPLE_SUS_PLIST)
Esempio n. 2
0
def main():
    filevault = fv_status()

    mac_ver = mac_version()

    if LooseVersion("10.11") <= LooseVersion(mac_ver):
        sip = sip_status()
    else:
        sip = 'Not Supported'

    # Yes, I know it came in 10.7.5, but eh. I don't care, I'm lazy
    if LooseVersion("10.8") <= LooseVersion(mac_ver):
        gatekeeper = gatekeeper_status()
    else:
        gatekeeper = 'Not Supported'

    plist_path = '/usr/local/sal/plugin_results.plist'

    if os.path.exists(plist_path):
        plist = FoundationPlist.readPlist(plist_path)
    else:
        plist = []
    result = {}
    result['plugin'] = 'MachineDetailSecurity'
    result['historical'] = True
    data = {}

    data['Filevault'] = filevault
    data['SIP'] = sip
    data['Gatekeeper'] = gatekeeper
    result['data'] = data
    plist.append(result)
    FoundationPlist.writePlist(plist, plist_path)
Esempio n. 3
0
def GetAppleSUSCatalog():
  """Fetches an Apple Software Update Service catalog from the server."""
  url = GetServerURL()
  try:
    updatecheck.getResourceIfChangedAtomically(
        '%s/applesus/' % url, APPLE_SUS_CATALOG)
    # Update the CatalogURL setting in com.apple.SoftwareUpdate.plist.
    sus_catalog = fpl.readPlist(APPLE_SUS_PLIST)
    sus_catalog['CatalogURL'] = urlparse.urljoin(
        'file://localhost/', urllib.quote(APPLE_SUS_CATALOG))
    fpl.writePlist(sus_catalog, APPLE_SUS_PLIST)
  except (fetch.MunkiDownloadError, fpl.NSPropertyListSerializationException):
    logging.exception('MunkiDownloadError getting Apple SUS catalog.')
Esempio n. 4
0
def main():
    uptime_seconds = get_uptime()
    
    plist_path = '/usr/local/sal/plugin_results.plist'

    if os.path.exists(plist_path):
        plist = FoundationPlist.readPlist(plist_path)
    else:
        plist = []
    result = {}
    result['plugin'] = 'Uptime'
    result['historical'] = False
    data = {}
    
    data['UptimeDays'] = uptime_seconds / 60 / 60 / 24
    data['UptimeSeconds'] = uptime_seconds
    result['data'] = data
    plist.append(result)
    FoundationPlist.writePlist(plist, plist_path)
Esempio n. 5
0
def build_prefs():
    # If munkiimport prefs exist, offer them as defaults.
    munkiimport_prefs = get_munkiimport_prefs()
    keys = ("repo_path", "repo_url")
    prefs = {}

    print ("No preference file was found for Spruce. Please allow me to "
           "break it down for you.")
    for key in keys:
        choice = None
        while choice is None:
            default = munkiimport_prefs.get(key, "")
            choice = raw_input(
                "Please enter a value for '{}' or hit enter to use the "
                "default value '{}': ".format(key, default))
        prefs[key] = choice if choice else default

    FoundationPlist.writePlist(prefs, SPRUCE_PREFS)
    return prefs
Esempio n. 6
0
def UploadAllManagedInstallReports(on_corp, logout=False):
  """Uploads any installs, updates, uninstalls back to Simian server.

  If no reports of installs/updates/uninstalls exist to report,
  then this function only contacts the server if logout is True.

  Args:
    on_corp: str, on_corp status from GetClientIdentifier.
    logout: bool, default False, whether to logout or not when finished.
  """
  # Report installs from the ManagedInstallsReport archives.
  archives_dir = os.path.join(munkicommon.pref('ManagedInstallDir'), 'Archives')
  if os.path.isdir(archives_dir):
    for fname in os.listdir(archives_dir):
      if not fname.startswith('ManagedInstallReport-'):
        continue
      install_report_path = os.path.join(archives_dir, fname)
      if not os.path.isfile(install_report_path):
        continue
      install_report, _ = GetManagedInstallReport(
          install_report_path=install_report_path)
      try:
        _UploadManagedInstallReport(on_corp, install_report)
        try:
          os.unlink(install_report_path)
        except (IOError, OSError):
          logging.warning(
              'Failed to delete ManagedInstallsReport.plist: %s',
              install_report_path)
      except ServerRequestError:
        logging.exception('Error uploading ManagedInstallReport installs.')

  # Report installs from the current ManagedInstallsReport.plist.
  install_report, install_report_path = GetManagedInstallReport()
  try:
    _UploadManagedInstallReport(on_corp, install_report, logout=logout)
    # Clear reportable information now that is has been published.
    install_report['InstallResults'] = []
    install_report['RemovalResults'] = []
    install_report['ProblemInstalls'] = []
    fpl.writePlist(install_report, install_report_path)
  except ServerRequestError:
    logging.exception('Error uploading ManagedInstallReport installs.')
Esempio n. 7
0
def add_plugin_results(plugin, data, historical=False):
    """Add data to the shared plugin results plist.

    This function creates the shared results plist file if it does not
    already exist; otherwise, it adds the entry by appending.

    Args:
        plugin (str): Name of the plugin returning data.
        data (dict): Dictionary of results.
        historical (bool): Whether to keep only one record (False) or
            all results (True). Optional, defaults to False.
    """
    plist_path = '/usr/local/sal/plugin_results.plist'
    if os.path.exists(plist_path):
        plugin_results = FoundationPlist.readPlist(plist_path)
    else:
        plugin_results = []

    plugin_results.append({'plugin': plugin, 'historical': historical, 'data': data})
    FoundationPlist.writePlist(plugin_results, plist_path)
Esempio n. 8
0
def UploadAllManagedInstallReports(client, on_corp):
  """Uploads any installs, updates, uninstalls back to Simian server.

  Args:
    client: A SimianAuthClient.
    on_corp: str, on_corp status from GetClientIdentifier.
  """
  # Report installs from the ManagedInstallsReport archives.
  archives_dir = os.path.join(munkicommon.pref('ManagedInstallDir'), 'Archives')
  if os.path.isdir(archives_dir):
    for fname in os.listdir(archives_dir):
      if not fname.startswith('ManagedInstallReport-'):
        continue
      install_report_path = os.path.join(archives_dir, fname)
      if not os.path.isfile(install_report_path):
        continue
      install_report, _ = GetManagedInstallReport(
          install_report_path=install_report_path)
      try:
        _UploadManagedInstallReport(client, on_corp, install_report)
        try:
          os.unlink(install_report_path)
        except (IOError, OSError):
          logging.warning(
              'Failed to delete ManagedInstallsReport.plist: %s',
              install_report_path)
      except ServerRequestError:
        logging.exception('Error uploading ManagedInstallReport installs.')

  # Report installs from the current ManagedInstallsReport.plist.
  install_report, install_report_path = GetManagedInstallReport()
  try:
    _UploadManagedInstallReport(client, on_corp, install_report)
    # Clear reportable information now that is has been published.
    install_report['InstallResults'] = []
    install_report['RemovalResults'] = []
    install_report['ProblemInstalls'] = []
    fpl.writePlist(install_report, install_report_path)
  except ServerRequestError:
    logging.exception('Error uploading ManagedInstallReport installs.')
Esempio n. 9
0
def UploadAllManagedInstallReports(client, on_corp):
  """Uploads any installs, updates, uninstalls back to Simian server.

  Args:
    client: A SimianAuthClient.
    on_corp: str, on_corp status from GetClientIdentifier.
  """
  # Report installs from the ManagedInstallsReport archives.
  archives_dir = os.path.join(munkicommon.pref('ManagedInstallDir'), 'Archives')
  if os.path.isdir(archives_dir):
    for fname in os.listdir(archives_dir):
      if not fname.startswith('ManagedInstallReport-'):
        continue
      install_report_path = os.path.join(archives_dir, fname)
      if not os.path.isfile(install_report_path):
        continue
      install_report, _ = GetManagedInstallReport(
          install_report_path=install_report_path)
      try:
        _UploadManagedInstallReport(client, on_corp, install_report)
        try:
          os.unlink(install_report_path)
        except (IOError, OSError):
          logging.warning(
              'Failed to delete ManagedInstallsReport.plist: %s',
              install_report_path)
      except ServerRequestError:
        logging.exception('Error uploading ManagedInstallReport installs.')

  # Report installs from the current ManagedInstallsReport.plist.
  install_report, install_report_path = GetManagedInstallReport()
  try:
    _UploadManagedInstallReport(client, on_corp, install_report)
    # Clear reportable information now that is has been published.
    install_report['InstallResults'] = []
    install_report['RemovalResults'] = []
    install_report['ProblemInstalls'] = []
    fpl.writePlist(install_report, install_report_path)
  except ServerRequestError:
    logging.exception('Error uploading ManagedInstallReport installs.')
Esempio n. 10
0
def main():
    '''main function'''
    cachedir = '%s/cache' % os.path.dirname(os.path.realpath(__file__))
    if not os.path.exists(cachedir):
        os.makedirs(cachedir)

    agent_data = get_status_data("Agent")
    mgmt_data = get_status_data("Management")

    # Build results dict that is compatible with the existing model
    result = {}
    # Translate bool values
    if "yes" in agent_data['Infected']:
        result.update({'active-threats-present': "1"})
    else:
        result.update({'active-threats-present': "0"})
    if "yes" in agent_data['Ready']:
        result.update({'agent-running': "1"})
    else:
        result.update({'agent-running': "0"})
    if "started" in agent_data['ES Framework']:
        result.update({'enforcing-security': "1"})
    else:
        result.update({'enforcing-security': "0"})
    if "enabled" in agent_data['Protection']:
        result.update({'self-protection-enabled': "1"})
    else:
        result.update({'self-protection-enabled': "0"})

    # Rest of values can be sent relatively cleanly
    result.update({'agent-version': agent_data['Version']})
    result.update({'agent-id': agent_data['ID']})
    result.update(
        {'last-seen': dp.parse(mgmt_data['Last Seen']).strftime('%s')})
    result.update({'mgmt-url': mgmt_data['Server']})

    # Write results of checks to cache file
    output_plist = os.path.join(cachedir, 'sentinelone.plist')
    FoundationPlist.writePlist(result, output_plist)
Esempio n. 11
0
def main():
    plist_path = '/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/XProtect.meta.plist'
    if os.path.exists(plist_path):
        plist = FoundationPlist.readPlist(plist_path)
        version = str(plist['Version'])
    else:
        version = 'Not supported'

    plist_path = '/usr/local/sal/plugin_results.plist'

    if os.path.exists(plist_path):
        plist = FoundationPlist.readPlist(plist_path)
    else:
        plist = []
    result = {}
    result['plugin'] = 'XprotectVersion'
    result['historical'] = False
    data = {}
    data['Version'] = version
    result['data'] = data
    plist.append(result)
    FoundationPlist.writePlist(plist, plist_path)
Esempio n. 12
0
def add_plugin_results(plugin, data, historical=False):
    """Add data to the shared plugin results plist.

    This function creates the shared results plist file if it does not
    already exist; otherwise, it adds the entry by appending.

    Args:
        plugin (str): Name of the plugin returning data.
        data (dict): Dictionary of results.
        historical (bool): Whether to keep only one record (False) or
            all results (True). Optional, defaults to False.
    """
    plist_path = '/usr/local/sal/plugin_results.plist'
    if os.path.exists(plist_path):
        plugin_results = FoundationPlist.readPlist(plist_path)
    else:
        plugin_results = []

    plugin_results.append({
        'plugin': plugin,
        'historical': historical,
        'data': data
    })
    FoundationPlist.writePlist(plugin_results, plist_path)
Esempio n. 13
0
def main():
    # Skip running on manual munki check
    if len(sys.argv) > 1:
        if sys.argv[1] == 'manualcheck':
            print 'Manual check: skipping'
            exit(0)

    # Create cache dir if it does not exist
    cachedir = '%s/cache' % os.path.dirname(os.path.realpath(__file__))
    if not os.path.exists(cachedir):
        os.makedirs(cachedir)

    result = {}
    # check if Sophos is installed, and check for InterceptX
    if os.path.isdir('/Library/Sophos Anti-Virus/SophosCryptoGuardLegacy.app'):
        result.update({'Installed': 'Sophos Central with InterceptX'})
    elif os.path.isdir('/Applications/Sophos Endpoint.app'):
        result.update({'Installed': 'Sophos Central'})
    elif os.path.isdir('/Applications/Sophos/Sophos Endpoint.app'):
        result.update({'Installed': 'Sophos Central'})
    elif os.path.isdir('/Applications/Sophos Anti-Virus.app'):
        result.update({'Installed': 'Sophos Business'})
    else:
        result.update({'Installed': 'Not Installed'})

    # check if Sophos is running
    if result['Installed']:
        # check if Sophos is running
        result.update({'Running': check_sophos_running()})

    # check component versions
        result.update({'Versions': check_sophos_versions()})

    # Write results of checks to cache file
    output_plist = os.path.join(cachedir, 'sophos.plist')
    FoundationPlist.writePlist(result, output_plist)
Esempio n. 14
0
def main():

    if os.path.exists('/usr/bin/fdesetup'):
        filevault = fv_status()
    else:
        filevault = 'Not Supported'

    if os.path.exists('/usr/bin/csrutil'):
        sip = sip_status()
    else:
        sip = 'Not Supported'

    # Yes, I know it came in 10.7.5, but eh. I don't care, I'm lazy
    if os.path.exists('/usr/sbin/spctl'):
        gatekeeper = gatekeeper_status()
    else:
        gatekeeper = 'Not Supported'

    plist_path = '/usr/local/sal/plugin_results.plist'

    if os.path.exists(plist_path):
        plist = FoundationPlist.readPlist(plist_path)
    else:
        plist = []
    result = {}
    result['plugin'] = 'MachineDetailSecurity'
    result['historical'] = False
    data = {}

    data['Filevault'] = filevault
    data['SIP'] = sip
    data['Gatekeeper'] = gatekeeper
    result['data'] = data
    plist.append(result)
    print plist
    FoundationPlist.writePlist(plist, plist_path)
Esempio n. 15
0
        if item_pl:
            if updatecheck.installedState(item_pl):
                installed_state = "installed"
                exit_code = 0
            else:
                installed_state = "not installed"
                exit_code = 1
        print("%s: %s") % (check_item, installed_state)
        sys.exit(exit_code)

if not options.install and not options.uninstall:
    sys.exit()

temp_dir = tempfile.mkdtemp()
temp_plist = temp_dir + "/localmanifest.plist"
manifest = {}
manifest["catalogs"] = cataloglist
manifest["managed_installs"] = options.install or []
manifest["managed_uninstalls"] = options.uninstall or []
FoundationPlist.writePlist(manifest, temp_plist)
updatecheckresult = updatecheck.check(localmanifestpath=temp_plist)
if updatecheckresult == 1:
    need_to_restart = installer.run()
    if need_to_restart:
        print("Please restart immediately!")

try:
    shutil.rmtree(temp_dir)
except OSError:
    print("Could not remove temp directory")
Esempio n. 16
0
def main():
    # Skip a manual check
    if len(sys.argv) > 1:
        if sys.argv[1] == 'manualcheck':
            munkicommon.display_debug2("Manual check: skipping MunkiInfo Plugin")
            exit(0)

    prefs_to_get = [
        'ManagedInstallDir',
        'SoftwareRepoURL',
        'ClientIdentifier',
        'LogFile',
        'LoggingLevel',
        'LogToSyslog',
        'InstallAppleSoftwareUpdates',
        'AppleSoftwareUpdatesOnly',
        'SoftwareUpdateServerURL',
        'DaysBetweenNotifications',
        'LastNotifiedDate',
        'UseClientCertificate',
        'SuppressUserNotification',
        'SuppressAutoInstall',
        'SuppressStopButtonOnInstall',
        'PackageVerificationMode',
        'FollowHTTPRedirects',
        'UnattendedAppleUpdates',
        'ClientCertificatePath',
        'ClientKeyPath',
        'LastAppleSoftwareUpdateCheck',
        'LastCheckDate',
        'LastCheckResult',
        'LogFile',
        'SoftwareRepoCACertificate',
        'SoftwareRepoCAPath',
        'PackageURL',
        'CatalogURL',
        'ManifestURL',
        'IconURL',
        'ClientResourceURL',
        'ClientResourcesFilename',
        'HelpURL',
        'UseClientCertificateCNAsClientIdentifier',
        'AdditionalHttpHeaders',
        'SuppressLoginwindowInstall',
        'InstallRequiresLogout',
        'ShowRemovalDetail',
        'MSULogEnabled',
        'MSUDebugLogEnabled',
        'LocalOnlyManifest',
        'UnattendedAppleUpdates'
    ]
    plist_path = '/usr/local/sal/plugin_results.plist'
    if os.path.exists(plist_path):
        plist = FoundationPlist.readPlist(plist_path)
    else:
        plist = []
    result = {}
    result['plugin'] = 'MunkiInfo'
    result['historical'] = False
    data = {}
    for the_pref in prefs_to_get:
        data[the_pref] = str(munkicommon.pref(the_pref))

    result['data'] = data
    plist.append(result)
    FoundationPlist.writePlist(plist, plist_path)
Esempio n. 17
0
import os
import sys

sys.path.insert(0,'/usr/local/munki')

from munkilib import FoundationPlist

invPath = r"/Library/Managed Installs/ApplicationInventory.plist"
plugins = r"/Library/Internet Plug-Ins/"
directoryListing = os.listdir(plugins)
appinv = FoundationPlist.readPlist(invPath)

print "Adding %i plugins" % len(directoryListing)

for x in directoryListing:
    path = os.path.join(plugins, x, 'Contents/Info.plist')
    try:
        info = FoundationPlist.readPlist(path)
        plugin = {}
        plugin['CFBundleName'] = info.get('CFBundleName', x)
        plugin['bundleid'] = info.get('CFBundleIdentifier', 'N/A')
        plugin['version'] = info.get('CFBundleVersion','N/A')
        plugin['path'] = os.path.join(plugins, x)
        plugin['name'] = info.get('CFBundleName', os.path.splitext(os.path.basename(x))[0])
        appinv.append(plugin.copy())
    except Exception, message:
        pass

FoundationPlist.writePlist(appinv, invPath)
exit(0)
Esempio n. 18
0
if options.checkstate:
    updatecheck.MACHINE = munkicommon.getMachineFacts()
    updatecheck.CONDITIONS = munkicommon.getConditions()
    updatecheck.getCatalogs(cataloglist)
    for check_item in options.checkstate:
        installed_state = "unknown"
        item_pl = updatecheck.getItemDetail(check_item, cataloglist)
        if item_pl:
            if updatecheck.installedState(item_pl):
                installed_state = "installed"
                exit_code = 0
            else:
                installed_state = "not installed"
                exit_code = 1
        print "%s: %s" % (check_item, installed_state)
        exit(exit_code)

if not options.install and not options.uninstall:
    exit()

manifest = {}
manifest["catalogs"] = cataloglist
manifest["managed_installs"] = options.install or []
manifest["managed_uninstalls"] = options.uninstall or []
FoundationPlist.writePlist(manifest, "/tmp/localmanifest.plist")
updatecheckresult = updatecheck.check(localmanifestpath="/tmp/localmanifest.plist")
if updatecheckresult == 1:
    need_to_restart = installer.run()
    if need_to_restart:
        print "Please restart immediately!"
def write_plist(plist, filename):
    FoundationPlist.writePlist(plist, filename)