-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathupxbc
executable file
·2658 lines (2463 loc) · 106 KB
/
upxbc
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
#! /bin/sh
# by [email protected] at Sun Dec 31 19:21:00 CET 2017
""":" #upxbc: UPX-based compressor for execuables and data files
type python2.7 >/dev/null 2>&1 && exec python2.7 -- "$0" ${1+"$@"}
type python2.6 >/dev/null 2>&1 && exec python2.6 -- "$0" ${1+"$@"}
type python2.5 >/dev/null 2>&1 && exec python2.5 -- "$0" ${1+"$@"}
type python2.4 >/dev/null 2>&1 && exec python2.4 -- "$0" ${1+"$@"}
exec python -- ${1+"$@"}; exit 1
This script need Python 2.5, 2.6 or 2.7. Python 3.x won't work. Python 2.4
typically won't work (unless the hashlib module is installed from PyPi).
Typical usage: upxbc -f -o output.c32 input.c32
https://github.com/pts/upxbc
"""
import array
import os
import os.path
import pipes
import struct
import subprocess
import sys
import zlib
verbose = [0]
def parse_struct(fields, data):
values = struct.unpack('<' * (fields[0][1][0] not in '<>') + ''.join(f[1] for f in fields), data)
# TODO(pts): Convert long to int if needed.
return dict(zip((f[0] for f in fields), values))
def dump_struct(fields, data):
if verbose[0] <= 0:
return
format = '<' * (fields[0][1][0] not in '<>') + ''.join(f[1] for f in fields)
values = struct.unpack(format, data)
print '--- Header ' + format
for (field_name, field_type), value in zip(fields, values):
if isinstance(value, (int, long)):
value = '0x%x' % value
else:
value = repr(value)
print '%s = %s' % (field_name, value)
print '---/Header'
def get_elf32_header(ubufsize, load_addr=None, ubufsize2=None):
# ELF 32-bit LSB executable, Intel 80386, version 1 (GNU/Linux), statically linked, stripped.
# Contains ELF EHDR and 1 PHDR (program header).
if load_addr is None:
# Doesn't make a difference in UpxCompressed, using a small value.
#load_addr = 0x8048000
# Works for compression, doesn't work for decompresson.
#load_addr = 0x200
# Minimum value that works for decompression. Smaller values produce:
# ': compressed data violation'.
load_addr = 0x101000
if load_addr & 0xff: # It would work even without alignment. Just for sanity.
raise ValueError('load_addr not aligned.')
if ubufsize2 is None:
return ''.join(( # 0x54 bytes.
'\x7fELF\x01\x01\x01\x03\0\0\0\0\0\0\0\0\x02\0\x03\0\x01\0\0\0',
struct.pack('<L', load_addr + 0x54), # e_entry.
'4\0\0\0\0\0\0\0\0\0\0\x004\0\x20\0\x01\0\x28\0\0\0\0\0\x01\0\0\0\0\0\0\0',
# p_vaddr, p_paddr, p_filesz, p_memsz.
struct.pack('<LLLL', load_addr, load_addr, ubufsize + 0x54, ubufsize + 0x54),
'\x07\0\0\0\x01\0\0\0'))
else:
return ''.join(( # 0x74 bytes.
'\x7fELF\x01\x01\x01\x03\0\0\0\0\0\0\0\0\x02\0\x03\0\x01\0\0\0',
struct.pack('<L', load_addr + 0x54), # e_entry.
'4\0\0\0\0\0\0\0\0\0\0\x004\0\x20\0',
struct.pack('<H', 1 + (ubufsize2 is not None)), # e_phnum.
'\x28\0\0\0\0\0',
# p_type, p_offset, p_vaddr, p_paddr, p_filesz, p_memsz, p_flags, p_align.
struct.pack('<LLLLLLLL', 1, 0, load_addr, load_addr, ubufsize + 0x74, ubufsize + 0x74, 7, 1),
# p_type, p_offset, p_vaddr, p_paddr, p_filesz, p_memsz, p_flags, p_align.
struct.pack('<LLLLLLLL', 1, ubufsize + 0x74, load_addr + ubufsize, load_addr + ubufsize, ubufsize2, ubufsize2, 7, 1)))
def get_compressed_elf32_header(ubufsize, load_addr=0x101000, method=0):
if load_addr != 0x101000:
raise NotImplementedError
mid = struct.pack('<LL', ubufsize + 0x54, ubufsize + 0x54)
# The compressed header must be shorter than the uncompressed one,
# otherwise UPX fails with ': header corrupted'.
if method == 0:
# Same as get_elf32_header(ubufsize).
return ''.join(('\x7f\x45\x4c\x46\x01\x01\x01\x03\0\0\0\0\0\0\0\0\x02\0\x03\0\x01\0\0\0\x54\x10\x10\0\x34\0\0\0\0\0\0\0\0\0\0\0\x34\0\x20\0\x01\0\x28\0\0\0\0\0\x01\0\0\0\0\0\0\0\0\x10\x10\0\0\x10\x10\x00', mid, '\x07\0\0\0\x01\0\0\x00'))
elif method == 2:
return ''.join(('\xdb\x0e\x72\xf9\x7f\x45\x4c\x46\x01\x03\0\x02\0\x0a\x01\x07\xeb\xb6\x65\xbf\x54\x10\x10\0\x34\0\0\x0b\x20\x17\x28\x0b\xff\xcf\x0d\x1b\x01\x14\x23\x03', mid, '\0\0\x40\xb0\x07\x1b\x20\x01\0\0\xff'))
elif method == 5:
return ''.join(('\xf6\x0e\x72\xf9\x7f\x45\x4c\x46\x01\x03\0\x02\0\x15\x01\x0e\x66\xed\xad\xfd\x54\x10\x10\0\x34\0\x01\x17\x20\x2e\x28\x17\x01\x61\xff\xcf\xc6\x29\x46\x06', mid, '\x07\x37\x49\x92\x24\x09\0\0\0\x2a\xff'))
elif method == 8:
return ''.join(('\x5f\x7b\xb2\xf9\x7f\x45\x4c\x46\x01\x03\0\x02\0\x14\x01\x0e\x54\x10\xf6\xbd\x96\xf6\x10\0\x34\0\x01\x16\x20\x2e\x28\x17\x01\x29\xc2\xf6\xff\x1d\x10\x10\x07', mid, '\x07\x37\x4a\x92\x24\x49\0\0\0\x80\xff'))
else:
raise NotImplementedError
def get_upx_prog(to_append=None, _cached=[]):
if to_append is not None:
_cached.append(to_append)
elif not _cached:
mydir = os.path.dirname(__file__) or '.'
prog = os.path.join(mydir, 'tools', 'upx')
# execve(2) does os.path.exist.
if not os.path.isfile(prog):
prog = os.path.join(mydir, 'upx')
# execve(2) does os.path.exist.
if not os.path.isfile(prog):
prog = 'upx' # Search on $PATH.
_cached.append(prog)
return _cached[0]
def run_upx_elf32(
udata, tmp_filename, method, padding_char='\0', padding=0, udata2=None,
load_addr=None):
"""Creates an ELF32 file and runs UPX to compress it.
The compressed file is written to tmp_filename. (Upon an exception, the
contents and existence of tmp_filename is undefined.)
Args:
udata: str or bytes, to be compressed. Will be saved to the first
PT_LOAD segment.
udata2: str, bytes or None, to be compressed. If None, ignored, otherwise
it will be saved to the second PT_LOAD segment.
padding: A nonnegative integer or True or False. If not 0 is specified,
it may affect data and udata. For positive integers, the specified
amount of padding_char will be appended to udata. If it is bool and
it is False, then a magic long enough padding will be appended to
udata. If it is bool and it is True, then a magic long enough
padding will be put to udata, and the original udata will be put to
udata2. The True value usually makes UPX produce a suboptimal
compression ratio, and it never uses a filter, so `method' must
contain '--no-filter' and '--bad-ratio-ok' in this case to avoid
confusion.
Returns:
(uncompressed_elf32_size, uncompressed_elf32_header, padding_data).
"""
if not isinstance(udata, (str, buffer)):
raise TypeError
if not isinstance(method, (list, tuple)):
raise TypeError
if len(padding_char) != 1:
raise ValueError
if '--none' in method:
raise ValueError('run_upx_elf32 does not support --none.')
if padding is True or padding is False:
if udata2 is not None:
raise ValueError('padding as bool does not work with udata2.')
# Now we try to ensure a gain of >=4096 bytes, so that UPX won't report
# ': NotCompressibleException'. To do so, we add some trailing padding which is
# very much compressible. We don't want to add a proportional padding, because
# ultimately we want to keep uncompressible input unchanged.
#
# * With M_LZMA: decompressor + literal is <3404 bytes, 4096 + 3204 == 7600 bytes
# * With others: decompressor + literal is <704 bytes, 4096 + 704 == 4800 bytes
#
# Please note that with UPX 3.94, even if we add 10000 0 bytes of
# padding to udata2, UPX may still report ': NotCompressibleException'
# if udata + padding_data is not compressible (e.g. 10000 0 bytes in
# udata2, empty udata, 1900 0 bytes in padding_data makes UPX fail, but
# 2000 0 bytes in padding_data works; 10000 0 bytes in udata2, 1500
# uncompressible random bytes in udata, 500 0 bytes in padding data
# makes UPX fail). So no matter how much padding we add to udata2, it
# doesn't help if udata + padding_data is uncompressible. Our solution:
# we add all the padding to padding_data, and keep udata2 empty.
padding_size = (4800, 7600)['--lzma' in method]
if padding:
# With padding=True, UPX may choose suboptimal compressing settings
# (even with --ultra-brute), because UPX 3.94 calculates the
# determines the compression method and parameters based on how each
# candidate performs on udata + padding_data (i.e. the first PT_LOAD).
# Since in this case, we'd be passing only padding_data (all 0 bytes)
# with empty udata, UPX will choose method 2 (M_NRV2B_LE32) with some
# suboptimal parameters for the real udata. Even if we specify
# --nrv2d, --nrv2e or --lzma, the parameters are still suboptimal.
# (Example: examples/hello_banchmark.static with glibc 2.19, 664560
# bytes, best method is --lzma, then --nrv2e, but UPX here would
# still choose M_NRV2B_LE32.)
#
# To avoid misunderstandings, we explicitly fail here if
# --bad-ratio-ok is not specified.
if '--bad-ratio-ok' not in method:
raise ValueError(
'Compression ratio with padding=True is usually bad, '
'specify --bad-ratio-ok if it is OK.')
if '--no-filter' not in method:
# Because of https://github.com/upx/upx/issues/171, UPX 3.94 never
# applies a filter in this case, so to avoid confusion we require
# --no-filter explicitly.
raise ValueError('padding=True needs --no-filter.')
udata, udata2 = '', udata
else:
if not isinstance(padding, (int, long)):
raise ValueError
if padding < 0:
raise ValueError
padding_size = padding = int(padding)
if len(udata) + padding_size == 0:
# UPX returns garbage in this case.
raise ValueError('Cannot compress empty data.')
padding_data = padding_char * padding_size or ''
udata2_size = None
if udata2 is not None:
udata2_size = len(udata2)
if '--bad-ratio-ok' in method:
method = [flag for flag in method if flag != '--bad-ratio-ok']
elf32_size = (0x54 + 0x20 * (udata2 is not None) +
len(udata) + padding_size + (udata2_size or 0))
elf32_header = get_elf32_header(
len(udata) + padding_size, ubufsize2=udata2_size, load_addr=load_addr)
if len(elf32_header) != 0x54 + 0x20 * (udata2 is not None):
raise AssertionError
#assert 0, (padding_data, udata2)
f = open(tmp_filename, 'wb')
try:
f.write(elf32_header)
f.write(udata)
if padding_data:
f.write(padding_data)
if udata2 is not None:
f.write(udata2)
finally:
f.close()
os.chmod(tmp_filename, 0700) # Avoid UPX error: ': file not executable'
# -qqq is totally quiet, it doesn't even print the exception.
# -qq prints one line with the sizes.
cmd = [get_upx_prog(), '-qq']
cmd.extend(method)
cmd.extend(('--', tmp_filename))
print >>sys.stderr, (
'info: running with udata_size=%d padding_size=%d udata2_size=%d: %s' %
(len(udata), padding_size, len(udata2 or ''),
' ' .join(map(pipes.quote, cmd))))
try:
p = subprocess.Popen(cmd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
os.remove(tmp_filename)
raise RuntimeError('UPX program not found: %s' % cmd[0])
try:
upx_stdout, upx_stderr = p.communicate('')
finally:
exit_code = p.wait()
if exit_code:
#assert 0, (exit_code, upx_stderr, os.stat(tmp_filename).st_size)
os.remove(tmp_filename)
# 'upx: ...: IOException: file is too small -- skipped\n'
# 'upx: ...: NotCompressibleException\n'
# ': file is too small' in upx_stderr or # We take care of this.
if ': NotCompressibleException' in upx_stderr:
return False, None, None
if ': file is too large' in upx_stderr:
return None, None, None
sys.stderr.write(upx_stderr)
raise RuntimeError('UPX failed with exit_code=0x%x.' % exit_code)
# Don't print upx_stdout, it just contains statistics as a one-liner.
#sys.stderr.write(upx_stderr)
return elf32_size, elf32_header, padding_data
class UpxCompressed(object):
"""Data compressed by UPX."""
# Not using collections.namedtuple because of Python 2.4 compatibility.
# Possible values of self.format, defined in src/conf.h in UPX.
M_NONE = 0 # Not defined by UPX.
M_NRV2B_LE32 = 2
M_NRV2D_LE32 = 5
M_NRV2E_LE32 = 8
M_LZMA = 14
__slots__ = (
# Compression method (algorithm) identifier, one one
# M_NONE (0), M_NRV2B_LE32 (2), M_NRV2D_LE32 (5, rare),
# M_NRV2E_LE32 (8, rare), M_LZMA (14).
'method',
# 0 means no filter, i.e. unfilter doesn't have to be applied after
# decompress.
#
# Possible values for Linux i386 ELF (from
# PackLinuxElf32x86::getFilters in src/p_lx_elf.cpp):
# 0x00, 0x46, 0x49. Filters 0x46 and 0x49 need both filter and
# filter_cto to be filled correctly.
#
# Possible values for UPX in general (from src/filteri.cpp):
# 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
# 0x0b, 0x0c, 0x0d, 0x0e, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
# 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x24, 0x25, 0x26, 0x36,
# 0x46, 0x49, 0x50, 0x51, 0x52, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85,
# 0x86, 0x87, 0x90, 0x91, 0x92, 0x93, 0xa0, 0xa1, 0xa2, 0xa3, 0xb0,
# 0xb1, 0xb2, 0xb3, 0xd0.
'filter',
# A byte (0..255) value, passed as the cto argument to unfilter.
'filter_cto',
# Compressed data as an str.
'compressed_data',
# Size of the uncompressed memory buffer, where the decompressor
# writes its output. At least as much as the size of the uncompressed
# input data. Additional bytes will be filled with padding_char ('\0').
'ubufsize',
# Position-independent i386 machine code for the decompress function.
# Linux i386 ABI, see http://wiki.osdev.org/System_V_ABI
# C signature: int decompress(const char *inp, unsigned ins, char *outp, unsigned *ubufsizep) __attribute__((regparm(0)));
# Call decompress before unfilter.
# You need to know the uncompressed size first, put it to *ubufsizep.
# decompress will modify *ubufsizep, but eventually it will set it back to its
# initial value.
# M_NRV2B_LE32 (but not M_LZMA) ignores the initial value of *ubufsizep.
# Preallocate outp to that size.
# Pass compressed_data as inp[:ins].
# Returns 0 on success.
'decompress_code',
# Position-independent i386 machine code for the unfilter (lxunfilter) function.
# Linux i386 ABI, see http://wiki.osdev.org/System_V_ABI
# C signature: void unfilter(char *outp, unsigned ubufsize, unsigned filter_cto) __attribute__((regparm(0)));
# Call decompress before unfilter.
# No need to call unfilter if filter is 0.
# You need to know the uncompressed size first, put it to ubufsize.
# Preallocate outp to that size.
# Pass output of decompress as outp[:ubufsize].
'unfilter_code',
# Auxiliary info needed for decompression wit UPX.
'compressed_elf32_header',
)
def __init__(self, **kwargs):
for name in self.__slots__:
setattr(self, name, None)
for name, value in sorted(kwargs.iteritems()):
setattr(self, name, value)
def __repr__(self):
return '%s(%s)' % (
type(self).__name__, ', '.join(
'%s=%r' % (name, getattr(self, name))
for name in sorted(self.__slots__)))
def upx_make_uncompressed(udata, need_decompress_code=True):
"""Returns UpxCompressed representing the original, uncompressed data."""
if not isinstance(udata, (str, buffer)):
raise TypeError
return UpxCompressed(
method=0,
filter=0,
filter_cto=0,
compressed_data=str(udata),
ubufsize=len(udata),
# Based on decompress_none.nasm .
decompress_code='\x8bD$\x10\x8b\x009D$\x08t\x04\x83\xc8\xff\xc3VW\x8bt$\x0c\x8b|$\x14\x91\xf3\xa4_^1\xc0\xc3' * bool(need_decompress_code),
unfilter_code='\xc3' * bool(need_decompress_code), # ret.
compressed_elf32_header='',
)
def adler32_combine(adler1, adler2, len2):
"""Based on adler32_combine_ in zlib."""
adler1, adler2 = adler1 & 0xffffffff, adler2 & 0xffffffff
rem = (len2 % 65521) & 0xffffffff
sum1 = adler1 & 0xffff
sum2 = (rem * sum1) % 65521
sum1 += (adler2 & 0xffff) + 65521 - 1
sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + 65521 - rem
if sum1 >= 65521: sum1 -= 65521
if sum1 >= 65521: sum1 -= 65521
if sum2 >= (65521 << 1): sum2 -= (65521 << 1)
if sum2 >= 65521: sum2 -= 65521
return sum1 | (sum2 << 16)
#s1 = 'foo'
#s2 = 'MYBARBAZ'
#assert adler32_combine(zlib.adler32(s1), zlib.adler32(s2), len(s2)) == (zlib.adler32(s1 + s2) & 0xffffffff)
def pack_fields(fields):
output = []
for name, format, value in fields:
#print (name, format, value)
if format == '.str':
output.append(str(value))
elif format == '.pad':
output.append('\0' * (-sum(len(x) for x in output) % value))
elif format == '.phcs': # PackHeader checksum byte of the `value' preceding bytes.
buf = ''
i = len(output)
while len(buf) < value and i > 0:
i -= 1
buf = output[i] + buf
if len(buf) != value:
raise AssertionError
output.append(chr(sum(ord(c) for c in buf) % 251))
elif format == '.minsize':
size = sum(len(x) for x in output)
if size < value:
output.append('\0' * (value - size))
else:
output.append(struct.pack('<' * (format[0][0] not in '<>') + format, value))
#assert 0, [sum(len(x) for x in output), bend_ofs]
return ''.join(output)
def build_elf32_for_upx_decompression(
ch, tmp_filename, udata_size, udata_adler32, load_addr):
"""Builds a Linux i386 ELF executable which UPX can decompress."""
if udata_size > ch.ubufsize:
raise ValueError
l_checksum = 0 # Fake but OK (accepted by UPX).
loader_data = '\xc3' * 16 # Fake but OK (accepted by UPX).
elf32_header = get_compressed_elf32_header(ch.ubufsize, method=0)
if ch.method in (2, 5, 8):
compressed_elf32_header = get_compressed_elf32_header(
ch.ubufsize, method=ch.method, load_addr=load_addr)
elif ch.method == 14 and not ch.compressed_elf32_header:
# We don't care about compression ratio here, because
# compressed_elf32_header is just temporary.
ch2 = upx_compress32(
elf32_header, tmp_filename, method='--lzma --no-filter --bad-ratio-ok')
if ch2.ubufsize != 0x54:
raise AssertionError('Unexpected padding in LZMA-compressed ELF32 header.')
compressed_elf32_header = ch2.compressed_data
del ch2
elif not ch.compressed_elf32_header:
raise ValueError('compressed_elf32_header empty.')
else:
compressed_elf32_header = ch.compressed_elf32_header
if not compressed_elf32_header:
raise ValueError
# elf32_header is only needed for the checksum computation.
bend_ofs = 164 + len(compressed_elf32_header) + len(ch.compressed_data) # Offset of ld_pad8.
loader_ofs = bend_ofs + (-bend_ofs & 3)
l_version = 13
l_format = 12
fields = (
('ei_mag', '4s', '\x7fELF'),
('ei_class', 'B', 1),
('ei_data', 'B', 1),
('ei_version', 'B', 1),
('e_osabi', 'B', 3),
('e_abiversion', 'B', 0),
('e_pad', '7s', '\0\0\0\0\0\0\0'),
('e_type', 'H', 2),
('e_machine', 'H', 3),
('e_version', 'L', 1),
('e_entry', 'L', 0xc01000 + loader_ofs + 8),
('e_phoff', 'L', 0x34),
('e_shoff', 'L', 0),
('e_flags', 'L', 0),
('e_ehsize', 'H', 0x34),
('e_phentsize', 'H', 0x20),
('e_phnum', 'H', 2),
('e_shentsize', 'H', 0x28),
('e_shnum', 'H', 0),
('e_shstrndx', 'H', 0),
('p0_type', 'L', 1),
('p0_offset', 'L', 0),
('p0_vaddr', 'L', 0xc01000),
('p0_paddr', 'L', 0xc01000),
('p0_filesz', 'L', loader_ofs + len(loader_data)),
('p0_memsz', 'L', loader_ofs + len(loader_data)),
('p0_flags', 'L', 5),
('p0_align', 'L', 0x1000),
('p1_type', 'L', 1),
('p1_offset', 'L', (load_addr + 0x54 + ch.ubufsize) & 0xfff),
('p1_vaddr', 'L', load_addr + 0x54 + ch.ubufsize),
('p1_paddr', 'L', load_addr + 0x54 + ch.ubufsize),
('p1_filesz', 'L', 0),
('p1_memsz', 'L', 0),
('p1_flags', 'L', 6),
('p1_align', 'L', 0x1000),
('l_checksum', 'L', l_checksum),
('l_magic', '4s', 'UPX!'),
('l_lsize', 'H', len(loader_data)),
('l_version', 'B', l_version),
('l_format', 'B', l_format),
('p_progid', 'L', 0),
('p_filesize', 'L', 0x54 + ch.ubufsize),
('p_blocksize', 'L', 0x54 + ch.ubufsize),
('sz0_unc', 'L', 0x54),
('sz0_cpr', 'L', len(compressed_elf32_header)),
('b0_method', 'B', ch.method),
('b0_ftid', 'B', 0),
('b0_cto8', 'B', 0),
('b0_unused', 'B', 0),
('b0_cpr', '.str', compressed_elf32_header),
('sz1_unc', 'L', ch.ubufsize),
('sz1_cpr', 'L', len(ch.compressed_data)),
('b1_method', 'B', ch.method),
('b1_ftid', 'B', ch.filter),
('b1_cto8', 'B', ch.filter_cto),
('b1_unused', 'B', 0),
('b1_cpr', '.str', ch.compressed_data),
('ld_pad4', '.pad', 4),
#('ld_ofsa', 'L', loader_ofs - 0x8c), # Why 0x8c?
#('ld_ofsb', 'L', loader_ofs - 4),
('ld_data', '.str', loader_data),
('ld_eof', '12s', '\0\0\0\0UPX!\0\0\0\0'),
('ph_magic', '4s', 'UPX!'),
('ph_version', 'B', l_version),
('ph_format', 'B', l_format),
('ph_method', 'B', ch.method),
('ph_level', 'B', 10), # Educated guess.
('ph_u_adler', 'L', adler32_combine(zlib.adler32(elf32_header), zlib.adler32('\0' * (ch.ubufsize - udata_size), udata_adler32), ch.ubufsize)),
('ph_c_adler', 'L', zlib.adler32(ch.compressed_data, zlib.adler32(compressed_elf32_header)) & 0xffffffff),
('ph_u_len', 'L', ch.ubufsize),
('ph_c_len', 'L', len(ch.compressed_data)),
('ph_u_file_size', 'L', 0x54 + ch.ubufsize),
('ph_filter', 'B', ch.filter),
('ph_filter_cto', 'B', ch.filter_cto),
('ph_n_mru1', 'B', 0), # Not stored anywhere else.
('ph_checksum', '.phcs', 27),
('overlay_ofs', 'L', 0x80),
('minsize_pad', '.minsize', 0x200),
)
return pack_fields(fields)
UPX_NONLZMA_EFFORT_METHOD_FLAGS = (
'--best', '-1', '-2', '-3', '-4', '-5', '-6', '-7', '-8', '-9')
UPX_EFFORT_METHOD_FLAGS = UPX_NONLZMA_EFFORT_METHOD_FLAGS + (
'--brute', '--ultra-brute')
UPX_NRV_METHOD_FLAGS = ('--nrv2b', '--nrv2d', '--nrv2e')
def get_upx_method_flags(method, do_add_lzma_by_default=True):
if isinstance(method, str):
method = method.replace(',', ' ').split()
method = ['-' * (1 + (flag not in '123456789')) + flag for flag in
(flag.strip('-') for flag in method) if flag]
has_effort = len([1 for flag in method if flag in UPX_EFFORT_METHOD_FLAGS])
has_nonlzma_effort = len(
[1 for flag in method if flag in UPX_NONLZMA_EFFORT_METHOD_FLAGS])
has_nrv = len(
[1 for flag in method if flag in UPX_NRV_METHOD_FLAGS])
method_flags = set(
flag for flag in method if flag in UPX_NRV_METHOD_FLAGS or
flag == '--lzma' or flag == '--none')
if len(method_flags) > 1:
# UPX would make the last one take effect.
raise ValueError(
'Multiple method flags specified: %s' % ' '.join(sorted(method_flags)))
if method_flags and ('--brute' in method or '--ultra-brute' in method):
raise ValueError('Method flags not compatible with --*brute: %s' %
' '.join(sorted(method_flags)))
if '--none' in method:
method[:] = [flag for flag in method if flag not in (
'--none', '--no-filter', '--small', '--bad-ratio-ok')]
if method:
raise ValueError('--none must be specified alone.')
return ['--none', '--no-lzma']
if '--no-lzma' in method:
if '--lzma' in method:
raise ValueError('Both --lzma and --no-lzma was specified.')
if not has_effort:
# `--ultra-brute --no-lzma' doesn't produce LZMA output.
method[:0] = ('--ultra-brute',)
elif '--lzma' in method:
if has_nonlzma_effort:
# `--best --lzma' is equivalent to `--lzma', and it forces LZMA.
# To avoid confusion, only --lzma should be specified.
raise ValueError(
'If you want LZMA-only output, specify --lzma without --best or -<n>'
'; you get LZMA-or-others by default.')
if not has_effort:
# `--ultra-brute --lzma' and `--brute --lzma' may still produce
# non-LZMA output, but `--best --lzma' forces LZMA output.
# So does `--lzma', so we don't add `--best' here. But we just add it.
method[:0] = ('--best',)
else:
if not has_effort:
if has_nrv:
# --brute or --ultra-brute would shadow --nrv... , and it may make
# --UPX choose the wrong NRV algorithm.
method[:0] = ('--best', '--no-lzma')
elif do_add_lzma_by_default:
method[:0] = ('--ultra-brute', '--lzma')
else:
method[:0] = ('--ultra-brute', '--no-lzma')
elif has_nonlzma_effort:
# Doesn't make a difference, just makes it explicit.
method[:0] = ('--no-lzma',)
elif has_nrv: # --nrv... with --brute or --ultra-brute.
raise ValueError(
'--brute or --ultra-brute would shadow --nrv... ; '
'specify --best instead.')
elif do_add_lzma_by_default:
# --brute or --ultra-brute, but no --lzma.
# Doesn't make a difference, just makes it explicit.
method[:0] = ('--lzma',) # Make it explicit.
else:
method[:0] = ('--no-lzma',)
if ('--lzma' in method) + ('--no-lzma' in method) != 1:
raise AssertionError
return method
assert get_upx_method_flags('') == ['--ultra-brute', '--lzma']
assert get_upx_method_flags('--lzma') == ['--best', '--lzma']
assert get_upx_method_flags('--nrv2b') == ['--best', '--no-lzma', '--nrv2b']
assert get_upx_method_flags('--no-lzma') == ['--ultra-brute', '--no-lzma']
EHDR_FIELDS = (
('ei_mag', '4s'),
('ei_class', 'B'),
('ei_data', 'B'),
('ei_version', 'B'),
('e_osabi', 'B'),
('e_abiversion', 'B'),
('e_pad', '7s'),
('e_type', 'H'),
('e_machine', 'H'),
('e_version', 'L'),
('e_entry', 'L'),
('e_phoff', 'L'),
('e_shoff', 'L'),
('e_flags', 'L'),
('e_ehsize', 'H'),
('e_phentsize', 'H'),
('e_phnum', 'H'),
('e_shentsize', 'H'),
('e_shnum', 'H'),
('e_shstrndx', 'H'),
)
PHDR_FIELDS = ( # ELF program header.
('p_type', 'L'),
('p_offset', 'L'),
('p_vaddr', 'L'),
('p_paddr', 'L'),
('p_filesz', 'L'),
('p_memsz', 'L'),
('p_flags', 'L'),
('p_align', 'L'),
)
def parse_elf32_compressed_by_upx(
data, udata, padding_data, do_swap, elf32_size, elf32_header,
need_decompress_code, decompress_code=None, unfilter_code=None,
do_check_size=True):
"""Returns an UpxCompressed object."""
i = 0
ehdr = parse_struct(EHDR_FIELDS, data[i : i + 0x34])
dump_struct(EHDR_FIELDS, data[i : i + 0x34])
i += 0x34
if ehdr['ei_mag'] != '\x7fELF':
raise ValueError
if ehdr['ei_class'] != 1:
raise ValueError
if ehdr['ei_data'] != 1:
raise ValueError
if ehdr['ei_version'] != 1:
raise ValueError
if ehdr['e_osabi'] not in (0, 3): # 0: System V, 3: Linux.
raise ValueError
if ehdr['e_abiversion'] != 0:
raise ValueError
#if ehdr['e_pad'] != '\0\0\0\0\0\0\0':
# raise ValueError
if ehdr['e_type'] != 2:
raise ValueError('Expected an executable file.')
if ehdr['e_machine'] != 3: # x86.
raise ValueError('Expected i386.')
if ehdr['e_version'] != 1:
raise ValueError
if ehdr['e_ehsize'] != 0x34:
raise ValueError
if ehdr['e_phentsize'] != 0x20:
raise ValueError
if ehdr['e_flags'] != 0:
raise ValueError
if ehdr['e_shentsize'] not in (0, 0x28):
raise ValueError
if ehdr['e_shnum'] != 0:
raise ValueError
if ehdr['e_phnum'] != 2:
raise ValueError(
'Bad number of program header entries: %d' % ehdr['e_phnum'])
if ehdr['e_phoff'] != i:
raise ValueError
phdr = None
for phi in xrange(ehdr['e_phnum']):
phdri = parse_struct(PHDR_FIELDS, data[i : i + 0x20])
# phi=0 p_vaddr=p_paddr=0xc01000
# phi=1 p_vaddr=p_paddr=0x1000 + load_addr
dump_struct(PHDR_FIELDS, data[i : i + 0x20])
i += 0x20
if phdri['p_memsz'] != 0:
if phdr is not None:
raise ValueError('Too many phdrs.')
phdr = phdri
elf_hdr_size = i
if phdr is None:
raise ValueError('Missing phdr.')
if phdr['p_type'] != 1: # PT_LOAD.
raise ValueError
if phdr['p_memsz'] != phdr['p_filesz']:
raise ValueError
p_filesz4 = phdr['p_filesz']
p_filesz4 += -p_filesz4 & 3 # 7 and 15 don't work here.
if phdr['p_vaddr'] != phdr['p_paddr']:
raise ValueError
if phdr['p_memsz'] == 0:
raise ValueError
if phdr['p_offset'] != 0:
raise ValueError
# TODO(pts): Where is the base vaddr 0x00c01000 specified in the UPX sources?
# Can it change if we make the load_addr smaller?
if data[p_filesz4 : p_filesz4 + 16] != '\0\0\0\0UPX!\0\0\0\0UPX!':
raise ValueError(p_filesz4)
# Based on PackLinuxElf64::unpack in p_lx_elf.cpp and p_unix.h .
l_info_fields = ( # 12-byte trailer in header for loader
('l_checksum', 'L'), # TODO(pts): Check this adler32. (It doesn't seem to match.)
('l_magic', '4s'), # UPX_MAGIC_LE32 == 'UPX!'.
('l_lsize', 'H'), # Decompressor size. 0x818 for ls.c32, 0x1200 for lua.c32.
('l_version', 'B'), # Must be at least 10, getVersion() returns 13.
('l_format', 'B'), # UPX_F_LINUX_ELF_i386 == 12.
)
l_info = parse_struct(l_info_fields, data[i : i + 12])
dump_struct(l_info_fields, data[i : i + 12])
i += 12
if l_info['l_magic'] != 'UPX!':
raise ValueError('Bad l_magic.')
if l_info['l_format'] != 12:
raise ValueError('Bad l_format.')
if not 10 <= l_info['l_version'] <= 14:
raise ValueError('Unsupported l_version: %d' % l_info['l_version'])
p_info_fields = ( # 12-byte packed program header.
('p_progid', 'L'),
('p_filesize', 'L'),
('p_blocksize', 'L'),
)
p_info = parse_struct(p_info_fields, data[i : i + 12])
dump_struct(p_info_fields, data[i : i + 12])
i += 12
if p_info['p_progid'] != 0:
raise ValueError('Bad p_progid.')
if p_info['p_filesize'] != elf32_size:
raise ValueError
if p_info['p_blocksize'] != elf32_size:
raise ValueError
last_b_info = data_b_info = padding_b_info = None
c_adler32 = 1 # zlib.adler32('').
compressed_elf32_header = None
# The upx binary calls upx_ucl_compress and upx_lzma_compress is called
# with 3 or 4 different block sizes:
#
# * 0x54 or 0x74 (for the ELF32 header). This is block 0 here.
# * 0x65e == 1630 this is the modified stub_i386_linux_elf_fold of uncompressed size sizeof(stub_i386_linux_elf_fold) - fold_hdrlen == 1758 - 128 == 1630
# buildLinuxLoader(
# stub_i386_linux_elf_entry, sizeof(stub_i386_linux_elf_entry),
# tmp, sizeof(stub_i386_linux_elf_fold), ft );
# This is not present in a block here, it's in FOLDEXEC, after load_end_ofs.
# * len(udata) + len(padding_data). This is block 1 here if do_swap=False.
# * len(padding_data). This is block 1 here if do_swap=False.
# * len(udata). This is block 2 here if do_swap=True.
for _ in xrange(2 + bool(do_swap)):
# Lots of filters (b_ftid) are defined in src/filteri.cpp .
# Packer::getDecompressorSections (contains NRV and LZMA)
# Method can be (for elf32):
# * with --small: (!! which is the default? which one is smaller? should we specify --small? also for compress_flat16 !!)
# * M_LZMA == 14: LZMA_ELF00,LZMA_DEC10,LZMA_DEC30.
# * M_NRV2B_LE32 == 2: N2BSMA10,N2BDEC10,N2BSMA20,N2BDEC20,N2BSMA30,N2BDEC30,N2BSMA40,N2BSMA50,N2BDEC50,N2BSMA60,N2BDEC60.
# * M_NRV2D_LE32 == 5: N2DSMA10,N2DDEC10,N2DSMA20,N2DDEC20,N2DSMA30,N2DDEC30,N2DSMA40,N2DSMA50,N2DDEC50,N2DSMA60,N2DDEC60.
# * M_NRV2E_LE32 == 8: N2ESMA10,N2EDEC10,N2ESMA20,N2EDEC20,N2ESMA30,N2EDEC30,N2ESMA40,N2ESMA50,N2EDEC50,N2ESMA60,N2EDEC60.
# * without --small (fast) (!! why? 3 bytes extra output?):
# * M_LZMA == 14 (lua.c32): LZMA_ELF00,LZMA_DEC20,LZMA_DEC30.
# * M_NRV2B_LE32 == 2 (ls.c32): N2BFAS10,+80CXXXX,N2BFAS11,N2BDEC10,N2BFAS20,N2BDEC20,N2BFAS30,N2BDEC30,N2BFAS40,N2BFAS50,N2BDEC50,N2BFAS60,+40CXXXX,N2BFAS61,N2BDEC60.
# * M_NRV2D_LE32 == 5: N2DFAS10,+80CXXXX,N2DFAS11,N2DDEC10,N2DFAS20,N2DDEC20,N2DFAS30,N2DDEC30,N2DFAS40,N2DFAS50,N2DDEC50,N2DFAS60,+40CXXXX,N2DFAS61,N2DDEC60.
# * M_NRV2E_LE32 == 8: N2EFAS10,+80CXXXX,N2EFAS11,N2EDEC10,N2EFAS20,N2EDEC20,N2EFAS30,N2EDEC30,N2EFAS40,N2EFAS50,N2EDEC50,N2EFAS60,+40CXXXX,N2EFAS61,N2EDEC60.
# PackLinuxElf32x86::addStubEntrySections (both b_method and b_ftid)
# LEXEC000 call main; decompress: ...
# LXUNF000?
# LXUNF002?
# MRUBYTE0?
# LXMRU005?
# LXMRU006?
# LXMRU007?
# LXUNF008?
# LXUNF010?
# LEXEC009?
# LEXEC010
# calls addLoader(getDecompressorSections(), NULL);
# LEXEC015
# LXUNF042?
# calls addFilter32(ft->id);?
# LXMRU058?
# LXUNF035?
# LEXEC017? (if no filter)
# --- This is the end of the decompression udata.
# IDENTSTR '\n\0$Info: This file is packed with the UPX executable packer http://upx.sf.net $\n\0$Id: UPX ' ... '3.94 Copyright (C) 1996-2017 the UPX Team. All Rights Reserved. $\n\0'
# LEXEC020
# LUNMP000?
# LUNMP001?
# LEXEC025
# FOLDEXEC Patched and then compressed stub_i386_linux_elf_fold, without its first 128 bytes. The uncompressed version is typically 1630 bytes.
b_info_fields = ( # 12-byte header before each compressed block.
('sz_unc', 'L'), # Uncompressed size.
('sz_cpr', 'L'), # Compressed size.
('b_method', 'B'), # Compression algorithm.
('b_ftid', 'B'), # Filter ID.
('b_cto8', 'B'), # Filter parameter.
('b_unused', 'B'),
)
last_b_info = parse_struct(b_info_fields, data[i : i + 12])
dump_struct(b_info_fields, data[i : i + 12])
i += 12
last_b_info['c_ofs'] = i # Compressed data starts here.
last_b_cpr = buffer(data, i, last_b_info['sz_cpr'])
if compressed_elf32_header is None:
compressed_elf32_header = last_b_cpr
elif padding_b_info is None:
padding_b_info = last_b_info
else:
data_b_info = last_b_info
c_adler32 = zlib.adler32(last_b_cpr, c_adler32)
i += last_b_info['sz_cpr']
c_adler32 &= 0xffffffff
if do_swap:
if data_b_info is None:
raise AssertionError
if data_b_info['sz_unc'] != len(udata):
raise ValueError
if padding_b_info['sz_unc'] != len(padding_data):
raise ValueError
if padding_b_info['sz_cpr'] > 0xff:
raise ValueError('Padding is not compressible enough.')
else:
if padding_b_info is None or data_b_info is not None:
raise AssertionError
padding_b_info, data_b_info = None, padding_b_info
if data_b_info['sz_unc'] != len(udata) + len(padding_data):
raise ValueError
compressed_data = buffer(data, data_b_info['c_ofs'], data_b_info['sz_cpr'])
# This can happen when compressing '\0' with padding=True.
if data_b_info['b_method'] == 0:
if buffer(udata) != compressed_data:
raise ValueError
# See funpad4(fi) in PackLinuxElf32::unpack.
i += (-i & 0x3) # Round up to 4 bytes.
loader_ofs = i
if verbose[0] >= 1:
print 'loader_ofs = 0x%x' % i
after_loader_ofs = loader_ofs + l_info['l_lsize']
if data[after_loader_ofs : after_loader_ofs + 16] != '\0\0\0\0UPX!\0\0\0\0UPX!':
raise ValueError
if after_loader_ofs != p_filesz4:
raise ValueError('Bad l_lsize.')
if after_loader_ofs != len(data) - 48:
raise ValueError('Expected PackHeader near EOF.')
before_loader_pad = -i & 0x7
i += before_loader_pad # Round up to 8 bytes. 4 or 16 don't work.
# Loader starts here at i (with ofsa).
ofsa, ofsb = struct.unpack('<LL', data[i : i + 8])
i += 8
sizea = i - ofsa
# What are these offsets? Who emits them?
if verbose[0] >= 1:
print 'ofsa = 0x%x' % ofsa
print 'ofsb = 0x%x' % ofsb
print 'sizea = 0x%x' % sizea
if i != (ehdr['e_entry'] - phdr['p_vaddr']):
raise ValueError(
'Bad entry point: i=0x%x ofs=0x%x' %
(i, ehdr['e_entry'] - phdr['p_vaddr']))
if i != ofsb + 4:
raise ValueError('Bad ofsb.')
if not 0 <= sizea < 0x200: # Typically 0x8c. Why?
raise ValueError('Bad sizea.')
lexec000_ofs = i
if data[i] != '\xe8': # `call main' in the beginning of LEXEC000
raise ValueError('Bad loader start byte.')
if data_b_info['b_ftid'] != 0 and (data[i + 5] != '\xeb' or data[i + 6] > '\x7f'):
# This is the jump to the real decompress routine.
raise ValueError('Bad decompress start byte.')
i += l_info['l_lsize'] - 8 - before_loader_pad
if i != after_loader_ofs:
raise AssertionError
i += 12
# None of these checksums seems to match, we don't care, because UPX
# doesn't care either when decompressing.
#assert 0, (l_info['l_checksum'] & 0xffffffff, zlib.adler32(
# buffer(data, loader_ofs, l_info['l_lsize']), 1) & 0xffffffff)
# PackHeader::putPackHeader called from pack4().
ph_fields = ( # PackHeader.
('ph_alignment', '<0s'),
('ph_magic', '4s'),
('ph_version', 'B'),
('ph_format', 'B'),
('ph_method', 'B'),
('ph_level', 'B'), # Not stored anywhere else.
('ph_u_adler', 'L'),
('ph_c_adler', 'L'),
('ph_u_len', 'L'),
('ph_c_len', 'L'),
('ph_u_file_size', 'L'),
('ph_filter', 'B'),
('ph_filter_cto', 'B'),
('ph_n_mru1', 'B'), # Not stored anywhere else.
('ph_checksum', 'B'),
)
ph = parse_struct(ph_fields, data[i : i + 32])
ph_checksum = sum(ord(c) for c in buffer(data, i + 4, 27)) % 251
dump_struct(ph_fields, data[i : i + 32])
overlay_ofs, = struct.unpack('<L', data[i + 32 : i + 36])
if verbose[0] >= 1:
print 'overlay_ofs = 0x%x' % overlay_ofs
i += 36
if i != len(data):
raise ValueError('Expected EOF on compressed ELF32 executable.')
if overlay_ofs != elf_hdr_size + 12:
raise ValueError
if ph['ph_magic'] != 'UPX!':
raise ValueError('Bad l_magic.')
if ph['ph_version'] != l_info['l_version']:
raise ValueError
if ph['ph_format'] != l_info['l_format']:
raise ValueError
if (ph['ph_method'] != data_b_info['b_method'] and
data_b_info['b_method'] != 0):
raise ValueError
#if ph['ph_level'] != ...: # Not stored anywhere else.
# raise ValueError
if do_swap:
u_adler32 = zlib.adler32(udata, zlib.adler32(padding_data, zlib.adler32(elf32_header))) & 0xffffffff
else:
u_adler32 = zlib.adler32(padding_data, zlib.adler32(udata, zlib.adler32(elf32_header))) & 0xffffffff
if ph['ph_u_adler'] != u_adler32:
raise ValueError
if ph['ph_c_adler'] != c_adler32:
raise ValueError
if ph['ph_u_len'] != last_b_info['sz_unc']: # Only the last block.
raise ValueError
if ph['ph_c_len'] != last_b_info['sz_cpr']: # Only the last block.
raise ValueError
if ph['ph_u_file_size'] != elf32_size:
raise ValueError
if ph['ph_filter'] != data_b_info['b_ftid']:
raise ValueError
if ph['ph_filter_cto'] != data_b_info['b_cto8']:
raise ValueError
#if ph['ph_n_mru1'] != ...: # Not stored anywhere else.
# raise ValueError
if ph['ph_checksum'] != ph_checksum:
raise ValueError
if do_check_size and len(compressed_data) >= len(udata):
return upx_make_uncompressed(udata, need_decompress_code=need_decompress_code)
if data_b_info['b_method'] == 0:
raise ValueError
i = data.find('\n\0$Info: This file is packed with the UPX executable packer http://upx.sf.net $\n\0$Id: UPX ', loader_ofs) # identbig.
if i < 0:
i = data.find(' the UPX Team. All Rights Reserved. http://upx.sf.net $\n\0', loader_ofs) # identsmall.
if i < 0:
# This can be cause by --small being specified at least twice (then it
# will have only UPX_VERSION_STRING4, i.e. "3.94\0").
raise ValueError('UPX end-of-decompress signature not found: %r.' % data[loader_ofs:])
if data[i - 23 : i - 4] != '\n$Id: UPX (C) 1996-':
raise ValueError
i -= 23
# It's important to crop at i now, because it is followed by the
# compressed FOLDEXEC (stub_i386_linux_elf_fold), which is <1630 bytes
# (less because of compression).
loader_end_ofs = i
if (do_check_size and need_decompress_code and
len(compressed_data) + (loader_end_ofs - loader_ofs) >=
len(udata) + 0x10):
return upx_make_uncompressed(udata)