forked from yincp/iOS-checkIPA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkipa
executable file
·1113 lines (949 loc) · 42.5 KB
/
checkipa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# Scan IPA file and parse its Info.plist and embedded.mobileprovision
# files. Perform checks of expected key/value relationships and report
# the results.
#
# Copyright (c) 2012 by Apperian, Inc. All rights reserved.
# Copyright (c) 2015 [email protected]
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#---------------------------------------------------------------------
# pylint thinks the following methods have "Too many branches," making
# the code path hard to follow. This is not the case, so we're
# disabling this.
#
# IntegrityCheck.detect_errors
# IntegrityCheck.output_report
# IntegrityCheck.check_appid
#
# pylint: disable=R0912
from pprint import pprint
import sys
import os
import datetime
import tempfile
import shutil
import re
import zipfile
import plistlib
import optparse
import json
import subprocess
import platform
import uuid
from biplist import *
DEFAULT_ENCODING = 'utf-8'
VERSION_NUMBER = '1.7'
# debugging only...
def dump(obj):
import inspect
pprint(inspect.getmembers(obj))
#---------------------------------------------------------------------
# UdidCheck Class
#---------------------------------------------------------------------
class UdidCheck(object):
def __init__(self, udids, provision):
msg = ''
if 'ProvisionedDevices' in provision:
provisioned_ids = provision['ProvisionedDevices']
if len(provisioned_ids) > 1:
delim_rx = re.compile(r'\s+')
udid_list = delim_rx.split(udids)
matches = list(set(udid_list) & set(provisioned_ids))
# SUCCESS!
if (len(matches) > 0):
msg_a = []
for udid in udid_list:
if udid == "":
continue
if udid in matches:
msg_a.append('Provisioned: %s' % (udid))
else:
msg_a.append(' not found: %s' % (udid))
msg = "\n".join(msg_a)
else:
msg = 'no matching devices found'
else:
msg = 'no provisioned devices in this app'
self.output(msg)
# end __init__
def output(self, msg):
print("")
for line in msg.split("\n"):
print(' %s' % (line))
print("")
# end UdidCheck class
#---------------------------------------------------------------------
# IntegrityCheck Class
#---------------------------------------------------------------------
class IntegrityCheck(object):
"""This class reports and examines specific details and
relationships between values in Info.plist and
embedded.mobileprovision files"""
def __init__(self, params):
self.data = params['info']
self.profile = params['mobileprovision']
self.verbose = params['verbose']
self.ipa_filename = params['ipa_filename']
self.jformat = params['jformat']
self.icon_file = params['icon_file']
self.warnings = {}
self.errors = {}
self.ipa_info = {}
self.icon_info = {}
self.signature = []
self._initialize_results_data()
# run the checks
self.process_checks()
if self.verbose:
pass
# debug only self.verbose_output()
if params['icon_file'] is not None:
self.save_icon()
if len(self.profile) == 0:
self.detect_exec_signature_when_no_provision()
if self.jformat:
self.output_json()
else:
self.output_report()
def detect_exec_signature_when_no_provision(self):
if platform.system() == 'Darwin':
exec_file = self.data['CFBundleExecutable']
zip_obj = zipfile.ZipFile(self.ipa_filename, 'r')
regx = re.compile(r'Payload/[^/]+\.app/%s' % exec_file)
while True:
tmp_file = os.path.join('/tmp', str(uuid.uuid1()))
if not os.path.exists(tmp_file):
break
filenames = zip_obj.namelist()
found = False
for fname in filenames:
if regx.search(fname):
output = open(tmp_file, 'wb')
output.write(zip_obj.read(fname))
output.close()
found = True
break
zip_obj.close()
if found:
cmd = 'codesign -vv -d "%s"' % tmp_file
self.signature = execute_cmd(cmd)
else:
zip_obj = zipfile.ZipFile(self.ipa_filename, 'r')
filenames = zip_obj.namelist()
found = False
for fname in filenames:
if fname == 'iTunesMetadata.plist':
found = True
break
zip_obj.close()
if found:
self.signature.append('Authority=Apple iPhone OS Application Signing')
else:
self.signature.append(': no signature')
def detect_errors(self):
results = []
if self.errors['ipa_failure']:
results.append({'label': 'IPA File',
'description': 'Info.plist file is not accessable'})
if self.errors['mobileprovision']:
results.append({'label': 'Provision Profile',
'description': 'not located or accessable'})
if self.errors['mobileprovision']:
results.append({'label': 'Provision Profile',
'description': 'not located or accessable'})
if self.errors['bundleid']:
results.append({'label': 'BundleID',
'description': 'does not exist'})
if self.errors['bundleseed']:
results.append({'label': 'Bundleseed',
'description': 'does not exist'})
if self.errors['appid']:
results.append({'label': 'AppID',
'description': 'does not exist or has a problem'})
if self.errors['appid_malformed']:
results.append({'label': 'AppID',
'description': 'formatted incorrectly'})
if len(self.profile) > 0 and self.errors['appid_bundleseed_mismatch']:
appid_parts = self.profile['Entitlements']['application-identifier'].split('.', 1)
appid_suffix = appid_parts[1]
bundleid_val = self.data['CFBundleIdentifier']
desc = 'BundleID "%s" does not match AppID "%s"' % (bundleid_val, appid_suffix)
results.append({'label': 'ID Mismatch', 'description': desc})
if self.errors['appid_bundleid_mismatch']:
results.append({'label': 'AppID',
'description': 'does not match the BundleID and is not wildcard'})
if self.errors['distmethod']:
results.append({'label': 'Distribution',
'description': 'not Enterprise and no provisioned devices'})
if self.errors['dist_dev']:
results.append({'label': 'Distribution',
'description': 'development profile not found'})
if self.errors['dist_missing']:
results.append({'label': 'Distribution',
'description': 'no distribution profile found'})
if len(self.profile) > 0 and self.errors['expire_date_past']:
exp_desc = '%s is in the past' % (self.profile['ExpirationDate'])
results.append({'label': 'Expiration Date', 'description': exp_desc})
return results
# end detect_errors()
def detect_warnings(self):
results = []
if self.warnings['push']:
results.append({'label': 'Push Notification',
'description': 'not enabled'})
if self.warnings['push_apsenv']:
results.append({'label': 'Push Notification',
'description': 'aps-environment key is not set'})
if True or self.warnings['dist_dev']:
dist_warn_desc = "code signing Entitlements 'get-task-allow' value is set to YES; should be NO"
results.append({'label': 'Distribution',
'description': dist_warn_desc})
if len(self.profile) > 0 and self.warnings['expire_date_coming']:
exp_desc = '%s is rapidly approaching' % (self.profile['ExpirationDate'])
results.append({'label': 'Expiration Date', 'description': exp_desc})
return results
# end detect_warnings()
def output_report(self):
report_warnings = self.detect_warnings()
report_errors = self.detect_errors()
vertical_spacer = ''
# Heading
main_heading = 'IPA File Integrity: "%s"' % (os.path.basename(self.ipa_filename))
txt = []
txt.append(vertical_spacer)
txt.append(main_heading)
txt.append('=' * len(main_heading))
txt.append(vertical_spacer)
# Info
provisioned_devices = self.get_provisioned_devices()
txt.append('Info')
txt.append('-' * len('Info'))
if 'CFBundleName' in self.data:
txt.append(' Name: %s' % (self.data['CFBundleName']))
if 'CFBundleVersion' in self.data:
txt.append(' Version: %s' % (self.data['CFBundleVersion']))
if len(self.profile) > 0 and ('ExpirationDate' in self.profile):
txt.append(' Expiration Date: %s' % (self.profile['ExpirationDate']))
if self.ipa_info['adhoc'] and not self.ipa_info['enterprise']:
ipa_type = 'Ad Hoc/Developer'
elif self.ipa_info['enterprise'] and not self.ipa_info['adhoc']:
ipa_type = 'Enterprise'
elif self.ipa_info['wildcard']:
ipa_type = 'Wildcard'
elif len(self.profile) > 0:
ipa_type = 'AppStore'
else:
jb_or_itunes_found = False
if len(self.signature):
signature_str = ';'.join(self.signature)
if re.search(r': no signature', signature_str):
jb_or_itunes_found = True
ipa_type = 'NotSigned'
elif re.search(r'Authority=Apple iPhone OS Application Signing', signature_str):
jb_or_itunes_found = True
ipa_type = 'iTunes'
if not jb_or_itunes_found:
ipa_type = 'unknown distribution type'
report_errors.append({'code': -1001, 'label': 'Distribution', 'description': 'unknown distribution type'})
txt.append(' Distribution Profile Type: %s' % (ipa_type))
if len(provisioned_devices) > 0:
txt.append(' Provisioned Devices (%d): ' % (len(provisioned_devices)))
for udid in provisioned_devices:
txt.append(' %s' % (udid))
else:
txt.append(' Provisioned Devices (0):')
txt.append(vertical_spacer)
# Warnings
txt.append('Warnings')
txt.append('-' * len('Warnings'))
if len(report_warnings) == 0:
txt.append(' none')
else:
for war in report_warnings:
txt.append(' %s: %s' % (war['label'], war['description']))
txt.append(vertical_spacer)
# Errors
txt.append('Errors')
txt.append('-' * len('Errors'))
if len(report_errors) == 0:
txt.append(' none')
else:
for err in report_errors:
txt.append(' %s: %s' % (err['label'], err['description']))
txt.append(vertical_spacer)
for line in txt:
print(' %s' % (line))
# end output_report
def output_json(self):
report_warnings = self.detect_warnings()
report_errors = self.detect_errors()
if self.ipa_info['adhoc'] and not self.ipa_info['enterprise']:
ipa_type = 'Ad Hoc/Developer'
elif self.ipa_info['enterprise'] and not self.ipa_info['adhoc']:
ipa_type = 'Enterprise'
elif self.ipa_info['wildcard']:
ipa_type = 'Wildcard'
elif len(self.profile) > 0:
ipa_type = 'AppStore'
else:
jb_or_itunes_found = False
if len(self.signature):
signature_str = ';'.join(self.signature)
if re.search(r': no signature', signature_str):
jb_or_itunes_found = True
ipa_type = 'NotSigned'
elif re.search(r'Authority=Apple iPhone OS Application Signing', signature_str):
jb_or_itunes_found = True
ipa_type = 'iTunes'
if not jb_or_itunes_found:
ipa_type = 'unknown distribution type'
report_errors.append({'code': -1001, 'label': 'Distribution', 'description': 'unknown distribution type'})
self.ipa_info['ipa_type'] = ipa_type
jobj = {'code': 0, 'data': self.data, 'profile': self.profile, 'ipa': self.ipa_info,
'warnings': report_warnings, 'errors': report_errors, 'icon': self.icon_info}
# pprint(jobj)
print json.dumps(jobj, cls=MyJsonEncoder, indent=4)
# end output_json
def save_icon(self):
icon_iden = self.get_icon()
try:
if self.icon_file and os.path.isfile(self.icon_file):
os.remove(self.icon_file)
zip_obj = zipfile.ZipFile(self.ipa_filename, 'r')
regx = re.compile(r'Payload/[^/]+\.app/%s.png' % icon_iden, re.I)
regx2 = re.compile(r'Payload/[^/]+\.app/%[email protected]' % icon_iden, re.I)
regx3 = re.compile(r'Payload/[^/]+\.app/%[email protected]' % icon_iden, re.I)
filenames = zip_obj.namelist()
filename = ''
for fname in filenames:
if regx3.search(fname):
output = open(self.icon_file, 'wb')
output.write(zip_obj.read(fname))
output.close()
zip_obj.close()
self.icon_info = {'save': 'success', 'source': fname, 'file': self.icon_file}
return
for fname in filenames:
if regx2.search(fname):
output = open(self.icon_file, 'wb')
output.write(zip_obj.read(fname))
output.close()
zip_obj.close()
self.icon_info = {'save': 'success', 'source': fname, 'file': self.icon_file}
return
for fname in filenames:
if regx.search(fname):
output = open(self.icon_file, 'wb')
output.write(zip_obj.read(fname))
output.close()
zip_obj.close()
self.icon_info = {'save': 'success', 'source': fname, 'file': self.icon_file}
return
except Exception, e:
self.icon_info = {'save': 'failed', 'msg': e.message}
return
self.icon_info = {'save': 'failed', 'msg': 'can not find icon file in ipa'}
# end save_icon
def get_icon(self):
try:
if self.data.has_key('CFBundleIcons'):
icons = self.data['CFBundleIcons']
if icons and icons.has_key('CFBundlePrimaryIcon'):
primary_icon = icons['CFBundlePrimaryIcon']
if primary_icon and primary_icon.has_key('CFBundleIconFiles'):
icon_files = primary_icon['CFBundleIconFiles']
if icon_files and isinstance(icon_files, list):
pIconPixels = re.compile(r'\S+(\d{2,3})x(?(1))')
max_pixel = 0
max_index = -1
i = 0
for file in icon_files:
m = pIconPixels.match(file)
if m:
pixel = int(m.group(1))
if pixel > max_pixel:
max_pixel = pixel
max_index = i
i += 1
if max_pixel > 0 and max_index >= 0:
return icon_files[max_index]
if len(icon_files > 0):
return icon_files[0]
except:
pass
return 'icon'
# end get_icon
def get_provisioned_devices(self):
if len(self.profile) > 0 and 'ProvisionedDevices' in self.profile:
return self.profile['ProvisionedDevices']
else:
return []
def process_checks(self):
self.check_bundle_id()
self.check_bundle_seed()
self.check_appid()
self.check_push()
self.check_dist_method()
self.check_dist_profile()
self.check_expiration_date()
def check_expiration_date(self):
if len(self.profile) > 0 and ('ExpirationDate' in self.profile):
warning_period_in_days = 14
expire_date = self.profile['ExpirationDate']
difference_date = expire_date - datetime.datetime.today()
days_until_expire = difference_date.days + 1
if (days_until_expire > 0) and (days_until_expire <= warning_period_in_days):
self.warnings['expire_date_coming'] = True
elif days_until_expire <= 0:
self.errors['expire_date_past'] = True
# Checks whether a distribution certificate or a developer
# certificate is present in mobileprovision
#
# Development signed apps typically set the 'get-task-allow' to True
#
# FIXME: 'dist_dev' should be conditionally set to errors or
# warnings, depending if we're in an Enterprise context
# or not. For now, we're choosing warnings as if we're
# in a developer context.
def check_dist_profile(self):
if len(self.profile) > 0 and 'get-task-allow' in self.profile['Entitlements']:
if self.profile['Entitlements']['get-task-allow']: # boolean, should be False
self.warnings['dist_dev'] = True
else:
self.errors['dist_missing'] = True
# end check_dist_profile
def check_push(self):
appid = None
if len(self.profile) > 0 and 'Entitlements' in self.profile:
if 'application-identifier' in self.profile['Entitlements']:
appid = self.profile['Entitlements']['application-identifier']
else:
self.warnings['push'] = True
else:
self.warnings['push'] = True
if len(self.profile) > 0 and 'Entitlements' in self.profile:
if 'aps-environment' not in self.profile['Entitlements']:
self.warnings['push'] = True
self.warnings['push_apsenv'] = True
if appid is not None:
# split on only 1 (the first) period, thus returning 2
# elements, if valid appid format
appid_vals = appid.split('.', 1)
# wildcard appid, not allowed for push
if len(appid_vals) != 2:
self.warnings['push'] = True
elif appid_vals[1] == '*':
self.ipa_info['wildcard'] = True
self.warnings['push'] = True
# end check_push()
def check_appid(self):
bundleseed = None
bundleid = None
appid = None
if len(self.profile) > 0 and 'ApplicationIdentifierPrefix' in self.profile:
if len(self.profile['ApplicationIdentifierPrefix']) > 0:
bundleseed = self.profile['ApplicationIdentifierPrefix'][0]
else:
self.errors['appid'] = True
if 'CFBundleIdentifier' in self.data:
bundleid = self.data['CFBundleIdentifier']
if len(self.profile) > 0 and 'Entitlements' in self.profile:
if 'application-identifier' in self.profile['Entitlements']:
appid = self.profile['Entitlements']['application-identifier']
else:
self.errors['appid'] = True
else:
self.errors['appid'] = True
if appid is not None:
# split on only 1 (the first) period, thus returning 2
# elements, if valid appid format
appid_vals = appid.split('.', 1)
# wildcard appid, not allowed for push
if len(appid_vals) != 2:
# malformed appid: must have value.value
self.errors['appid'] = True
self.errors['appid_malformed'] = True
elif appid_vals[1] == '*':
self.ipa_info['wildcard'] = True
# mismatch in mobileprovision profile
if (bundleseed is not None) and (len(appid_vals) > 0):
if bundleseed != appid_vals[0]:
self.errors['appid_bundleseed_mismatch'] = True
# mismatch between info.plist and mobileprovision
if (bundleid is not None) and (len(appid_vals) > 1) and not (self.ipa_info['wildcard']):
appid_suffix = appid_vals[1] # appid, excluding bundle seed id
if not self.is_bundleid_match_against_appid(bundleid, appid_suffix):
self.errors['appid_bundleseed_mismatch'] = True
# end check_appid
# Apple's specified Entitlement app id is a string
# _pattern_ against which the bundle id must match; the
# two values do not have to be exactly the same. Example:
#
# app id (excluding bundle seed id): com.apperian.*
# bundle id: com.apperian.AppCatalog
#
# In this example there is no mismatch because the app
# id's '*' wildcard allows any string to be used at that
# part of the reverse domain string pattern.
#
# return boolean
def is_bundleid_match_against_appid(self, bundleid, appid):
if re.compile(r'\*').search(appid):
wildcard_match = re.compile(r'[^*]+').search(appid)
if wildcard_match is not None:
appid_parts = appid.split('*', 1)
bundleid_match = re.compile(r'^%s' % (appid_parts[0])).search(bundleid)
return bundleid_match is not None
# appid is only '*'; bundle id will always match
else:
return True
# no wildcard; must be exact match
else:
return appid == bundleid
# end is_bundleid_match_against_appid
# if 'CFBundleIdentifier' key exists and is blank string: error
# if 'CFBundleIdentifier' key not exists: error
def check_bundle_id(self):
if 'CFBundleIdentifier' in self.data:
if self.data['CFBundleIdentifier'].strip() == "":
self.errors['bundleid'] = True
else: # key missing
self.errors['bundleid'] = True
def check_bundle_seed(self):
if len(self.profile) > 0 and 'ApplicationIdentifierPrefix' in self.profile:
app_id_prefix = self.profile['ApplicationIdentifierPrefix']
if len(app_id_prefix) >= 1:
if app_id_prefix[0].strip() == "":
self.errors['bundleseed'] = True
else:
self.errors['bundleseed'] = True
else:
self.errors['bundleseed'] = True
def check_dist_method(self):
if len(self.profile) > 0 and 'ProvisionsAllDevices' in self.profile:
self.ipa_info['enterprise'] = True
elif len(self.profile) > 0 and 'ProvisionedDevices' in self.profile:
self.ipa_info['adhoc'] = True
elif len(self.profile) > 0:
self.ipa_info['appstore'] = True
else:
self.errors['distmethod'] = True
def _initialize_results_data(self):
# All errors and warnings are to be declared here and set to
# false. As new rules are discovered, they can be added here,
# and then they can be handled by the caller.
#
# ipa_failure => The IPA file was not able to extract correctly, or
# did not conatin an info.plist
#
# mobileprovision => The embedded.mobileprovision file was not found
# and thus the IPA does not have a provisioning profile
#
# bundleid => Bundleid key in info.plist either doesn't exist or is
# and empty string
#
# bundleseed => The bundleseed in mobileprovision either doesn't exist
# or is an empty string
#
# appid => The appid in mobileprovision has an error that makes it
# unacceptable, explained in further errors
#
# appid_malformed => The appid is not in the form of String.String
#
# appid_bundleseed_mismatch => The appid is not match the bundleseed
# in the first value
#
# appid_bundleid_mismatch => The appid is not a wildcard and doesn't
# match the bundleid in the second value
#
# distmethod => The app does not have a ProvisionedDevices (ad hoc) or
# ProvisionsAllDevices key
#
# dist_dev => This app has a development distribution profile and cannot be
# distributed
#
# dist_missing => This app is missing a distribution profile
#
# expire_date_past => Expiration date < tomorrow
self.errors = {
"ipa_failure": False,
"mobileprovision": False,
"bundleid": False,
"bundleseed": False,
"appid": False,
"appid_malformed": False,
"appid_bundleseed_mismatch": False,
"appid_bundleid_mismatch": False,
"distmethod": False,
"dist_dev": False,
"dist_missing": False,
"expire_date_past": False}
# push => Push is disabled for this app
#
# push_apsenv => The aps-environment key is not set and thus
# push disabled
#
# expire_date_coming => The expire date is within 14 days of
# current date
self.warnings = {
"push": False,
"push_apsenv": False,
"dist_dev": False,
"expire_date_coming": False}
# IPA info contains information about the IPA that is
# unrelated to errors or warnings, such as if it's an App
# Catalog or is a wildcard application (meaning push is
# disabled)
#
# app_catalog => This application is an App Catalog
#
# wildcard => This application has a wildcard provisioning profile
# meaning push is disabled
#
#
# enterprise => This app has an Enterprise distribution
# profile
#
# adhoc => This app has an Ad hoc distribution profile
self.ipa_info = {
"app_catalog": False,
"wildcard": False,
"enterprise": False,
"adhoc": False,
"appstore": False}
# end initializeResultsData
def verbose_output(self):
print('')
print('INFO:')
pprint(self.ipa_info)
print('')
print('WARNINGS:')
pprint(self.warnings)
print('')
print('ERRORS:')
pprint(self.errors)
print('')
print('checks completed: items marked True are problematic.')
# end IntegrityCheck class
#---------------------------------------------------------------------
# ParseIPA class
#---------------------------------------------------------------------
class ParseIPA(object):
plist_file_rx = re.compile(r'Payload/.+?\.app/Info.plist$')
plist_misnamed_payload_file_rx = re.compile(r'payload/.+?\.app/Info.plist$')
plist_misnamed_payload_file_as_Applications_rx = re.compile(r'Applications/.+?\.app/Info.plist$', re.I)
provision_file_rx = re.compile(r'\bembedded.mobileprovision$')
xml_rx = re.compile(r'<\??xml')
provision_xml_rx = re.compile(r'<\?xml.+</plist>', re.DOTALL)
def __init__(self, ipa_filename):
self.info_plist_data = {}
self.provision_data = {}
self.errors = []
self.ipa_filename = ipa_filename
self.full_path_plist_filename = ''
self.temp_directory = ''
def get_filename_from_ipa(self, filetype):
zip_obj = zipfile.ZipFile(self.ipa_filename, 'r')
if filetype == 'Info':
regx = ParseIPA.plist_file_rx
elif filetype == 'Misnamed_Payload_Check':
regx = ParseIPA.plist_misnamed_payload_file_rx
elif filetype == 'Misnamed_Payload_as_Applications_Check':
regx = ParseIPA.plist_misnamed_payload_file_as_Applications_rx
else:
regx = ParseIPA.provision_file_rx
filenames = zip_obj.namelist()
filename = ''
for fname in filenames:
if regx.search(fname):
filename = fname
break
return {'filename': filename, 'zip_obj': zip_obj}
# end get_filename_from_ipa()
def extract_provision_data(self):
extract_info = self.get_filename_from_ipa('Provision')
zip_obj = extract_info['zip_obj']
provision_filename = extract_info['filename']
data = {}
if provision_filename == '':
# if platform.system() != 'Darwin':
# self.errors.append({'code': -2001, 'label': 'Provision', 'description': 'embedded.mobileprovision file not found in IPA'})
pass
else:
content = zip_obj.read(provision_filename)
match = ParseIPA.provision_xml_rx.search(content)
if (match is not None):
provision_xml_content = match.group()
data = plistlib.readPlistFromString(provision_xml_content)
else:
self.errors.append({'code': -2002, 'label': 'Provision', 'description': 'unable to parse embedded.mobileprovision file'})
self.provision_data = data
# end extract_provision_data
def extract_info_plist_data(self):
extract_info = self.get_filename_from_ipa('Info')
zip_obj = extract_info['zip_obj']
plist_filename = extract_info['filename']
data = {}
if plist_filename == '':
if self.get_filename_from_ipa('Misnamed_Payload_Check')['filename'] != '':
self.errors.append({'code': -2003, 'label': 'Payload', 'description': "Payload folder is misnamed 'payload' (lower-case p). Rename to 'Payload'"})
elif self.get_filename_from_ipa('Misnamed_Payload_as_Applications_Check')['filename'] != '':
self.errors.append({'code': -2004, 'label': 'Payload', 'description': 'Found Applications directory instead of Payload'})
else:
self.errors.append({'code': -2005, 'label': 'PList', 'description': 'Info.plist file not found in IPA'})
else:
# content = zip_obj.read(plist_filename)
# if (ParseIPA.xml_rx.match(content)):
# data = plistlib.readPlistFromString(content)
# else:
# self.temp_directory = tempfile.mkdtemp()
#
# zip_obj.extract(plist_filename, self.temp_directory)
# fullpath_plist = os.path.join(self.temp_directory, plist_filename)
#
# os_info = os.uname()
# if os_info[0] == 'Linux':
# cmd = 'plutil -i "%s" -o "%s"' % (fullpath_plist, fullpath_plist)
# else:
# cmd = 'plutil -convert xml1 "%s"' % (fullpath_plist)
#
# # pprint(cmd)
#
# os.system(cmd)
# data = plistlib.readPlist(fullpath_plist)
self.temp_directory = tempfile.mkdtemp()
zip_obj.extract(plist_filename, self.temp_directory)
fullpath_plist = os.path.join(self.temp_directory, plist_filename)
data = readPlist(fullpath_plist)
# end if plist == ''
self.info_plist_data = data
# end extractPlist()
def is_valid_zip_archive(self):
return zipfile.is_zipfile(self.ipa_filename)
# end ParseIPA class
class MyJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.__str__()
if isinstance(obj, plistlib.Data):
return '<Data>' #obj.__repr__()
return json.JSONEncoder.default(self, obj)
# end MyJsonEncoder class
class MyOptionParser(optparse.OptionParser):
def format_epilog(self, formatter):
return self.epilog
# end MyOptionParser class
def execute_cmd(cmd):
result_lines = []
try:
cmd_process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
result_lines.extend(cmd_process.stdout.readlines())
result_lines.extend(cmd_process.stderr.readlines())
cmd_process.kill() #need to kill?
except:
pass
return result_lines
# end execute_cmd
def get_options():
error_in_output = '''
For json output, error numbers as follow:
-1001 Distribution unknown distribution type
-2001 Provision embedded.mobileprovision file not found in IPA (from v1.7, this is not an error on a Mac system)
-2002 Provision unable to parse embedded.mobileprovision file
-2003 Payload Payload folder is misnamed 'payload' (lower-case p). Rename to 'Payload'
-2004 Payload Found Applications directory instead of Payload
-2005 Plist Info.plist file not found in IPA
-9001 Checkipa valid input filename not provided
-9002 Checkipa icon file can not be a directory
-9003 Checkipa not a valid zip archive
-9004 Checkipa The program 'plutil' is currently not installed
-9005 Checkipa The program 'codesign' is currently not installed
'''
version_info = 'checkipa: version %s' % (VERSION_NUMBER)
optp = MyOptionParser(version=version_info, epilog=error_in_output)
optp.add_option('-i', '--ipafile', action='store', dest='input_file',
help='''provide IPA filename
''')
optp.add_option('-u', '--udids', action='store', dest='udids',
help='''check if udids are provisioned
''')
optp.add_option('-v', '--verbose', action='store_true',
dest='verbose', default=False,
help='''print data structures to stdout
''')
optp.add_option('-j', '--json', action='store_true',
dest='json_format', default=False,
help='''print data with json format to stdout
''')
optp.add_option('-x', '--extract-icon', action='store', dest='icon_file',
help='''specifid filename which icon will be saved
''')
optp.set_usage('checkipa -i <filename> [-u "udid udid"] [-v] [-j] [-x <filename>]')
optp.set_description('''Uesed to check and extract infomations from Info.plist and mobileprovision in ipa file,
forked from https://github.com/apperian/iOS-checkIPA.
In addtion, json output and extracting icon option are added by Yincp.
''')
just_to_read = '''For output errors in json file, error numbers as follow:
-1001 Distribution unknown distribution type
-2001 Provision embedded.mobileprovision file not found in IPA
-2002 Provision unable to parse embedded.mobileprovision file
-2003 Payload Payload folder is misnamed 'payload' (lower-case p). Rename to 'Payload'
-2004 Payload Found Applications directory instead of Payload
-2005 Plist Info.plist file not found in IPA
-9001 Checkipa valid input filename not provided
-9002 Checkipa icon file can not be a directory
-9003 Checkipa not a valid zip archive
-9004 Checkipa The program 'plutil' is currently not installed
'''
opts_args = optp.parse_args()
return opts_args[0]
# end get_options
def process_ipa(params):
parse = params['parse']
ipa_filename = params['ipa_filename']
check_udids = params['check_udids']
udids = params['udids']
verbose = params['verbose']
jformat = params['jformat']
icon_file = params['icon_file']
parse.extract_info_plist_data()
parse.extract_provision_data()
if len(parse.errors) == 0:
#---------------------------------------------------------------------
# verbose output
#---------------------------------------------------------------------
if verbose:
print('Info.plist')
pprint(parse.info_plist_data)
print('')
print('embedded.mobileprovision')
pprint(parse.provision_data)
#---------------------------------------------------------------------
# check provisioned devices
#---------------------------------------------------------------------
if check_udids:
UdidCheck(udids, parse.provision_data)
else:
#---------------------------------------------------------------------
# check integrity
#---------------------------------------------------------------------
params = {'info': parse.info_plist_data,
'mobileprovision': parse.provision_data,
'verbose': verbose, 'ipa_filename': ipa_filename,
'jformat': jformat, 'icon_file': icon_file}
IntegrityCheck(params)