forked from etrepum/strip_pkg_signature
-
Notifications
You must be signed in to change notification settings - Fork 0
/
strip_pkg_signature.py
executable file
·177 lines (149 loc) · 5.2 KB
/
strip_pkg_signature.py
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
#!/usr/bin/env python
import os
import sys
import zlib
import struct
import hashlib
import argparse
from binascii import b2a_hex
from xml.etree import cElementTree as etree
from tempfile import NamedTemporaryFile
from shutil import copyfileobj, copy2
class XARFormatError(ValueError):
pass
class NoChecksum(object):
def __init__(self, initial=''):
pass
def digest(self):
return ''
MAGIC = 0x78617221 # xar!
VERSIONS = {0, 1}
CHECKSUM = {0: NoChecksum,
1: hashlib.sha1,
2: hashlib.md5}
class Struct(object):
def __init__(self, fmt, fields):
self.fmt = fmt
self.fields = fields
self.size = struct.calcsize(fmt)
def fromfile(self, f):
return self.unpack(f.read(self.size))
def unpack(self, data):
return dict(zip(self.fields, struct.unpack(self.fmt, data)))
def pack(self, dct):
return struct.pack(self.fmt,
*(dct[field] for field in self.fields))
HEADER = Struct('>IHHQQI',
('magic', 'size', 'version',
'toc_length_compressed', 'toc_length_uncompressed',
'cksum_alg'))
def toc_digest(hdr, ztocdata):
return CHECKSUM[hdr['cksum_alg']](ztocdata).digest()
def readtoc(f):
hdr = HEADER.fromfile(f)
if hdr['magic'] != MAGIC:
raise XARFormatError('magic %r != %r' %
(hdr['magic'], MAGIC))
if hdr['version'] not in VERSIONS:
raise XARFormatError('version %r not supported' %
(hdr['version'],))
if hdr['cksum_alg'] not in CHECKSUM:
raise XARFormatError('cksum_alg %r not supported' %
(hdr['cksum_alg'],))
ztocdata = f.read(hdr['toc_length_compressed'])
tocdata = zlib.decompress(ztocdata)
if hdr['toc_length_uncompressed'] != len(tocdata):
raise XARFormatError('toc_length_uncompressed %r != %r' %
(hdr['toc_length_uncompressed'],
len(tocdata)))
digest = toc_digest(hdr, ztocdata)
if digest:
orig_digest = f.read(len(digest))
if digest != orig_digest:
raise XARFormatError('digest %r != %r' %
(b2a_hex(digest),
b2a_hex(orig_digest)))
return hdr, tocdata
def strip_signature(fn, out_fn=None, dry_run=False, keep_old=False):
if out_fn is not None:
if keep_old:
raise TypeError('keep_old is not compatible with out_fn')
if os.path.isdir(out_fn):
out_fn = os.path.join(out_fn, os.path.basename(fn))
def do(msg, func, *args, **kw):
if not dry_run:
if func is not None:
func(*args, **kw)
else:
msg = msg + ' (dry run)'
print fn, msg
in_place = out_fn is None
with open(fn, 'rb') as f:
hdr, tocdata = readtoc(f)
new_tocdata = strip_toc_signature(tocdata)
if new_tocdata is None:
if in_place:
do('SKIPPED, already unsigned',
None)
else:
do('COPIED, already unsigned',
copy2, fn, out_fn)
else:
do('REPLACED TOC',
write_xar,
fn if in_place else out_fn,
hdr, new_tocdata, f, keep_old)
def write_xar(fn, hdr, tocdata, heap, keep_old=False):
ztocdata = zlib.compress(tocdata)
digest = toc_digest(hdr, ztocdata)
newhdr = dict(hdr,
toc_length_uncompressed=len(tocdata),
toc_length_compressed=len(ztocdata))
outf = NamedTemporaryFile(prefix='.' + os.path.basename(fn),
dir=os.path.dirname(fn),
delete=False)
try:
st_mode = os.stat(fn).st_mode
if os.fstat(outf.fileno()) != st_mode:
os.fchmod(outf.fileno(), st_mode)
except OSError:
pass
try:
outf.writelines([HEADER.pack(newhdr),
ztocdata,
digest])
copyfileobj(heap, outf)
outf.close()
except:
outf.close()
os.unlink(outf.name)
raise
if keep_old:
oldfn = fn + '.old'
if os.path.exists(oldfn):
os.unlink(oldfn)
os.link(fn, oldfn)
os.rename(outf.name, fn)
def strip_toc_signature(xmlstr):
et = etree.fromstring(xmlstr)
toc = et.find('toc')
if not toc:
return None
sig = toc.find('signature')
if not sig:
return None
toc.remove(sig)
return etree.tostring(et)
def main():
parser = argparse.ArgumentParser(sys.argv[0])
parser.add_argument('--dry-run', dest='dry_run', action='store_true',
help='do not write new xar files')
parser.add_argument('--keep-old', dest='keep_old', action='store_true',
help='keep the originals as XARFILE.old')
parser.add_argument('xarfiles', metavar='XARFILE', type=str, nargs='+',
help='the xar files to remove signatures from')
args = parser.parse_args()
for fn in args.xarfiles:
strip_signature(fn, dry_run=args.dry_run, keep_old=args.keep_old)
if __name__ == '__main__':
main()