コード例 #1
0
def extract_bundleid_and_authorize(app_path):
    info_path = app_path + "/info.plist"
    if os.path.exists(info_path):
        plist = biplist.readPlist(info_path)
        bundle_id = plist['CFBundleIdentifier']
        ios_sim_location_authorize(bundle_id)
        logger.info("Location service authorized.")
コード例 #2
0
ファイル: path.py プロジェクト: ratazzi/ServicesBox-Helper
def bootstrap():
    defaults_path = os.path.expanduser('~/Library/Preferences/org.ratazzi.ServicesBox.plist')
    defaults = dict()
    if os.path.isfile(defaults_path):
        try:
            defaults = biplist.readPlist(defaults_path)
        except (biplist.InvalidPlistException, biplist.NotBinaryPlistException):
            defaults = plistlib.readPlist(defaults_path)

    if 'dir_library' in defaults:
        env.add('dir_library', defaults['dir_library'])
    else:
        # development environment
        env.add('dir_library', os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))

    bundles = 'darwin' in sys.platform and 'bundles' or 'bundle'

    env.add('dir_bundles', os.path.join(env.get('dir_library'), bundles))
    env.add('dir_config', os.path.join(env.get('dir_library'), 'etc'))
    env.add('dir_bin', os.path.join(env.get('dir_library'), 'bin'))
    env.add('dir_tmp', os.path.join(env.get('dir_library'), 'tmp'))
    env.add('dir_data', os.path.join(env.get('dir_library'), 'data'))
    env.add('dir_log', os.path.join(env.get('dir_library'), 'var', 'log'))
    env.add('dir_run', os.path.join(env.get('dir_library'), 'var', 'run'))

    # custom data path
    for item in DEFAULT_DIRS.keys():
        key = 'dir_%s' % item
        if defaults.get(key):
            env.add(key, defaults[key])

    for k, _dir in os.environ.items():
        if k.startswith('%sDIR_' % env.PREFIX):
            if not os.path.exists(_dir):
                os.makedirs(_dir)
コード例 #3
0
def getLabelsByMessage(mailroot):
    global system_labels, mail_version, osx_version

    if osx_version < 101100:
        base_url = re.sub(r'^.*?(IMAP|POP)-(.*)$',lambda match: r'{}://{}'.format(match.group(1).lower(),match.group(2)),mailroot)
    else:
        account_ids = {}
        backuptoc_plist = biplist.readPlist(os.path.expanduser("~/Library/Mail/" + mail_version + "/MailData/BackupTOC.plist"))
        for mailbox in backuptoc_plist['mailboxes']:
             if mailbox.has_key('path'):
                 account_ids[mailbox['path'][1:]] = mailbox['account-id']
        protocol = re.sub(r'^.*?(IMAP|POP)-.*$',lambda match: r'{}'.format(match.group(1).lower()),mailroot)
        account = re.sub(r'^.*?(IMAP|POP)-(.*)',lambda match: r'{}-{}'.format(match.group(1),match.group(2)),mailroot)
        if account_ids.has_key(account):
            base_url = '{}://{}'.format(protocol,account_ids[account])
        else:
            base_url = 'noaccountid'

    label_list = defaultdict(list)
    conn = sqlite3.connect(os.path.expanduser('~') + "/Library/Mail/" + mail_version + "/MailData/Envelope Index")
    c = conn.cursor()
    query = "SELECT labels.message_id, mailboxes.url FROM labels INNER JOIN mailboxes ON labels.mailbox_id=mailboxes.ROWID WHERE url LIKE ?"
    for row in c.execute(query,[base_url + "%"]):
        label_part = urllib.unquote(row[1].replace(base_url + "/","")).decode('utf8')
        if label_part in system_labels:
            label_part = system_labels[label_part]
        label_list[row[0]].append(label_part)
    conn.close()
    return label_list
コード例 #4
0
ファイル: obok_2.01.py プロジェクト: 12101/dedrm-ebook-tools
def GetUserHexKey(prefs = ""):
    "find wsuid and pwsdid"
    wsuid = ""
    pwsdid = ""
    if sys.platform.startswith('win'):
        regkey_browser = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\Kobo\\Kobo Desktop Edition\\Browser")
        cookies = _winreg.QueryValueEx(regkey_browser, "cookies")
        bytearrays = cookies[0]
    elif sys.platform.startswith('darwin'):
        cookies = readPlist(prefs)
        bytearrays = cookies["Browser.cookies"]
    for bytearr in bytearrays:
        cookie = ByteArrayToString(bytearr)
        print cookie
        wsuidcheck = re.match("^wsuid=([0-9a-f-]+)", cookie)
        if(wsuidcheck):
            wsuid = wsuidcheck.group(1)
        pwsdidcheck = re.match("^pwsdid=([0-9a-f-]+)", cookie)
        if (pwsdidcheck):
            pwsdid = pwsdidcheck.group(1)

    if(wsuid == "" or pwsdid == ""):
        print "wsuid or pwsdid key not found :/"
        exit()
    preuserkey = string.join((pwsdid, wsuid), "")
    print SHA256(pwsdid)
    userkey = SHA256(preuserkey)
    return userkey[32:]
コード例 #5
0
ファイル: check_itunes_app.py プロジェクト: liuliainio/liuli
def check_app():
    hash_apple_id()
    bad_id_dic = {}
    i = 0
    while True:
        ipas = get_ipas()
        if not ipas:
            update_app_num()
            print bad_id_dic.keys()
            return
        report_list = []
        for ipa in ipas:
            i += 1
            file_name = md5(ipa[2]).hexdigest().upper()
            path = '/mnt/ctappstore100/vol%s/%s/%s/%s.ipa' % (ipa[1], file_name[:2], file_name[2:4], file_name)
            zf = zipfile.ZipFile(path)
            zf.extract('iTunesMetadata.plist')
            itunes = biplist.readPlist('iTunesMetadata.plist')
            if itunes['appleId'] in hash_id_dic:
                app_num_dic[hash_id_dic[itunes['appleId']]] = app_num_dic[hash_id_dic[itunes['appleId']]] + 1
                report_list.append((ipa[3], hash_id_dic[itunes['appleId']]))
            else:
                print itunes['appleId']
                bad_id_dic[itunes['appleId']] = 1
            print i
        report_status(report_list)
コード例 #6
0
ファイル: core.py プロジェクト: smoriarty21/OSXAuditor
def UniversalReadPlist(PlistPath):
    plistDictionnary = False

    if FOUNDATION_IS_IMPORTED:
        plistNSData, errorMessage = Foundation.NSData.dataWithContentsOfFile_options_error_(PlistPath, Foundation.NSUncachedRead, None)
        if errorMessage is not None or plistNSData is None:
            log.PrintAndLog(u"Unable to read in the data from the plist file: " + PlistPath.decode("utf-8"), "ERROR")
        plistDictionnary, plistFormat, errorMessage = Foundation.NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_(plistNSData, Foundation.NSPropertyListMutableContainers, None, None)
        if errorMessage is not None or plistDictionnary is None:
            log.PrintAndLog(u"Unable to read in the data from the plist file: " + PlistPath.decode("utf-8"), "ERROR")
        if not hasattr(plistDictionnary, "has_key"):
            log.PrintAndLog(u"The plist does not have a dictionary as its root as expected: " + PlistPath.decode("utf-8"), "ERROR")
        return plistDictionnary
    else:
        if BIPLIST_IS_IMPORTED:
            try:
                plistDictionnary = biplist.readPlist(PlistPath)
            except (IOError):
                log.PrintAndLog (u"Cannot open " + PlistPath.decode("utf-8") , "ERROR")
            except:
                log.PrintAndLog(u"Cannot parse " + PlistPath.decode("utf-8") + u" (Binary or JSON plist may FAIL) \n", "ERROR")
            return plistDictionnary

        elif PLISTLIB_IS_IMPORTED:
            try:
                plistDictionnary = plistlib.readPlist(PlistPath)
            except (IOError):
                log.PrintAndLog (u"Cannot open " + PlistPath.decode("utf-8") , "ERROR")
            except:
                log.PrintAndLog(u"Cannot parse " + PlistPath.decode("utf-8") + u" (Binary or JSON plist may FAIL) \n", "ERROR")
            return plistDictionnary
        else:
            log.PrintAndLog(u"Cannot parse " + PlistPath.decode("utf-8") + u". No plist lib available.\n", "ERROR")
            return None
コード例 #7
0
def upload_app_to_testflight(archive_path, testflight_api_token, testflight_team_token, testflight_distro_lists=[], notify=True):

    plist_path = "%s/Info.plist" % archive_path
    archive_plist = biplist.readPlist(plist_path)

    app_path = archive_plist['ApplicationProperties']['ApplicationPath']
    app_name = archive_plist['Name']
    full_app_path = "%s/Products/%s" % (archive_path, app_path)
    dsym_path = "%s/dSYMs/%s.app.dSYM" % (archive_path, app_name)

    app_package = package_app('iphoneos', full_app_path, app_name)
    app_dsym_zip = zip_dsym(dsym_path)
    notes = compile_note_from_git_head()
    distro_list = ",".join(testflight_distro_lists)

    file_upload_params = {'file' : app_package, 'dsym' : app_dsym_zip}
    meta_params = {
            'api_token'          : testflight_api_token,
            'team_token'         : testflight_team_token,
            'notes'              : notes,
            'notify'             : notify,
            'distribution_lists' : distro_list
            }
    upload_response = requests.post(testflight_api_url, meta_params, files=file_upload_params)

    app_package.close()
    app_dsym_zip.close()

    print upload_response.text

    if upload_response.status_code == 200:
        return True
    else:
        return False
コード例 #8
0
ファイル: __init__.py プロジェクト: wooster/gitlogger
	def commits_for_user(self, username):
		users = biplist.readPlist(self.user_file_path)
		user_info = users.get(username)
		email_addresses = user_info['email_addresses']
		in_user_commit = False
		current_timestamp = 0
		commits_for_timestamp = {}
		repos = github_repos(username=username, password=user_info['password'])
		for repo in repos:
			repo_path = self._repo_path(username, repo.name)
			log_for_repo = self._log_for_repo(repo, repo_path)
			for line in log_for_repo.splitlines():
				if line.startswith(">>"):
					(commit, timestamp_dt, timestamp_unix, email) = line[2:].split("|")
					if email in email_addresses:
						in_user_commit = True
						utc_datetime = self.convert_iso8601_to_utc( self.reformat_as_actual_iso8601(timestamp_dt))
						current_timestamp = utc_datetime
						commits_for_timestamp.setdefault(current_timestamp, {'added':0, 'removed':0, 'timestamp_local':timestamp_dt})
					else:
						print >> sys.stderr, "Unknown email:", email
						in_user_commit = False
					continue
				elif len(line) and in_user_commit:
					try:
						(added, removed) = line.split()[0:2]
						if added != '-':
							commits_for_timestamp[current_timestamp]['added'] += int(added)
						if removed != '-':
							commits_for_timestamp[current_timestamp]['removed'] += int(removed)
					except ValueError as e:
						print >> sys.stderr, e
						print >> sys.stderr, "Error on:", line
		return commits_for_timestamp
コード例 #9
0
ファイル: app.py プロジェクト: randombrein/RIL2SRL
def import_srl(ril_data):
    try:
        plist = readPlist(SRL_FILE)

    except (InvalidPlistException, NotBinaryPlistException), e:
        print "Not a plist:", e
        return
コード例 #10
0
ファイル: AppGettr.py プロジェクト: espes/AppGettr
def readZipPlist(zipf, name):
  try:
    metadataFile = zipf.open(name)
    return plistlib.readPlist(metadataFile)
  except Exception:
    metadataFile = StringIO(zipf.read(name))
    return biplist.readPlist(metadataFile)
コード例 #11
0
ファイル: bundle.py プロジェクト: appknox/isign
    def resign(self, deep, signer, provisioning_profile, alternate_entitlements_path=None):
        """ signs app in place """

        # TODO all this mucking about with entitlements feels wrong. The entitlements_path is
        # not actually functional, it's just a way of passing it to later stages of signing.
        # Maybe we should determine entitlements data in isign/archive.py or even isign/isign.py,
        # and then embed it into Signer?

        # In the typical case, we add entitlements from the pprof into the app's signature
        if not signer.is_adhoc():
            if alternate_entitlements_path is None:
                # copy the provisioning profile in
                self.provision(provisioning_profile)

                entitlements = self.extract_entitlements(provisioning_profile)

            else:
                log.info("signing with alternative entitlements: {}".format(alternate_entitlements_path))
                entitlements = biplist.readPlist(alternate_entitlements_path)
            self.write_entitlements(entitlements)

        # actually resign this bundle now
        super(App, self).resign(deep, signer)

        # The entitlements are only needed temporarily while signing so we
        # don't want to leave the file in the Payload/archive...
        os.remove(self.entitlements_path);
コード例 #12
0
	def wifiPlists(self):
		# 3ea0280c7d1bd352397fc658b2328a7f3b124f3b - Signatures

		# ade0340f576ee14793c607073bd7e8e409af07a8 - List of known networks
		# -- SecurityMode, WiFiNetworkRequiresPassword, lastAutoJoined, SSID_STR (name of wifi)
		# Strength, WEPKeyLen, lastJoined, WiFiNetworkIsSecure, ?80211W_ENABLED?, BSSID
		# NYU has: EnterpriseProfile/EAPClientConfiguration/UserName
		wifi_data_list = list()

		knownNets = os.path.join(self.appDir, "ade0340f576ee14793c607073bd7e8e409af07a8.plist")

		if os.path.exists(knownNets):
			
			try:
				data = biplist.readPlist(knownNets)

				wifi_data_list = self.returnWifiPlistData(data, wifi_data_list)

			except:
				try:
					data = plistlib.readPlist(knownNets)

					wifi_data_list = self.returnWifiPlistData(data, wifi_data_list)

				except:
					print "Error reading wifi Plist"


		return wifi_data_list
コード例 #13
0
ファイル: models.py プロジェクト: mani3/appinstaller
 def plist(self, filepath, key):
     try:
         print filepath
         plist = biplist.readPlist(os.path.expanduser(filepath))
     except IOError, e:
         app.logger.error(e)
         pass
コード例 #14
0
ファイル: plist.py プロジェクト: aln787/macbuild
def do_plist(module, filename, values, backup=False):
    working_values = values
    changed = False

    try:
        f = open(filename)
        plist = biplist.readPlist(f)
    except IOError:
        plist = {}
    except biplist.InvalidPlistException:
        module.fail_json(msg="an invalid plist already exists")

    changed = not equal(plist, working_values)

    if changed and not module.check_mode:
        if backup:
            module.backup_local(filename)

        try:
            update(plist, working_values)
            plist_dir = os.path.dirname(filename)
            if not os.path.exists(plist_dir):
                os.makedirs(plist_dir)
            f = open(filename, 'w')
            biplist.writePlist(plist, f)
        except Exception as e:
            module.fail_json(msg="Can't change %s" % filename, error=str(e))

    return changed
コード例 #15
0
 def __init__(self, plugInPath):
     # Load properties
     propsPath = plugInPath + "/CCBPProperties.plist"
     props = biplist.readPlist(propsPath)
     
     self._nodeClassName = props.get("className")
     self._nodeEditorClassName = props.get("editorClassName")
     
     self._nodeProperties = []
     self._nodePropertiesDict = {}
     
     self.loadPropertiesForBundle(plugInPath, self._nodeProperties)
     self.setupNodePropsDict()
     
     # Support for spriteFrame drop targets
     spriteFrameDrop = props.get("spriteFrameDrop")
     if spriteFrameDrop:
         self._dropTargetSpriteFrameClass = spriteFrameDrop.get("className")
         self._dropTargetSpriteFrameProperty = spriteFrameDrop.get("property")
         
     # Check if node type can be root node and which children are allowed
     self._canBeRoot = bool(props.get("canBeRootNode"))
     self._canHaveChildren = bool(props.get("canHaveChildren"))
     self._isAbstract = bool(props.get("isAbstract"))
     self._requireChildClass = props.get("requireChildClass")
     self._requireParentClass = props.get("requireParentClass")
     self._positionProperty = props.get("positionProperty")
コード例 #16
0
ファイル: unTRUST.py プロジェクト: NotionalLabs/unTRUST
    def parse_plist_file(self, filename):
        plist_dict = None
        self.logr('Parsing .plist file: %s' % filename, 0)

        try:
            plist_dict = biplist.readPlist(filename)
        except:
            self.logr('Error parsing .plist file %s' % filename, 1)

        # Apple base64 encodes the Certificates in the binary plists
        # If any of these keys do not exist, give them blank string value
        if 'HostCertificate' in plist_dict.keys():
            plist_dict['HostCertificate'] = self.strip_formatting(plist_dict['HostCertificate'].encode("base64").strip())
        else:
            plist_dict['HostCertificate'] = ' '

        if 'RootCertificate' in plist_dict.keys():
            plist_dict['RootCertificate'] = self.strip_formatting(plist_dict['RootCertificate'].encode("base64").strip())
        else:
            plist_dict['HostCertificate'] = ' '

        if 'DeviceCertificate' in plist_dict.keys():
            plist_dict['DeviceCertificate'] = self.strip_formatting(plist_dict['DeviceCertificate'].encode("base64").strip())
        else:
            plist_dict['HostCertificate'] = ' '

        if 'HostID' not in plist_dict.keys():
            plist_dict['HostID'] = ' '

        if 'SystemBUID' not in plist_dict.keys():
            plist_dict['SystemBUID'] = ' '
        
        plist_dict['mtime'] = time.ctime(os.path.getmtime(filename))

        return plist_dict
コード例 #17
0
def ios_sim_location_authorize(bundle_id, on_off='on'):
    '''
    Give location authorization to app according to the Bundle ID.
    Change the .plist file in simulator folder.
    '''

    tmp = os.path.join(os.path.expanduser("~/Library"), "Application Support", "iPhone Simulator", "*.*", "Library")
    paths = glob.glob(tmp)

    for sim_dir in paths:
        sim_dir = os.path.join(sim_dir, 'Caches')
        if not os.path.exists(sim_dir):
            os.mkdir(sim_dir)
        sim_dir = os.path.join(sim_dir, 'locationd')
        if not os.path.exists(sim_dir):
            os.mkdir(sim_dir)

        existing_path = os.path.join(sim_dir, 'clients.plist')
        if os.path.exists(existing_path):
            plist = biplist.readPlist(existing_path)
        else:
            plist = {}

        if bundle_id not in plist:
            plist[bundle_id] = {}

        plist[bundle_id]["BundleId"] = bundle_id
        plist[bundle_id]["Authorized"] = True if on_off == "on" else False
        plist[bundle_id]["LocationTimeStarted"] = 0

        biplist.writePlist(plist, existing_path)
コード例 #18
0
ファイル: __init__.py プロジェクト: wooster/gitlogger
	def add_email(self, username, email):
		users = biplist.readPlist(self.user_file_path)
		user_info = users.get(username)
		if email not in user_info['email_addresses']:
			user_info['email_addresses'].append(email)
		users[username] = user_info
		biplist.writePlist(users, self.user_file_path)
コード例 #19
0
ファイル: iosRecovery.py プロジェクト: OSaa/BackupProfiler
def getAppFiles(infoplist, backupDir, AppFiles):

    # Get files in backup
    fileList = list()
    for root, dirs, files in os.walk(backupDir):
        for filename in os.listdir(backupDir):
            fullpath = os.path.join(backupDir, filename)
            if os.path.isfile(fullpath):
                fileList.append(filename)
        
    
    encryptedDict = dict()

    try:
        info = plistlib.readPlist(infoplist)
    except:
        try:
            info = biplist.readPlist(infoplist)
        except:
            print "Cannot read Info.plist for app data"

    InstalledApps = info.get("Installed Applications")

    for app in InstalledApps:
        data = ("AppDomain-" + app + "-Library/Preferences/" + app + ".plist")
        data = hashlib.sha1(data).hexdigest()
        if (not encryptedDict.has_key(data)):
            encryptedDict[data] = app

    for plistName in fileList:
        if encryptedDict.has_key(plistName):
            if not os.path.exists( AppFiles + plistName + ".plist"):
                fullPath = os.path.join(backupDir, plistName)
                shutil.copy(fullPath, AppFiles)
                appFolder = AppFiles + plistName
                newname = os.rename(appFolder, appFolder + ".plist")
        
        elif encryptedDict.has_key(plistName[:-6]):
            fullPath = os.path.join(backupDir, plistName)
            shutil.copy(fullPath, AppFiles)

    # 37d957bda6d8be85555e7c0a7d30c5a8bc1b5cce - Recent Searches
    # ed50eadf14505ef0b433e0c4a380526ad6656d3a - Web History Dates
    # 4f6a6e175b8b087c833905bcc4e304d1389ae7b4 - Weather Cities
    # 691fe25b949227d26b6c59432bf108f6e3ec54ec - Stocks Data
    # 3ea0280c7d1bd352397fc658b2328a7f3b124f3b - Signatures
    # ade0340f576ee14793c607073bd7e8e409af07a8 - List of known networks
    # 51a4616e576dd33cd2abadfea874eb8ff246bf0e - Keychain Data

    dataPlists = ["51a4616e576dd33cd2abadfea874eb8ff246bf0e", "ade0340f576ee14793c607073bd7e8e409af07a8", "5ceceae7e957a53682cf500e5dd9499b5e2278aa", "3ea0280c7d1bd352397fc658b2328a7f3b124f3b", "691fe25b949227d26b6c59432bf108f6e3ec54ec", "4f6a6e175b8b087c833905bcc4e304d1389ae7b4", "37d957bda6d8be85555e7c0a7d30c5a8bc1b5cce", "ed50eadf14505ef0b433e0c4a380526ad6656d3a"]

    for plist in dataPlists:
        if plist in fileList:
            if not os.path.exists( AppFiles + plist + ".plist"):
                fullPath = os.path.join(backupDir, plist)
                shutil.copy(fullPath, AppFiles)

                appFolder = os.path.join(AppFiles, plist)
                newname = os.rename(appFolder, appFolder + ".plist")
コード例 #20
0
ファイル: views.py プロジェクト: aelam/AppManager
def provisioning_profile_list(request):
    provs = ProvisioningProfile.objects.all()[0]
    print(provs)
    plist = biplist.readPlist(provs.profile_path)
    print(plist)


    return HttpResponse("provisioning_profile_list")
コード例 #21
0
def convert_bin_xml(bin_xml_file):
    """Convert Binary XML to Readable XML"""
    try:
      plist_obj = readPlist(bin_xml_file)
      data = writePlistToString(plist_obj)
      return data
    except biplist.InvalidPlistException:
      logger.warning("Failed to convert plist")
コード例 #22
0
ファイル: messages.py プロジェクト: gotomypc/pushproxy
    def parsingFinished(self):
        # decode iMessage biplist payload
        iMessageTopic = 'e4e6d952954168d0a5db02dbaf27cc35fc18d159' \
                         .decode('hex')
        if self.topic == iMessageTopic \
            or self.recipientPushToken == iMessageTopic:

            self.biplist = biplist.readPlist(StringIO(self.payload))
コード例 #23
0
ファイル: fileParser.py プロジェクト: 2016flyinbed/cocos
def parserPlist(plistFile):
	if not os.path.isfile(plistFile):
		plistInfo = {}
	else:
		try:
			plistInfo = biplist.readPlist(plistFile)			
		except Exception, e:
			plistInfo = {}
コード例 #24
0
def read(stream):
    if not isinstance(stream, six.BytesIO):
        stream = six.BytesIO(stream)
    if biplist.is_stream_binary_plist(stream):
        stream.seek(0)
        return biplist.readPlist(stream)
    stream.seek(0)
    return loads(stream)
コード例 #25
0
ファイル: firewall.py プロジェクト: LucaBongiorni/idiot
    def run(self):
        try:
            d = biplist.readPlist('/Library/Preferences/com.apple.alf.plist')
            enabled = (d['globalstate'] == 1)
        except:
            return (False, "failed to read firewall config plist")

        return (enabled, "{}".format("enabled" if enabled else "disabled"))
コード例 #26
0
ファイル: PackageHandlers.py プロジェクト: akfreas/spout
    def plist_from_ipa(self):

        app_name = self.extract_app_name()
        plist_dict_path = self.ipa_file.extract("Payload/" + app_name + ".app/" + "Info.plist", path=self.temp_dir)

        parsed_dict = biplist.readPlist(plist_dict_path)
        copied_dict = dict(parsed_dict)

        return copied_dict
コード例 #27
0
ファイル: dmgbuild_cfg.py プロジェクト: joshuasb/knossos
def icon_from_app(app_path):
    plist_path = os.path.join(app_path, "Contents", "Info.plist")
    plist = biplist.readPlist(plist_path)
    icon_name = plist["CFBundleIconFile"]
    icon_root, icon_ext = os.path.splitext(icon_name)
    if not icon_ext:
        icon_ext = ".icns"
    icon_name = icon_root + icon_ext
    return os.path.join(app_path, "Contents", "Resources", icon_name)
コード例 #28
0
ファイル: build_steps.py プロジェクト: homerjam/file2
def set_in_biplist(build_params, filename, key, value):
	if isinstance(value, str) or isinstance(value, unicode):
		value = pystache.render(value, build_params['app_config'])
	
	found_files = glob.glob(filename)
	for found_file in found_files:
		plist = biplist.readPlist(found_file)
		plist = utils.transform(plist, key, lambda _: value, allow_set=True)
		biplist.writePlist(plist, found_file)
コード例 #29
0
ファイル: dmgbuild_settings.py プロジェクト: AURIN/geoserver
def icon_from_app(app_path):
    plist_path = os.path.join(app_path, 'Contents', 'Info.plist')
    plist = biplist.readPlist(plist_path)
    icon_name = plist['CFBundleIconFile']
    icon_root,icon_ext = os.path.splitext(icon_name)
    if not icon_ext:
        icon_ext = '.icns'
    icon_name = icon_root + icon_ext
    return os.path.join(app_path, 'Contents', 'Resources', icon_name)
コード例 #30
0
ファイル: bundle.py プロジェクト: dweinstein/isign
 def __init__(self, path):
     self.path = path
     info_path = join(self.path, 'Info.plist')
     if not exists(info_path):
         raise NotMatched("no Info.plist found; probably not a bundle")
     self.info = biplist.readPlist(info_path)
     if not is_info_plist_native(self.info):
         raise NotMatched("not a native iOS bundle")
     # will be added later
     self.seal_path = None
コード例 #31
0
import biplist
import glob, os
import argparse

parser = argparse.ArgumentParser()

parser.add_argument('output', help='Filename for output')
args = parser.parse_args()
output = open(args.output, 'w')
directory = '/Applications'
for path, dirs, files in os.walk(directory):
    for subdir in dirs:
        if subdir.endswith('.app'):
            plist_path = os.path.join(path, subdir, 'Contents/Info.plist')
            output.write(subdir)
            output.write('\n')
            try:
                plist = biplist.readPlist(plist_path)
            except:
                output.write('No Version Found\n')
                continue
            if 'CFBundleShortVersionString' in plist.keys():
                output.write(plist['CFBundleShortVersionString'])
            elif 'CFBundleVersion' in plist.keys():
                output.write(plist['CFBundleVersion'])
            else:
                output.write('No Version Found')
            output.write('\n')

output.close()
コード例 #32
0
    def ReadPlist(path_or_file, deserialize=False):
        '''
            Safely open and read a plist.
            Returns a tuple (True/False, plist/None, "error_message")
        '''
        #log.debug("Trying to open plist file : " + path)
        error = ''
        path = ''
        plist = None
        f = None
        if isinstance(path_or_file, str):
            path = path_or_file
            try:
                f = open(path, 'rb')
            except OSError as ex:
                error = 'Could not open file, Error was : ' + str(ex)
        else:  # its a file
            f = path_or_file

        if f:
            if deserialize:
                try:
                    plist = nd.deserialize_plist(f)
                    f.close()
                    return (True, plist, '')
                except (nd.DeserializeError,
                        nd.biplist.NotBinaryPlistException,
                        nd.biplist.InvalidPlistException,
                        plistlib.InvalidFileException,
                        nd.ccl_bplist.BplistError, ValueError, TypeError,
                        OSError, OverflowError) as ex:
                    error = 'Error deserializing plist: ' + path + " Error was : " + str(
                        ex)
                    f.close()
                    return (False, plist, error)
            else:
                try:
                    if sys.version_info >= (3, 9):
                        plist = plistlib.load(f)
                    else:
                        plist = biplist.readPlist(f)
                    return (True, plist, '')
                except (biplist.InvalidPlistException,
                        plistlib.InvalidFileException) as ex:
                    try:
                        # Check for XML format
                        f.seek(0)
                        file_start_bytes = f.read(10)
                        if file_start_bytes.find(b'?xml') > 0:
                            # Perhaps this is manually edited or incorrectly formatted
                            # that has left whitespaces at the start of file before <?xml tag
                            # Or it's a bigSur (11.0) plist with hex integers
                            f.seek(0)
                            data = f.read().decode('utf8', 'ignore')
                            f.close()
                            data = CommonFunctions.replace_all_hex_int_with_int(
                                data)  # Fix for BigSur plists with hex ints
                            data = data.lstrip(" \r\n\t").encode(
                                'utf8', 'backslashreplace')

                            if sys.version_info >= (3, 9):
                                plist = plistlib.loads(data,
                                                       fmt=plistlib.FMT_XML)
                            else:
                                plist = biplist.readPlistFromString(data)
                            return (True, plist, '')
                        else:
                            error = 'Not a plist! ' + path + " Error was : " + str(
                                ex)
                    except (biplist.InvalidPlistException, ValueError,
                            plistlib.InvalidFileException) as ex:
                        error = 'Could not read plist: ' + path + " Error was : " + str(
                            ex)
        return (False, None, error)
コード例 #33
0
 def post(self):
     plist = readPlist(StringIO(self.request.body))
     self.set_header("Content-type", "text/plain")
     self.write(plist["lastUserName"])
コード例 #34
0
    def _sign_app(self,
                  build,
                  provisioning_profile,
                  entitlements_file,
                  certificate=None,
                  certificate_path=None,
                  certificate_password=None):
        app_folder_name = self._locate_ios_app(
            error_message="Couldn't find iOS app in order to sign it")
        path_to_app = path.abspath(
            path.join(self.path_to_ios_build, 'ios', app_folder_name))

        embedded_profile = 'embedded.mobileprovision'
        path_to_embedded_profile = path.abspath(
            path.join(path_to_app, embedded_profile))

        path_to_pp = path.join(build.orig_wd, provisioning_profile)
        if not path.isfile(path_to_pp):
            self._missing_provisioning_profile(build, path_to_pp)

        try:
            os.remove(path_to_embedded_profile)
        except Exception:
            LOG.warning("Couldn't remove {profile}".format(
                profile=path_to_embedded_profile))
        shutil.copy2(path_to_pp, path_to_embedded_profile)

        if not sys.platform.startswith('darwin'):
            if not certificate_path:
                lib.local_config_problem(
                    build,
                    message="To deploy iOS apps to a device, you must specify a "
                    "path to a certificate to sign with.",
                    examples={
                        "ios.profiles.DEFAULT.developer_certificate_path":
                        path.abspath("/Users/Bob/certificate.pfx")
                    },
                    more_info=
                    "http://current-docs.trigger.io/tools/ios-windows.html")

            if not certificate_password:
                lib.local_config_problem(
                    build,
                    message="To deploy iOS apps to a device, you must specify a "
                    "path the password to unlock your certificate.",
                    examples={
                        "ios.profiles.DEFAULT.developer_certificate_password":
                        "******"
                    },
                    more_info=
                    "http://current-docs.trigger.io/tools/ios-windows.html")

            cache_file = None
            development_certificate = False
            try:
                cert_name = subprocess.check_output([
                    'java', '-jar',
                    ensure_lib_available(build, 'p12name.jar'),
                    certificate_path, certificate_password
                ]).strip()
                if cert_name.startswith('iPhone Developer:'):
                    development_certificate = True
            except Exception:
                pass

            if development_certificate:
                # Development certificate signings can be cached
                # Hash for Forge binary + signing certificate + profile + info.plist
                h = hashlib.sha1()
                with open(path.join(path_to_app, 'Forge'),
                          'rb') as binary_file:
                    h.update(binary_file.read())
                with open(path.join(path_to_app, 'Info.plist'),
                          'rb') as info_plist_file:
                    h.update(info_plist_file.read())
                with open(certificate_path, 'rb') as certificate_file:
                    h.update(certificate_file.read())
                with open(path_to_embedded_profile, 'rb') as embedded_file:
                    h.update(embedded_file.read())

                if not path.exists(
                        path.abspath(
                            path.join(self.path_to_ios_build, '..',
                                      '.template', 'ios-signing-cache'))):
                    os.makedirs(
                        path.abspath(
                            path.join(self.path_to_ios_build, '..',
                                      '.template', 'ios-signing-cache')))
                cache_file = path.abspath(
                    path.join(self.path_to_ios_build, '..', '.template',
                              'ios-signing-cache', h.hexdigest()))

            # XXX: Currently cache file is never saved, see below.
            if cache_file is not None and path.exists(cache_file):
                with temp_file() as resource_rules_temp:
                    shutil.copy2(path.join(path_to_app, 'ResourceRules.plist'),
                                 resource_rules_temp)
                    zip_to_extract = ZipFile(cache_file)
                    zip_to_extract.extractall(path_to_app)
                    zip_to_extract.close()
                    shutil.copy2(resource_rules_temp,
                                 path.join(path_to_app, 'ResourceRules.plist'))
                return

            # Remote
            LOG.info(
                'Sending app to remote server for codesigning. Uploading may take some time.'
            )

            # Zip up app
            with temp_file() as app_zip_file:
                if cache_file is None:
                    with ZipFile(app_zip_file, 'w',
                                 compression=ZIP_DEFLATED) as app_zip:
                        for root, dirs, files in os.walk(path_to_app,
                                                         topdown=False):
                            for file in files:
                                app_zip.write(
                                    path.join(root, file),
                                    path.join(root[len(path_to_app):], file))
                                os.remove(path.join(root, file))
                            for dir in dirs:
                                os.rmdir(path.join(root, dir))
                else:
                    with ZipFile(app_zip_file, 'w',
                                 compression=ZIP_DEFLATED) as app_zip:
                        app_zip.write(path.join(path_to_app, 'Forge'), 'Forge')
                        app_zip.write(path.join(path_to_app, 'Info.plist'),
                                      'Info.plist')
                        app_zip.write(path_to_embedded_profile,
                                      'embedded.mobileprovision')
                        with temp_file() as tweaked_resource_rules:
                            import biplist
                            rules = biplist.readPlist(
                                path.join(path_to_app, 'ResourceRules.plist'))
                            # Don't sign anything
                            rules['rules']['.*'] = False
                            with open(tweaked_resource_rules,
                                      'wb') as tweaked_resource_rules_file:
                                biplist.writePlist(
                                    rules, tweaked_resource_rules_file)
                            app_zip.write(tweaked_resource_rules,
                                          'ResourceRules.plist')

                from poster.encode import multipart_encode
                from poster.streaminghttp import register_openers
                import urllib2

                class FileWithProgress:
                    def __init__(self, path, flags):
                        self.total_size = os.path.getsize(path)
                        self.file = open(path, flags)
                        self.name = self.file.name
                        self.path = path
                        self.amount_read = 0
                        self.last_progress = 0

                    def read(self, length):
                        data = self.file.read(length)
                        if data != "":
                            self.amount_read = self.amount_read + len(data)
                            # TODO: Nicer progress output
                            progress = 10 * self.amount_read / self.total_size
                            if progress > self.last_progress:
                                self.last_progress = progress
                                LOG.info(
                                    str(10 * progress) +
                                    " percent uploaded: " + self.path)
                        else:
                            self.file.close()
                        return data

                    def fileno(self):
                        return self.file.fileno()

                    def seek(self, pos):
                        return self.file.seek(pos)

                files = {
                    'app': FileWithProgress(app_zip_file, 'rb'),
                    'entitlements': FileWithProgress(entitlements_file, 'rb'),
                    'certificate': FileWithProgress(certificate_path, 'rb'),
                    'password': certificate_password
                }

                # Register the streaming http handlers with urllib2
                register_openers()

                # headers contains the necessary Content-Type and Content-Length
                # datagen is a generator object that yields the encoded parameters
                datagen, headers = multipart_encode(files)

                # Create the Request object
                request = urllib2.Request("https://trigger.io/codesign/sign",
                                          datagen, headers)

                with temp_file() as signed_zip_file:
                    resp = urllib2.urlopen(request)

                    # Read the log lines from the start of the response
                    while True:
                        data = resp.readline()
                        if data == "--failure\n":
                            raise IOSError("Remote codesign failed")
                        elif data == "--data\n" or data == "":
                            break
                        LOG.info(data.rstrip('\r\n'))

                    # Read the binary data from the 2nd part of the response
                    # TODO: Chunked download and progress
                    with open(signed_zip_file, 'wb') as signed_zip:
                        signed_zip.write(resp.read())

                    # Unzip response
                    zip_to_extract = ZipFile(signed_zip_file)
                    zip_to_extract.extractall(path_to_app)
                    zip_to_extract.close()

                    # XXX: Caching currently disabled as Info.plist changes on every build
                    """if cache_file is not None:
						shutil.copy2(signed_zip_file, cache_file)"""
                    LOG.info('Signed app received, continuing with packaging.')

        else:
            # Local
            codesign = self._check_for_codesign()
            resource_rules = path.abspath(
                path.join(path_to_app, 'ResourceRules.plist'))
            run_shell(codesign, '--force', '--preserve-metadata',
                      '--entitlements', entitlements_file, '--sign',
                      certificate,
                      '--resource-rules={0}'.format(resource_rules),
                      path_to_app)
コード例 #35
0
ファイル: applicationstate.py プロジェクト: ydkhatri/iLEAPP
def get_applicationstate(files_found, report_folder, seeker):
    file_found = str(files_found[0])
    db = open_sqlite_db_readonly(file_found)
    cursor = db.cursor()
    cursor.execute('''
    select ait.application_identifier as ai, kvs.value as compat_info,
    (SELECT kvs.value from kvs left join application_identifier_tab on application_identifier_tab.id = kvs.application_identifier
    left join key_tab on kvs.key = key_tab.id  
    WHERE key_tab.key='XBApplicationSnapshotManifest' and kvs.key = key_tab.id
    and application_identifier_tab.id = ait.id
    ) as snap_info
    from kvs 
    left join application_identifier_tab ait on ait.id = kvs.application_identifier
    left join key_tab on kvs.key = key_tab.id 
    where key_tab.key='compatibilityInfo' 
    order by ait.id
    ''')

    all_rows = cursor.fetchall()
    usageentries = len(all_rows)
    if usageentries > 0:
        data_list = []
        snap_info_list = []
        for row in all_rows:
            bundleid = str(row[0])
            plist_file_object = io.BytesIO(row[1])
            if row[1].find(b'NSKeyedArchiver') == -1:
                if sys.version_info >= (3, 9):
                    plist = plistlib.load(plist_file_object)
                else:
                    plist = biplist.readPlist(plist_file_object)
            else:
                try:
                    plist = nd.deserialize_plist(plist_file_object)
                except (nd.DeserializeError,
                        nd.biplist.NotBinaryPlistException,
                        nd.biplist.InvalidPlistException,
                        nd.plistlib.InvalidFileException,
                        nd.ccl_bplist.BplistError, ValueError, TypeError,
                        OSError, OverflowError) as ex:
                    logfunc(f'Failed to read plist for {row[0]}, error was:' +
                            str(ex))
            if plist:
                if type(plist) is dict:
                    var1 = plist.get('bundleIdentifier', '')
                    var2 = plist.get('bundlePath', '')
                    var3 = plist.get('sandboxPath', '')
                    data_list.append((var1, var2, var3))
                    if row[2]:
                        snap_info_list.append((var1, var2, var3, row[2]))
                else:
                    logfunc(f'For {row[0]} Unexpected type "' +
                            str(type(plist)) +
                            '" found as plist root, can\'t process')
            else:
                logfunc(f'For {row[0]}, plist could not be read!')
        report = ArtifactHtmlReport('Application State')
        report.start_artifact_report(report_folder, 'Application State DB')
        report.add_script()
        data_headers = ('Bundle ID', 'Bundle Path', 'Sandbox Path')
        report.write_artifact_data_table(data_headers, data_list, file_found)
        report.end_artifact_report()

        tsvname = 'Application State'
        tsv(report_folder, data_headers, data_list, tsvname)
    else:
        logfunc('No Application State data available')

    db.close()
    return
コード例 #36
0
ファイル: app.py プロジェクト: anantgarg/orchardlab
        def generate():
            # Checkout the branch, fetch new commits and update submodules
            git = sh.git.bake(_cwd=wd)
            yield (x for x in [chr(127) * 1024 + '\nChecking out branch...\n'])
            yield git.checkout('-B',
                               branch,
                               '-t',
                               'origin/' + branch,
                               _iter=True,
                               _out_bufsize=0)
            yield (x for x in ['Pulling from remote repository...\n'])
            yield git.pull('--ff-only', _iter=True)
            yield (x for x in ['Updating submodules...\n'])
            yield git.submodule('update', '--init', _iter=True, _out_bufsize=0)

            # Do the build!
            yield (x for x in ['Starting build...\n'])
            xcodebuild = sh.xcodebuild.bake(_cwd=wd)
            yield xcodebuild.build('-configuration',
                                   'Debug',
                                   '-arch',
                                   'armv7',
                                   '-sdk',
                                   'iphoneos',
                                   _iter=True,
                                   _out_bufsize=0)

            # Create the output folder structure if needed
            if not os.path.exists(output):
                os.makedirs(output)

            # Get the .app in the build output folder
            app_path = os.path.join(
                wd,
                glob.glob(os.path.join(wd, 'build/Debug-iphoneos/*.app'))[0])

            # Package the .app to .ipa
            xcrun = sh.xcrun.bake(_cwd=wd)
            yield (x for x in ['Compiling app...\n'])
            yield xcrun('-sdk',
                        'iphoneos',
                        'PackageApplication',
                        app_path,
                        '-o',
                        os.path.join(output, 'application.ipa'),
                        _iter=True,
                        _out_bufsize=0)

            # Write the .plist we'll need for downloading later
            yield (x for x in ['Writing plist...\n'])
            plist = biplist.readPlist(os.path.join(app_path, 'Info.plist'))
            data = {
                'items': [{
                    'assets': [{
                        'kind':
                        'software-package',
                        'url':
                        urlparse.urljoin(cherrypy.url(), 'application.ipa'),
                    }],
                    'metadata': {
                        'kind': 'software',
                        'bundle-identifier': plist['CFBundleIdentifier'],
                        'title': plist['CFBundleName']
                    }
                }]
            }
            biplist.writePlist(data,
                               os.path.join(output, 'application.plist'),
                               binary=False)

            yield (x for x in ['Done!\n'])
コード例 #37
0
ファイル: plistparser.py プロジェクト: ydkhatri/plistutils
 def _read_binary_plist(cls, file_obj):
     try:
         return biplist.readPlist(file_obj)
     except biplist.InvalidPlistException as e:
         raise InvalidPlistException(e)
コード例 #38
0
    """Add icons to App"""
    app_content_path = os.getenv("APP_CONTENT_PATH")
    if app_content_path == None:
        raise ValueError("No `APP_CONTENT_PATH` Environment Variable")
    if not os.path.exists(app_content_path):
        raise ValueError("%s not Exists" % app_content_path)
    print("Move App icons from: `%s` to `%s`" % (output_dir, app_content_path))
    move_icons_to_directory(output_dir, app_content_path)
    print("Add App Icon Success")
    """Edit Info.plist"""
    primary_icon_name = os.getenv("PRIMARY_ICON_NAME")
    plist_file_path = os.path.join(app_content_path, "Info.plist")
    if not os.path.exists(plist_file_path):
        raise ValueError("%s not Exists" % plist_file_path)
    print("Edit Info.plist: ", plist_file_path)
    plist_info = biplist.readPlist(plist_file_path)
    iPhoneOldCFBundlePrimaryIcon = plist_info["CFBundleIcons"][
        "CFBundlePrimaryIcon"]
    (iPhone_key, iPhone_value) = getCFBundleIcons(
        names,
        primary_icon_name,
        oldPrimaryInfo=iPhoneOldCFBundlePrimaryIcon,
        is_iPhone=True)
    plist_info[iPhone_key] = iPhone_value

    if plist_info.__contains__("CFBundleIcons~ipad"):
        iPadOldCFBundlePrimaryIcon = plist_info["CFBundleIcons~ipad"][
            "CFBundlePrimaryIcon"]
        (iPad_key, iPad_value) = getCFBundleIcons(
            names,
            primary_icon_name,
コード例 #39
0
 def __init__(self, filename):
     self.m_data = biplist.readPlist(filename)
コード例 #40
0
# 提供面向对象的API用于处理系统路径
import pathlib
# plist操作模块
import biplist


path = pathlib.Path.home()
path = path / 'Library/Developer/CoreSimulator/Devices'
print(path)

g = path.glob('*')
print('共%d个文件/文件夹' % len(list(g)))

# 固定宽度输出
# 当指定宽度小于所需宽度时:按所需宽度显示
mat = '{:^40}\t{:1}'

for f in path.glob('*'):
    if f.is_dir():
        plist = biplist.readPlist(str(f / 'device.plist'))
        print(mat.format(plist['name'], plist['runtime']))
コード例 #41
0
 def read_plist(path):
     return biplist.readPlist(path)
コード例 #42
0
                   + '</div><div class="code">' \
                   + map[key] \
                   + '</div></div>'

    for key in map:
        value = map[key]
        if isinstance(value, dict):
            strs += '<div class="col-md-12 group-title h3">' + key + '</div>'
            strs += dictToHtml(value)
            continue

    return strs


plistfilepath = sys.argv[1]
map = readPlist(plistfilepath)

file = open("iconfont.html", "w+")
file.write('''
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

    <title>Hello, world!</title>
コード例 #43
0
import sys
import io
import math
import zipfile
from biplist import readPlist
import lzo
from PIL import Image
from multiprocessing import Pool


procreatefile = sys.argv[-1]
zipref = zipfile.ZipFile(procreatefile, 'r')

plistdata = zipref.read('Document.archive')
plistbytes = io.BytesIO(plistdata)
plist = readPlist(plistbytes)
objects = plist.get('$objects')
composite_number = objects[1].get('composite').integer
composite_key_number = objects[composite_number].get('UUID').integer
composite_key = objects[composite_key_number]

allfiles = zipref.namelist()
composite_files = list(filter(lambda x: composite_key in x, allfiles))
filelist = list(map(lambda x: x.strip(composite_key).strip('/'), composite_files))

imagesize_string = objects[objects[1].get('size').integer]
imagesize = imagesize_string.strip('{').strip('}').split(', ')
imagesize[0] = int(imagesize[0])
imagesize[1] = int(imagesize[1])
tilesize = objects[1].get('tileSize')
orientation = objects[1].get('orientation')
コード例 #44
0
ファイル: characterization.py プロジェクト: XorgX304/rvt2
    def run(self, path):
        """
        Parameters:
            path (str): The path to the directory where the backup was unbacked.

        Returns:
            An array of a dictionary with the extracted documentation
        """
        self.logger().debug('Parsing: %s', path)
        self.check_params(path, check_path=True, check_path_exists=True)

        if not base.utils.check_file(os.path.join(path, 'Manifest.plist')):
            raise base.job.RVTError(
                'Manifest.plist not found. Is the source a (decrypted) iOS backup?'
            )

        data = dict()
        manifest = biplist.readPlist(os.path.join(path, 'Manifest.plist'))
        data['Version'] = manifest.get('Version', 'None')
        data['IsEncrypted'] = manifest.get('IsEncrypted', 'None')
        data['LastBackupDate'] = manifest.get('Date', 'None')
        if 'Lockdown' in manifest:
            data['DeviceName'] = manifest['Lockdown'].get('DeviceName', 'None')
            data['UniqueDeviceID'] = manifest['Lockdown'].get(
                'UniqueDeviceID', 'None')
            data['SerialNumber'] = manifest['Lockdown'].get(
                'SerialNumber', 'None')
            data['ProductVersion'] = manifest['Lockdown'].get(
                'ProductVersion', 'None')
            data['ProductType'] = manifest['Lockdown'].get(
                'ProductType', 'None')
            data['BuildVersion'] = manifest['Lockdown'].get(
                'BuildVersion', 'None')
        data['WasPasscodeSet'] = manifest.get('WasPasscodeSet', 'None')

        info = biplist.readPlist(os.path.join(path, 'Info.plist'))
        data['GUID'] = info.get('GUID', 'None')
        data['ICCID'] = info.get('ICCID', 'None')
        data['PhoneNumber'] = info.get('Phone Number', 'None')
        data['MEID'] = info.get('MEID', 'None')
        # check some data, they must be the same
        if 'Lockdown' in manifest:
            assert data['UniqueDeviceID'] == info['Target Identifier']
            assert data['UniqueDeviceID'] == info['Target Identifier'].lower()
            assert data['DeviceName'] == info['Device Name']
            assert data['DeviceName'] == info['Display Name']
            assert data['ProductVersion'] == info['Product Version']
            assert data['BuildVersion'] == info['Build Version']

        status = biplist.readPlist(os.path.join(path, 'Status.plist'))
        data['UUID'] = status['UUID']

        conn = sqlite3.connect(
            'file://{}/HomeDomain/Library/Accounts/Accounts3.sqlite?mode=ro'.
            format(path),
            uri=True)
        c = conn.cursor()
        for row in c.execute('SELECT * FROM ZACCOUNT'):
            if row[7] is not None:
                switcher = {
                    33: "iCloud Account",
                    27: "Hotmail Account",
                    38: "Jabber Account",
                    16: "Gmail Account",
                    13: "Yahoo Account",
                    11: "Facebook Account",
                    10: "LinkedIn Account",
                    4: "Twitter Account",
                    8: "Flickr Account",
                }
                tmp = switcher.get(row[7], "nothing")
                if tmp != "nothing":
                    data[tmp] = row[16]

        base.utils.check_file(self.myconfig('outfile'),
                              delete_exists=True,
                              create_parent=True)
        with open(self.myconfig('outfile'), "w") as outfile:
            writer = csv.writer(outfile)
            writer.writerow(("Characteristic", "Value"))
            for k, v in data.items():
                writer.writerow([k, v])

        self.logger().info("iPhone's characterization exported at %s",
                           self.myconfig('outfile'))

        return [data]
コード例 #45
0
ファイル: macuser.py プロジェクト: x35029/plaso
    def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
        """Extracts relevant user timestamp entries.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS.
    """
        if 'name' not in match or 'uid' not in match:
            return

        account = match['name'][0]
        uid = match['uid'][0]

        for policy in match.get('passwordpolicyoptions', []):
            try:
                xml_policy = ElementTree.fromstring(policy)
            except (ElementTree.ParseError, LookupError) as exception:
                logger.error((
                    'Unable to parse XML structure for an user policy, account: '
                    '{0:s} and uid: {1!s}, with error: {2!s}').format(
                        account, uid, exception))
                continue

            for dict_elements in xml_policy.iterfind('dict'):
                key_values = [value.text for value in iter(dict_elements)]
                # Taking a list and converting it to a dict, using every other item
                # as the key and the other one as the value.
                policy_dict = dict(zip(key_values[0::2], key_values[1::2]))

            time_string = policy_dict.get('passwordLastSetTime', None)
            if time_string and time_string != '2001-01-01T00:00:00Z':
                try:
                    date_time = dfdatetime_time_elements.TimeElements()
                    date_time.CopyFromStringISO8601(time_string)
                except ValueError:
                    date_time = None
                    parser_mediator.ProduceExtractionWarning(
                        'unable to parse password last set time string: {0:s}'.
                        format(time_string))

                shadow_hash_data = match.get('ShadowHashData', None)
                if date_time and isinstance(shadow_hash_data, (list, tuple)):
                    # Extract the hash password information.
                    # It is store in the attribute ShadowHasData which is
                    # a binary plist data; However biplist only extracts one
                    # level of binary plist, then it returns this information
                    # as a string.

                    # TODO: change this into a DataRange instead. For this we
                    # need the file offset and size of the ShadowHashData value data.
                    shadow_hash_data = shadow_hash_data[0]

                    resolver_context = context.Context()
                    fake_file = fake_file_io.FakeFile(resolver_context,
                                                      shadow_hash_data)
                    shadow_hash_data_path_spec = fake_path_spec.FakePathSpec(
                        location='ShadowHashData')
                    fake_file.open(path_spec=shadow_hash_data_path_spec)

                    try:
                        plist_file = biplist.readPlist(fake_file)
                    except biplist.InvalidPlistException:
                        plist_file = {}
                    salted_hash = plist_file.get('SALTED-SHA512-PBKDF2', None)
                    if salted_hash:
                        salt_hex_bytes = codecs.encode(salted_hash['salt'],
                                                       'hex')
                        salt_string = codecs.decode(salt_hex_bytes, 'ascii')
                        entropy_hex_bytes = codecs.encode(
                            salted_hash['entropy'], 'hex')
                        entropy_string = codecs.decode(entropy_hex_bytes,
                                                       'ascii')
                        password_hash = '$ml${0:d}${1:s}${2:s}'.format(
                            salted_hash['iterations'], salt_string,
                            entropy_string)
                    else:
                        password_hash = 'N/A'

                    event_data = plist_event.PlistTimeEventData()
                    event_data.desc = (
                        'Last time {0:s} ({1!s}) changed the password: {2!s}'
                    ).format(account, uid, password_hash)
                    event_data.key = 'passwordLastSetTime'
                    event_data.root = self._ROOT

                    event = time_events.DateTimeValuesEvent(
                        date_time, definitions.TIME_DESCRIPTION_WRITTEN)
                    parser_mediator.ProduceEventWithEventData(
                        event, event_data)

            time_string = policy_dict.get('lastLoginTimestamp', None)
            if time_string and time_string != '2001-01-01T00:00:00Z':
                try:
                    date_time = dfdatetime_time_elements.TimeElements()
                    date_time.CopyFromStringISO8601(time_string)
                except ValueError:
                    date_time = None
                    parser_mediator.ProduceExtractionWarning(
                        'unable to parse last login time string: {0:s}'.format(
                            time_string))

                if date_time:
                    event_data = plist_event.PlistTimeEventData()
                    event_data.desc = 'Last login from {0:s} ({1!s})'.format(
                        account, uid)
                    event_data.key = 'lastLoginTimestamp'
                    event_data.root = self._ROOT

                    event = time_events.DateTimeValuesEvent(
                        date_time, definitions.TIME_DESCRIPTION_WRITTEN)
                    parser_mediator.ProduceEventWithEventData(
                        event, event_data)

            time_string = policy_dict.get('failedLoginTimestamp', None)
            if time_string and time_string != '2001-01-01T00:00:00Z':
                try:
                    date_time = dfdatetime_time_elements.TimeElements()
                    date_time.CopyFromStringISO8601(time_string)
                except ValueError:
                    date_time = None
                    parser_mediator.ProduceExtractionWarning(
                        'unable to parse failed login time string: {0:s}'.
                        format(time_string))

                if date_time:
                    event_data = plist_event.PlistTimeEventData()
                    event_data.desc = (
                        'Last failed login from {0:s} ({1!s}) ({2!s} times)'
                    ).format(account, uid,
                             policy_dict.get('failedLoginCount', 0))
                    event_data.key = 'failedLoginTimestamp'
                    event_data.root = self._ROOT

                    event = time_events.DateTimeValuesEvent(
                        date_time, definitions.TIME_DESCRIPTION_WRITTEN)
                    parser_mediator.ProduceEventWithEventData(
                        event, event_data)
コード例 #46
0
#!/usr/bin/env python

import biplist
import sys

if len(sys.argv) < 3:
    print "Usage: plistget.py <plist file> <property>"
    sys.exit(1)

pl = biplist.readPlist(sys.argv[1])

print pl[sys.argv[2]]

コード例 #47
0
 def _plist_from_bin(self, data):
     f = BytesIO(data)
     return readPlist(f)
コード例 #48
0
def get_folder_images(folder_from, plist_images, plist_path, quiet):
    image_refers = plist_images
    warn = 0
    ref = 0
    yes_to_all = quiet or False
    plist_name = os.path.basename(plist_path)

    # fill image_refers
    for root, dirs, files in os.walk(folder_from):
        for fn in files:
            if fn.lower().endswith('.png'):
                img_path = os.path.join(root, fn)

                in_plist = False
                ref_key = ''
                for rk in plist_images:
                    n = plist_images[rk]
                    if img_path.endswith(n['name']):
                        ref_key = rk
                        in_plist = True
                        break

                if not in_plist:
                    log.warn(fn + ' in [ ' + root + ' ] not in plist')
                    print()
                    warn += 1
                    continue

                j = json.load(open(img_path + '.meta'))
                k = fn[:-4]  # .png len
                meta = j['subMetas'][k]

                log.head('will replace png named [ ' + fn + ' ] reference [ ' +
                         img_path + ' ] with plist')

                do = None
                if not yes_to_all:
                    log.fail('return to continue, n/N to skip, A yes to all')
                    do = input()

                if do is not None and do.strip().startswith('A'):
                    yes_to_all = True

                if yes_to_all or (not do.strip().startswith('n')):
                    if image_refers[ref_key].get('ref', None) is None:
                        image_refers[ref_key]['ref'] = []
                    image_refers[ref_key]['ref'].append({
                        'path':
                        img_path,
                        'name':
                        ref_key,
                        'uuid':
                        meta['uuid'],
                        'rawTextureUuid':
                        meta['rawTextureUuid']
                    })

                ref += 1

            elif fn.lower().endswith('.plist'):
                plist_path = os.path.join(root, fn)

                try:
                    plist = biplist.readPlist(plist_path)
                except:
                    plist = None
                    log.fail("read plist failed: " + str(sys.exc_info()[0]))

                j = json.load(open(plist_path + '.meta'))
                plist_meta = j['subMetas']
                for k in plist['frames'].keys():
                    if plist_meta.get(k, None) is not None:
                        meta = plist_meta[k]
                    else:
                        meta = plist_meta[str(k).replace('/', '-')]

                    in_plist = False
                    ref_key = ''
                    for rk in plist_images:
                        n = plist_images[rk]
                        if k.endswith(n['name']):
                            ref_key = rk
                            in_plist = True
                            break

                    if not in_plist:
                        log.warn(k + ' in [ ' + plist_path + ' ] not in plist')
                        print()
                        warn += 1
                        continue

                    log.head('will replace png named [ ' + k +
                             ' ] reference [ ' + plist_path + ' ] with plist')

                    do = None
                    if not yes_to_all:
                        log.fail(
                            'return to continue, n/N to skip, A yes to all')
                        do = input()

                    if do is not None and do.strip().startswith('A'):
                        yes_to_all = True

                    if yes_to_all or (not do.strip().startswith('n')):
                        if image_refers[ref_key].get('ref', None) is None:
                            image_refers[ref_key]['ref'] = []
                        image_refers[ref_key]['ref'].append({
                            'path':
                            plist_path,
                            'name':
                            ref_key,
                            'uuid':
                            meta['uuid'],
                            'rawTextureUuid':
                            meta['rawTextureUuid']
                        })

                        if image_refers[plist_name].get('ref', None) is None:
                            image_refers[plist_name]['ref'] = []
                        has = False
                        for x in image_refers[plist_name]['ref']:
                            if x['uuid'] == j['uuid']:
                                has = True
                                break
                        if not has:
                            image_refers[plist_name]['ref'].append({
                                'path':
                                plist_path,
                                'name':
                                fn,
                                'uuid':
                                j['uuid'],
                                'rawTextureUuid':
                                j['rawTextureUuid']
                            })

                    ref += 1

    return image_refers, warn, ref
コード例 #49
0
def make_entitlements(app_dir, distribution):
    entitlements = {}
    try:
        info_plist = readPlist(os.path.join(app_dir, "Info.plist"))
        app_id = info_plist['CFBundleIdentifier']
        message("Processing %s" % app_id)
        executable = info_plist['CFBundleExecutable']
    except (KeyError, IOError, ExpatError):
        error(
            "Unable to obtain CFBundleIdentifier/CFBundleExecutable from Info.plist"
        )

    basename = os.path.basename(app_dir)
    basename = os.path.splitext(basename)[0]
    if executable != basename:
        error("CFBundleExecutable (%s) must be the same as the .app (%s)" %
              (executable, basename))

    executable = join(app_dir, executable)
    if not os.path.exists(executable):
        error("CFBundleExecutable (%s) does not exist" % (executable))

    make_executable(executable)

    provisioning_profile_file = os.path.join(app_dir,
                                             "embedded.mobileprovision")
    if not os.path.exists(provisioning_profile_file):
        if parent_provisioningprofile:
            message(parent_provisioningprofile)
            provisioning_profile_file = parent_provisioningprofile
    if not os.path.exists(provisioning_profile_file):
        error('Unable to sign without specifying a valid provisioning profile')

    try:
        # provisioning profile is a binary file with embedded .plist xml. Need to find the xml inside the binary before parsing.
        PLIST_START = '<?xml'
        PLIST_END = '</plist>'
        with open(provisioning_profile_file, "rb") as fp:
            data = fp.read()
        xml = data[data.find(PLIST_START):data.find(PLIST_END) +
                   len(PLIST_END)]
        provisioning_profile = readPlistFromString(xml)
    except (IOError, ExpatError):
        error("Invalid mobile provisioning file %s " %
              provisioning_profile_file)

    try:
        profile_uid = provisioning_profile['ApplicationIdentifierPrefix'][0]
    except (KeyError, IndexError, IOError):
        error(
            "Failed to find ApplicationIdentifierPrefix in provisioning profile"
        )

    try:
        profile_entitlements = provisioning_profile['Entitlements']
        application_id = profile_entitlements['application-identifier']
    except KeyError:
        error("Failed to find ApplicationIdentifier in provisioning profile")

    if ".*" in application_id:
        message("Using wildcard provisioning profile")
    elif not application_id.endswith(app_id):
        error(
            "App ID in Info.plist is '%s' but provisioning profile is for '%s'"
            % (app_id, application_id))
    else:
        message("Provisioning profile is for: %s" % application_id)

    if profile_entitlements.get('aps-environment'):
        message("Using push notification environment: %s" %
                profile_entitlements['aps-environment'])

    # Copy entitlements from the provisioning profile
    entitlements.update(profile_entitlements)

    # Update bundle id (as it could be different when using a wildcard provisioning profile)
    bundle_id = '%s.%s' % (profile_uid, app_id)
    entitlements['application-identifier'] = bundle_id
    entitlements['keychain-access-groups'] = [bundle_id]

    return entitlements
コード例 #50
0
 def readPlistFromString(self, data):
     return readPlist(StringIO(data))
コード例 #51
0
def analyzing_ipa(file_path, vol_id):
    ItemInfo = namedtuple(
        'ItemInfo',
        ['package_name',
         'version_code',
         'min_sdk_version',
         'version_name',
         'apk_size',
         'screen_support',
         'is_break',
         'file_type',
         'platform'])
    sig = 'ipa'
    zf = zipfile.ZipFile(file_path)
    is_break = 1
    for f in zf.namelist():
        if f.endswith('.app/Info.plist'):
            tmp_file = f
            zf.extract(f)
        elif '.app/SC_Info' in f:
            is_break = 0
    zf.extract('iTunesMetadata.plist')
    itunes = biplist.readPlist('iTunesMetadata.plist')
    apple_id = itunes['appleId']
    if '@' in apple_id:
        itunes['appleId'] = md5(itunes['appleId']).hexdigest().upper()
    ipainfo = {'appleId': itunes['appleId']}
    biplist.writePlist(ipainfo, 'ipainfo.plist')
    biplist.writePlist(itunes, 'iTunesMetadata.plist')
    root = biplist.readPlist(tmp_file)
    os.popen('sudo rm -r ./Payload')
    source = 'itunes.apple.com'
    app_id = itunes.get('itemId')
    source_link = get_source_link(app_id, apple_id)
    if not source_link:
        return
    download_link = source_link
    app_name = itunes.get('itemName')
    apk_size = os.stat(file_path).st_size
    min_sdk_version = (root.get('MinimumOSVersion').replace('.', '') + '0000')[:4]
    file_type = 'ipa'
    package_name = root.get('CFBundleIdentifier')
    screen_support = 0
#    print itunes
    for i in root.get('UIDeviceFamily'):
        screen_support += int(i)
    if screen_support == 1:
        platform = 4
    elif screen_support == 2:
        platform = 8
    elif screen_support == 3:
        platform = 12
    if isinstance(root.get('CFBundleVersion'), str) and '.' in root.get('CFBundleVersion') and root.get('CFBundleVersion').replace('.', '').isdigit():
        version_name = root.get('CFBundleVersion')
    elif isinstance(root.get('CFBundleShortVersionString'), str) and root.get('CFBundleShortVersionString').replace('.', '').isdigit():
        version_name = root.get('CFBundleShortVersionString')
    else:
        version_name = root.get('CFBundleVersion')
    i = 0
    version_code = 0
    if '.' not in version_name:
        version_code = int(version_name)
    else:
        for v in version_name.split('.'):
            if i == 0:
                v = v[:5]
                version_code += int(v) << 50
            elif i < 4:
                v = v[:4]
                version_code += int(v) << 50 - i * 12
            elif i == 4:
                v = v[:5]
                version_code += int(v)
            if i > 4:
                break
            i += 1
    # print source_link,app_id
    item = ItemInfo(package_name=package_name,
                    version_code=int(version_code) if version_code else 0,
                    version_name=version_name,
                    apk_size=str(apk_size),
                    min_sdk_version=int(min_sdk_version) if min_sdk_version else 0,
                    screen_support=str(screen_support),
                    is_break=is_break,
                    file_type=file_type,
                    platform=platform)
    print item.package_name, item.version_name
    package_hash = move_ipa(file_path, vol_id, download_link)
    insert_item(item, vol_id, download_link, source, sig, package_hash)
    return item
コード例 #52
0
import biplist
import sys
import os
import re

retArray = []

if sys.platform == "darwin":
    source = biplist.readPlist(os.path.expanduser("~/Library/Preferences/com.apple.finder.plist"))
    recentDirs = source.get("FXRecentFolders", None)

    if recentDirs:
        for dic in recentDirs:
            baseName = dic["name"]

            file_bookmark = dic["file-bookmark"].decode("utf-8", "ignore")
            if not file_bookmark:
                continue

            path = re.search(r"(?<=;)/.*?%s" % baseName, file_bookmark, re.I)
            if path:
                # retArray.append(path.group())
                print("%s" % path.group())



コード例 #53
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# prettyplist.py
#
"""Pretty print the contents of a Apple (binary or plain) property list file."""

import sys
from pprint import pprint
from biplist import readPlist

plist = readPlist(sys.argv[1])
pprint(plist)
コード例 #54
0
ファイル: archive.py プロジェクト: jeffbonnes/isign
 def get_info(cls, path):
     return biplist.readPlist(cls._get_plist_path(path))
コード例 #55
0
    def Parse(self, statentry, file_object, knowledge_base):
        """Parse the Plist file."""
        _ = knowledge_base
        kwargs = {}
        try:
            kwargs["aff4path"] = file_object.urn
        except AttributeError:
            pass

        direct_copy_items = [
            "Label", "Disabled", "UserName", "GroupName", "Program",
            "StandardInPath", "StandardOutPath", "StandardErrorPath",
            "LimitLoadToSessionType", "EnableGlobbing", "EnableTransactions",
            "OnDemand", "RunAtLoad", "RootDirectory", "WorkingDirectory",
            "Umask", "TimeOut", "ExitTimeOut", "ThrottleInterval",
            "InitGroups", "StartOnMount", "StartInterval", "Debug",
            "WaitForDebugger", "Nice", "ProcessType", "AbandonProcessGroup",
            "LowPriorityIO", "LaunchOnlyOnce"
        ]

        string_array_items = [
            "LimitLoadToHosts", "LimitLoadFromHosts", "LimitLoadToSessionType",
            "ProgramArguments", "WatchPaths", "QueueDirectories"
        ]

        flag_only_items = [
            "SoftResourceLimits", "HardResourceLimits", "Sockets"
        ]

        plist = {}

        try:
            plist = biplist.readPlist(file_object)
        except (biplist.InvalidPlistException, ValueError, IOError) as e:
            plist["Label"] = "Could not parse plist: %s" % e

        # These are items that can be directly copied
        for key in direct_copy_items:
            kwargs[key] = plist.get(key)

        # These could be a string, they could be an array, we don't know and neither
        # does Apple so we check.
        for key in string_array_items:
            elements = plist.get(key)
            if isinstance(elements, string_types):
                kwargs[key] = [elements]
            else:
                kwargs[key] = elements

        # These are complex items that can appear in multiple data structures
        # so we only flag on their existence
        for key in flag_only_items:
            if plist.get(key):
                kwargs[key] = True

        if plist.get("inetdCompatability") is not None:
            kwargs["inetdCompatabilityWait"] = plist.get(
                "inetdCompatability").get("Wait")

        keepalive = plist.get("KeepAlive")
        if isinstance(keepalive, bool) or keepalive is None:
            kwargs["KeepAlive"] = keepalive
        else:
            keepalivedict = {}
            keepalivedict["SuccessfulExit"] = keepalive.get("SuccessfulExit")
            keepalivedict["NetworkState"] = keepalive.get("NetworkState")

            pathstates = keepalive.get("PathState")
            if pathstates is not None:
                keepalivedict["PathState"] = []
                for pathstate in pathstates:
                    keepalivedict["PathState"].append(
                        rdf_plist.PlistBoolDictEntry(
                            name=pathstate, value=pathstates[pathstate]))

            otherjobs = keepalive.get("OtherJobEnabled")
            if otherjobs is not None:
                keepalivedict["OtherJobEnabled"] = []
                for otherjob in otherjobs:
                    keepalivedict["OtherJobEnabled"].append(
                        rdf_plist.PlistBoolDictEntry(
                            name=otherjob, value=otherjobs[otherjob]))
            kwargs["KeepAliveDict"] = rdf_plist.LaunchdKeepAlive(
                **keepalivedict)

        envvars = plist.get("EnvironmentVariables")
        if envvars is not None:
            kwargs["EnvironmentVariables"] = []
            for envvar in envvars:
                kwargs["EnvironmentVariables"].append(
                    rdf_plist.PlistStringDictEntry(name=envvar,
                                                   value=envvars[envvar]))

        startcalendarinterval = plist.get("StartCalendarInterval")
        if startcalendarinterval is not None:
            if isinstance(startcalendarinterval, dict):
                kwargs["StartCalendarInterval"] = [
                    rdf_plist.LaunchdStartCalendarIntervalEntry(
                        Minute=startcalendarinterval.get("Minute"),
                        Hour=startcalendarinterval.get("Hour"),
                        Day=startcalendarinterval.get("Day"),
                        Weekday=startcalendarinterval.get("Weekday"),
                        Month=startcalendarinterval.get("Month"))
                ]
            else:
                kwargs["StartCalendarInterval"] = []
                for entry in startcalendarinterval:
                    kwargs["StartCalendarInterval"].append(
                        rdf_plist.LaunchdStartCalendarIntervalEntry(
                            Minute=entry.get("Minute"),
                            Hour=entry.get("Hour"),
                            Day=entry.get("Day"),
                            Weekday=entry.get("Weekday"),
                            Month=entry.get("Month")))

        yield rdf_plist.LaunchdPlist(**kwargs)
コード例 #56
0
        )
        if creation == "Y":
            os.makedirs(output_path)
            validated = True
        else:
            print("Okay, let's try again")
            validated = False
            output_path = input(
                "Please enter the location you want to save the backup: ")

#Encode password input
password = passcode.encode('utf-8')

#Open the manifest.plist and dump keybag
infile = open(manifest_file, 'rb')
manifest_plist = biplist.readPlist(infile)
keybag = Keybag(manifest_plist['BackupKeyBag'])

## Unlock keybag with password
passwordcorrect = False
keybag.unlockWithPasscode(password)

#Decrypt manifest.db
manifest_key = manifest_plist['ManifestKey'][
    4:]  #The key is everything after the first 4 bytes
db = open(manifest_db, 'rb')  #Opens Manifest.db as readable binary object
encrypted_db = db.read()
manifest_class = struct.unpack(
    '<l',
    manifest_plist['ManifestKey'][:4])[0]  #Gets manifest protection class
key = keybag.unwrapKeyForClass(manifest_class,
コード例 #57
0
    def process(self, dataSource, progressBar):

        try:
            os.mkdir(self.temporary_dir)
        except:
            pass

        progressBar.switchToIndeterminate()

        self.setup_custom_artifact_types()
        self.setup_custom_attribute_types()

        filesProcessed = 0

        files = self.file_manager.findFiles(
            dataSource, "%.plist", "%var/db/dslocal/nodes/Default/users/")

        totalNumberFiles = len(files)
        progressBar.switchToDeterminate(totalNumberFiles)

        self.log(Level.INFO,
                 "Found " + str(totalNumberFiles) + " files to process.")
        for file in files:
            self.log(Level.INFO, "Processing %s" % file.getName())

            # Check if the user pressed cancel while we were busy
            if self.context.isJobCancelled():
                return IngestModule.ProcessResult.OK

            # Copy the Plist file to a temporary directory to work with
            tmpPlistFile = self.copy_to_temp_directory(file)
            self.log(Level.INFO, "Reading %s as a plist" % tmpPlistFile)

            try:
                # Read the Plist file using biplist
                plist = readPlist(tmpPlistFile)

                # Extract all of the plist data that we can
                extractedData = self.extract_plist_data(plist)

                # Each Plist file gets a generic TSK_OS_ACCOUNT Artifact Type
                osAccountArtifact = file.newArtifact(
                    BlackboardArtifact.ARTIFACT_TYPE.TSK_OS_ACCOUNT)
                osArtifactAttributes = []

                # We can iterate over any expected attribute types and assign them to the artifact.
                for dictKey in self.osAccountAttributeTypes:
                    try:
                        osArtifactAttributes.append(
                            BlackboardAttribute(
                                self.case.getAttributeType(
                                    self.osAccountAttributeTypes[dictKey]
                                    ['attr_key']), self.moduleName,
                                extractedData[dictKey]))
                    except KeyError:
                        # Discarding the attribute type if, for whatever reason, they're not in the Plist.
                        pass

                # When we're done, go ahead and add them to the OS Account Artifact. We'll post it later.
                osAccountArtifact.addAttributes(osArtifactAttributes)

                # An account shadow can have multiple hashes (e.g. SALTED-SHA512-PBKDF2 & SRP-RFC5054-4096-SHA512-PBKDF2)
                # so we'll create an array to handle them all, then add them all at the end.
                hashedCredArtifacts = []

                # For each extracted hash
                for shadow in extractedData['shadows']:
                    # Create a new artifact using our custom TSK_HASHED_CREDENTIAL artifact type we set up earlier.
                    hashedCredArtifact = file.newArtifact(
                        self.case.getArtifactTypeID("TSK_HASHED_CREDENTIAL"))

                    hashedCredArtifactAttributes = []
                    # We can iterate over any expected attribute types and assign them to the artifact.
                    for dictKey in self.hashedCredentialAttributeTypes:
                        try:
                            hashedCredArtifactAttributes.append(
                                BlackboardAttribute(
                                    self.case.getAttributeType(
                                        self.hashedCredentialAttributeTypes[
                                            dictKey]['attr_key']),
                                    self.moduleName, shadow[dictKey]))
                        except KeyError:
                            # Discarding the attribute type if, for whatever reason, they're not in the Plist.
                            pass

                        # Add the attributes to the artifact.
                        hashedCredArtifact.addAttributes(
                            hashedCredArtifactAttributes)
                    # and add our artifact to the array of found shadows for the account.
                    hashedCredArtifacts.append(hashedCredArtifact)

                try:
                    # Post our extracted account information.
                    self.blackboard.postArtifact(osAccountArtifact,
                                                 self.moduleName)

                    # Then iterate over our harvested credential hashes for the account, posting them.
                    for hashedCredArtifact in hashedCredArtifacts:
                        self.blackboard.postArtifact(hashedCredArtifact,
                                                     self.moduleName)

                except Blackboard.BlackboardException:
                    self.log(
                        Level.SEVERE, "Unable to index blackboard artifact " +
                        str(osAccountArtifact.getArtifactTypeName()))

            except (InvalidPlistException, NotBinaryPlistException), e:
                self.log(
                    Level.INFO,
                    "Unable to parse %s as a Plist file. Skipping." %
                    file.getName())

            # We're done processing the Plist file, clean it up from our temporary directory.
            self.remove_from_temp_directory(file)

            # Update the progress bar, as progress has been made.
            filesProcessed += 1
            progressBar.progress(filesProcessed)
コード例 #58
0
def graphics(bg):
    #img55 = Image.open(bg)
    #img55.save(bg+'.copy.jpg')
    bgc=bg

    if preblur>0:
        img = Image.open(bg)
        preblurx=img.filter(ImageFilter.GaussianBlur(10))
        preblurx.save(bg+'.copy.jpg')
        bg=bg+'.copy.jpg'
    
    





        
    theme_name=bg
    #theme_name=raw_input('Theme Name: ')

    directory='themes/'+theme_name+'/IconBundles/'
    global directory2
    directory2='themes/'+theme_name+'/Bundles/com.apple.springboard/'
    directory3='themes/'+theme_name+'/Bundles/com.apple.mobileicons.framework/'
    directory4='themes/'+theme_name+'/'
    directory4a='themes/'+theme_name+'_bg/'
    directory5='themes/'+theme_name+'_bg/AnemoneHTML/'


    if not os.path.exists(directory):
        os.makedirs(directory)
    if not os.path.exists(directory2):
        os.makedirs(directory2)

    if not os.path.exists(directory3):
        os.makedirs(directory3)
    if not os.path.exists(directory5):
        os.makedirs(directory5)


        
    copyfile('Info.plist',directory4+'Info.plist' )  
    copyfile(mask_image,directory3+'AppIconMask@3x~iphone.png' )







    pygame.init()
    pygame.display.init()


    screen = pygame.display.set_mode((phonex,phoney),pygame.SRCALPHA)
    
    pygame.display.set_caption("Iphone")

    background = pygame.Surface(screen.get_size())
    rect = background.fill((200, 50, 250))

    clock_image, clock_rect = load_image(bg)

    
    clock_image = pygame.transform.scale(clock_image, (phonex,phoney))

    screen.blit(clock_image, clock_rect)

    #white = Color('pink')

    #screen.fill(white)





    #pygame.display.update()



    clock = pygame.time.Clock()

    #pl = plistlib.readPlist("IconSupportState.plist")
    #biplist.readPlist
    if phone=='k':
        pl = biplist.readPlist("IconSupportState.plist.kevin")
    if phone=='b':
        pl = biplist.readPlist("IconSupportState.plist.britt")
    #dock = pl["buttonBar"]
    dock = pl["buttonBar"]




    
    clock_image, clock_rect = load_image(bg)
    clock_image = pygame.transform.scale(clock_image, (phonex,phoney))
    screen.blit(clock_image, clock_rect)
    
    
    generate_screen(dock,screen,pl,'picture/',theme_name,directory)



    

        #page=page+1
    pygame.display.update()
    pygame.image.save(screen, "screenshot.jpeg")
    screen_image, screen_rect = load_image("screenshot.jpeg")
    screen_image = pygame.transform.scale(screen_image, (int(phonex*.75),int(phoney*.75)))
    #screen.blit(screen_image, screen_rect)

    pygame.display.update()


    img = Image.open("screenshot.jpeg")
    pilll(pl,img,"iconLists",directory,bg)
    pilll2(pl,img,"buttonBar",directory,bg)

    white = Color('white')

    screen.fill(white)



    #newbg=raw_input('custom back ground')
    newbg=''
    clock_image, clock_rect = load_image(newbg)
    if len(newbg)==0:
        
        clock_image, clock_rect = load_image(bgc)
    
    clock_image = pygame.transform.scale(clock_image, (phonex,phoney))

    #mode = clock_image.mode
    #size = clock_image.size
    #data = clock_image.tobytes()

    pil_image = pygame.image.tostring(clock_image,'RGBA')

    #print type(pil_image)
    pil_image = Image.frombytes("RGBA",(phonex,phoney),pil_image)




    #pil_image2 = Image.open(pil_image)
    pil_image2=pil_image
    #pil_image2=pil_image.filter(ImageFilter.BLUR)
    i=0
    #while i<blur:
    #    pil_image2=pil_image2.filter(ImageFilter.GaussianBlur(10))
    #    i=i+1
    #    print i
    converter = ImageEnhance.Color(pil_image2)
    pil_image2 = converter.enhance(.5)
    ####py_image = pygame.image.fromstring(data, size, mode)
    pil_image2.save('omg.jpg')




    mode = 'RGBA'
    size = pil_image2.size
    data = pil_image2.tobytes()

    clock_image = pygame.image.fromstring(data, size, mode)



    
    screen.blit(clock_image, clock_rect)


    generate_screen(dock,screen,pl,directory,theme_name,directory)



    time=0
    #screen.blit(clock_image, clock_rect)
    pygame.display.update()
    pygame.image.save(screen, 'screens/'+bg)
    pygame.display.update()
    #print 'ok'
    pygame.image.save(screen,directory5+'/bg.jpg')
    copyfile('index.html',directory5+'/index.html' )
    copyfile('Info.plist',directory4a+'/Info.plist' )  
コード例 #59
0
def run(request, api=False):
    """View iOS Files."""
    try:
        logger.info('View iOS Source File')
        exp = 'Error Description'
        file_format = None
        if api:
            fil = request.POST['file']
            md5_hash = request.POST['hash']
            mode = request.POST['type']
            viewsource_form = ViewSourceIOSApiForm(request.POST)
        else:
            fil = request.GET['file']
            md5_hash = request.GET['md5']
            mode = request.GET['type']
            viewsource_form = ViewSourceIOSForm(request.GET)
        typ = set_ext_api(fil)
        if not viewsource_form.is_valid():
            err = FormUtil.errors_message(viewsource_form)
            if api:
                return err
            return print_n_send_error_response(request, err, False, exp)
        base = Path(settings.UPLD_DIR) / md5_hash
        if mode == 'ipa':
            src1 = base / 'payload'
            src2 = base / 'Payload'
            if src1.exists():
                src = src1
            elif src2.exists():
                src = src2
            else:
                raise Exception('MobSF cannot find Payload directory')
        elif mode == 'ios':
            src = base
        sfile = src / fil
        sfile = sfile.as_posix()
        if not is_safe_path(src, sfile):
            msg = 'Path Traversal Detected!'
            if api:
                return {'error': 'Path Traversal Detected!'}
            return print_n_send_error_response(request, msg, False, exp)
        dat = ''
        sql_dump = {}
        if typ == 'm':
            file_format = 'cpp'
            with io.open(sfile,
                         mode='r',
                         encoding='utf8',
                         errors='ignore') as flip:
                dat = flip.read()
        elif typ == 'xml':
            file_format = 'xml'
            with io.open(sfile,
                         mode='r',
                         encoding='utf8',
                         errors='ignore') as flip:
                dat = flip.read()
        elif typ == 'plist':
            file_format = 'json'
            dat = biplist.readPlist(sfile)
            try:
                dat = json.dumps(dat, indent=4, sort_keys=True)
            except Exception:
                pass
        elif typ == 'db':
            file_format = 'asciidoc'
            sql_dump = read_sqlite(sfile)
        elif typ == 'txt' and fil == 'classdump.txt':
            file_format = 'cpp'
            app_dir = os.path.join(settings.UPLD_DIR, md5_hash + '/')
            cls_dump_file = os.path.join(app_dir, 'classdump.txt')
            if is_file_exists(cls_dump_file):
                with io.open(cls_dump_file,
                             mode='r',
                             encoding='utf8',
                             errors='ignore') as flip:
                    dat = flip.read()
            else:
                dat = 'Class Dump result not Found'
        elif typ == 'txt':
            file_format = 'text'
            with io.open(sfile,
                         mode='r',
                         encoding='utf8',
                         errors='ignore') as flip:
                dat = flip.read()
        else:
            if api:
                return {'error': 'Invalid Parameters'}
            return HttpResponseRedirect('/error/')
        context = {
            'title': escape(ntpath.basename(fil)),
            'file': escape(ntpath.basename(fil)),
            'type': file_format,
            'data': dat,
            'sqlite': sql_dump,
            'version': settings.MOBSF_VER,
        }
        template = 'general/view.html'
        if api:
            return context
        return render(request, template, context)
    except Exception as exp:
        logger.exception('Error Viewing Source')
        msg = str(exp)
        exp = exp.__doc__
        if api:
            return print_n_send_error_response(request, msg, True, exp)
        return print_n_send_error_response(request, msg, False, exp)
コード例 #60
0
def run(request, api=False):
    """View iOS Files"""
    try:
        print("[INFO] View iOS Source File")
        file_format = "cpp"
        if api:
            fil = request.POST['file']
            md5_hash = request.POST['hash']
            mode = request.POST['type']
            viewsource_form = ViewSourceIOSApiForm(request.POST)
        else:
            fil = request.GET['file']
            md5_hash = request.GET['md5']
            mode = request.GET['type']
            viewsource_form = ViewSourceIOSForm(request.GET)
        typ = set_ext_api(fil)
        if not viewsource_form.is_valid():
            err = FormUtil.errors_message(viewsource_form)
            if api:
                return err
            context = {
                'title': 'Error',
                'exp': 'Error Description',
                'doc': err
            }
            template = "general/error.html"
            return render(request, template, context, status=400)
        if mode == 'ipa':
            src = os.path.join(settings.UPLD_DIR, md5_hash + '/Payload/')
        elif mode == 'ios':
            src = os.path.join(settings.UPLD_DIR, md5_hash + '/')
        sfile = os.path.join(src, fil)
        dat = ''
        if typ == 'm':
            file_format = 'cpp'
            with io.open(sfile, mode='r', encoding="utf8",
                         errors="ignore") as flip:
                dat = flip.read()
        elif typ == 'xml':
            file_format = 'xml'
            with io.open(sfile, mode='r', encoding="utf8",
                         errors="ignore") as flip:
                dat = flip.read()
        elif typ == 'plist':
            file_format = 'json'
            dat = biplist.readPlist(sfile)
            try:
                dat = json.dumps(dat, indent=4, sort_keys=True)
            except:
                pass
        elif typ == 'db':
            file_format = 'asciidoc'
            dat = read_sqlite(sfile)
        elif typ == 'txt' and fil == "classdump.txt":
            file_format = 'cpp'
            app_dir = os.path.join(settings.UPLD_DIR, md5_hash + '/')
            cls_dump_file = os.path.join(app_dir, "classdump.txt")
            if isFileExists(cls_dump_file):
                with io.open(cls_dump_file,
                             mode='r',
                             encoding="utf8",
                             errors="ignore") as flip:
                    dat = flip.read()
            else:
                dat = "Class Dump result not Found"
        else:
            if api:
                return {"error": "Invalid Parameters"}
            return HttpResponseRedirect('/error/')
        context = {
            'title': escape(ntpath.basename(fil)),
            'file': escape(ntpath.basename(fil)),
            'type': file_format,
            'dat': dat
        }
        template = "general/view.html"
        if api:
            return context
        return render(request, template, context)
    except Exception as exp:
        msg = str(exp)
        exp = exp.__doc__
        if api:
            return print_n_send_error_response(request, msg, True, exp)
        else:
            return print_n_send_error_response(request, msg, False, exp)