-
Notifications
You must be signed in to change notification settings - Fork 0
/
PyLnk.py
1995 lines (1718 loc) · 69.3 KB
/
PyLnk.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
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 python3
# original version written by Tim-Christian Mundt (2011):
# https://sourceforge.net/p/pylnk/code/HEAD/tree/trunk/pylnk.py
# converted to python3 by strayge:
# https://github.com/strayge/pylnk
import argparse
import ntpath
import os
import re
import time
from datetime import datetime
from io import BytesIO, IOBase
from pprint import pformat
from struct import pack, unpack
from typing import Dict, Optional, Tuple, Union
DEFAULT_CHARSET = 'cp1251'
# ---- constants
_SIGNATURE = b'L\x00\x00\x00'
_GUID = b'\x01\x14\x02\x00\x00\x00\x00\x00\xc0\x00\x00\x00\x00\x00\x00F'
_LINK_INFO_HEADER_DEFAULT = 0x1C
_LINK_INFO_HEADER_OPTIONAL = 0x24
_LINK_FLAGS = (
'HasLinkTargetIDList',
'HasLinkInfo',
'HasName',
'HasRelativePath',
'HasWorkingDir',
'HasArguments',
'HasIconLocation',
'IsUnicode',
'ForceNoLinkInfo',
# new
'HasExpString',
'RunInSeparateProcess',
'Unused1',
'HasDarwinID',
'RunAsUser',
'HasExpIcon',
'NoPidlAlias',
'Unused2',
'RunWithShimLayer',
'ForceNoLinkTrack',
'EnableTargetMetadata',
'DisableLinkPathTracking',
'DisableKnownFolderTracking',
'DisableKnownFolderAlias',
'AllowLinkToLink',
'UnaliasOnSave',
'PreferEnvironmentPath',
'KeepLocalIDListForUNCTarget',
)
_FILE_ATTRIBUTES_FLAGS = (
'read_only', 'hidden', 'system_file', 'reserved1',
'directory', 'archive', 'reserved2', 'normal',
'temporary', 'sparse_file', 'reparse_point',
'compressed', 'offline', 'not_content_indexed',
'encrypted',
)
_MODIFIER_KEYS = ('SHIFT', 'CONTROL', 'ALT')
WINDOW_NORMAL = "Normal"
WINDOW_MAXIMIZED = "Maximized"
WINDOW_MINIMIZED = "Minimized"
_SHOW_COMMANDS = {1: WINDOW_NORMAL, 3: WINDOW_MAXIMIZED, 7: WINDOW_MINIMIZED}
_SHOW_COMMAND_IDS = dict((v, k) for k, v in _SHOW_COMMANDS.items())
DRIVE_UNKNOWN = "Unknown"
DRIVE_NO_ROOT_DIR = "No root directory"
DRIVE_REMOVABLE = "Removable"
DRIVE_FIXED = "Fixed (Hard disk)"
DRIVE_REMOTE = "Remote (Network drive)"
DRIVE_CDROM = "CD-ROM"
DRIVE_RAMDISK = "Ram disk"
_DRIVE_TYPES = {0: DRIVE_UNKNOWN,
1: DRIVE_NO_ROOT_DIR,
2: DRIVE_REMOVABLE,
3: DRIVE_FIXED,
4: DRIVE_REMOTE,
5: DRIVE_CDROM,
6: DRIVE_RAMDISK}
_DRIVE_TYPE_IDS = dict((v, k) for k, v in _DRIVE_TYPES.items())
_KEYS = {
0x30: '0', 0x31: '1', 0x32: '2', 0x33: '3', 0x34: '4', 0x35: '5', 0x36: '6',
0x37: '7', 0x38: '8', 0x39: '9', 0x41: 'A', 0x42: 'B', 0x43: 'C', 0x44: 'D',
0x45: 'E', 0x46: 'F', 0x47: 'G', 0x48: 'H', 0x49: 'I', 0x4A: 'J', 0x4B: 'K',
0x4C: 'L', 0x4D: 'M', 0x4E: 'N', 0x4F: 'O', 0x50: 'P', 0x51: 'Q', 0x52: 'R',
0x53: 'S', 0x54: 'T', 0x55: 'U', 0x56: 'V', 0x57: 'W', 0x58: 'X', 0x59: 'Y',
0x5A: 'Z', 0x70: 'F1', 0x71: 'F2', 0x72: 'F3', 0x73: 'F4', 0x74: 'F5',
0x75: 'F6', 0x76: 'F7', 0x77: 'F8', 0x78: 'F9', 0x79: 'F10', 0x7A: 'F11',
0x7B: 'F12', 0x7C: 'F13', 0x7D: 'F14', 0x7E: 'F15', 0x7F: 'F16', 0x80: 'F17',
0x81: 'F18', 0x82: 'F19', 0x83: 'F20', 0x84: 'F21', 0x85: 'F22', 0x86: 'F23',
0x87: 'F24', 0x90: 'NUM LOCK', 0x91: 'SCROLL LOCK'
}
_KEY_CODES = dict((v, k) for k, v in _KEYS.items())
ROOT_MY_COMPUTER = 'MY_COMPUTER'
ROOT_MY_DOCUMENTS = 'MY_DOCUMENTS'
ROOT_NETWORK_SHARE = 'NETWORK_SHARE'
ROOT_NETWORK_SERVER = 'NETWORK_SERVER'
ROOT_NETWORK_PLACES = 'NETWORK_PLACES'
ROOT_NETWORK_DOMAIN = 'NETWORK_DOMAIN'
ROOT_INTERNET = 'INTERNET'
RECYCLE_BIN = 'RECYCLE_BIN'
ROOT_CONTROL_PANEL = 'CONTROL_PANEL'
ROOT_USER = 'USERPROFILE'
ROOT_UWP_APPS = 'APPS'
_ROOT_LOCATIONS = {
'{20D04FE0-3AEA-1069-A2D8-08002B30309D}': ROOT_MY_COMPUTER,
'{450D8FBA-AD25-11D0-98A8-0800361B1103}': ROOT_MY_DOCUMENTS,
'{54a754c0-4bf1-11d1-83ee-00a0c90dc849}': ROOT_NETWORK_SHARE,
'{c0542a90-4bf0-11d1-83ee-00a0c90dc849}': ROOT_NETWORK_SERVER,
'{208D2C60-3AEA-1069-A2D7-08002B30309D}': ROOT_NETWORK_PLACES,
'{46e06680-4bf0-11d1-83ee-00a0c90dc849}': ROOT_NETWORK_DOMAIN,
'{871C5380-42A0-1069-A2EA-08002B30309D}': ROOT_INTERNET,
'{645FF040-5081-101B-9F08-00AA002F954E}': RECYCLE_BIN,
'{21EC2020-3AEA-1069-A2DD-08002B30309D}': ROOT_CONTROL_PANEL,
'{59031A47-3F72-44A7-89C5-5595FE6B30EE}': ROOT_USER,
'{4234D49B-0245-4DF3-B780-3893943456E1}': ROOT_UWP_APPS,
}
_ROOT_LOCATION_GUIDS = dict((v, k) for k, v in _ROOT_LOCATIONS.items())
TYPE_FOLDER = 'FOLDER'
TYPE_FILE = 'FILE'
_ENTRY_TYPES = {
0x00: 'KNOWN_FOLDER',
0x31: 'FOLDER',
0x32: 'FILE',
0x35: 'FOLDER (UNICODE)',
0x36: 'FILE (UNICODE)',
0x802E: 'ROOT_KNOWN_FOLDER',
# founded in doc, not tested
0x1f: 'ROOT_FOLDER',
0x61: 'URI',
0x71: 'CONTROL_PANEL',
}
_ENTRY_TYPE_IDS = dict((v, k) for k, v in _ENTRY_TYPES.items())
_DRIVE_PATTERN = re.compile(r'(\w)[:/\\]*$')
# ---- read and write binary data
def read_byte(buf):
return unpack('<B', buf.read(1))[0]
def read_short(buf):
return unpack('<H', buf.read(2))[0]
def read_int(buf):
return unpack('<I', buf.read(4))[0]
def read_double(buf):
return unpack('<Q', buf.read(8))[0]
def read_cunicode(buf):
s = b""
b = buf.read(2)
while b != b'\x00\x00':
s += b
b = buf.read(2)
return s.decode('utf-16-le')
def read_cstring(buf, padding=False):
s = b""
b = buf.read(1)
while b != b'\x00':
s += b
b = buf.read(1)
if padding and not len(s) % 2:
buf.read(1) # make length + terminator even
# TODO: encoding is not clear, unicode-escape has been necessary sometimes
return s.decode(DEFAULT_CHARSET)
def read_sized_string(buf, string=True):
size = read_short(buf)
if string:
return buf.read(size*2).decode('utf-16-le')
else:
return buf.read(size)
def get_bits(value, start, count, length=16):
mask = 0
for i in range(count):
mask = mask | 1 << i
shift = length - start - count
return value >> shift & mask
def read_dos_datetime(buf):
date = read_short(buf)
time = read_short(buf)
year = get_bits(date, 0, 7) + 1980
month = get_bits(date, 7, 4)
day = get_bits(date, 11, 5)
hour = get_bits(time, 0, 5)
minute = get_bits(time, 5, 6)
second = get_bits(time, 11, 5)
# fix zeroes
month = max(month, 1)
day = max(day, 1)
return datetime(year, month, day, hour, minute, second)
def write_byte(val, buf):
buf.write(pack('<B', val))
def write_short(val, buf):
buf.write(pack('<H', val))
def write_int(val, buf):
buf.write(pack('<I', val))
def write_double(val, buf):
buf.write(pack('<Q', val))
def write_cstring(val, buf, padding=False):
# val = val.encode('unicode-escape').replace('\\\\', '\\')
val = val.encode(DEFAULT_CHARSET)
buf.write(val + b'\x00')
if padding and not len(val) % 2:
buf.write(b'\x00')
def write_cunicode(val, buf):
uni = val.encode('utf-16-le')
buf.write(uni + b'\x00\x00')
def write_sized_string(val, buf, string=True):
size = len(val)
write_short(size, buf)
if string:
buf.write(val.encode('utf-16-le'))
else:
buf.write(val.encode())
def put_bits(bits, target, start, count, length=16):
return target | bits << (length - start - count)
def write_dos_datetime(val, buf):
date = time = 0
date = put_bits(val.year-1980, date, 0, 7)
date = put_bits(val.month, date, 7, 4)
date = put_bits(val.day, date, 11, 5)
time = put_bits(val.hour, time, 0, 5)
time = put_bits(val.minute, time, 5, 6)
time = put_bits(val.second, time, 11, 5)
write_short(date, buf)
write_short(time, buf)
# ---- helpers
def convert_time_to_unix(windows_time):
# Windows time is specified as the number of 0.1 nanoseconds since January 1, 1601.
# UNIX time is specified as the number of seconds since January 1, 1970.
# There are 134774 days (or 11644473600 seconds) between these dates.
unix_time = windows_time / 10000000.0 - 11644473600
try:
return datetime.fromtimestamp(unix_time)
except OSError:
return datetime.now()
def convert_time_to_windows(unix_time):
if isinstance(unix_time, datetime):
unix_time = time.mktime(unix_time.timetuple())
return int((unix_time + 11644473600) * 10000000)
class FormatException(Exception):
pass
class MissingInformationException(Exception):
pass
class InvalidKeyException(Exception):
pass
def guid_from_bytes(bytes):
if len(bytes) != 16:
raise FormatException("This is no valid _GUID: %s" % bytes)
ordered = [
bytes[3], bytes[2], bytes[1], bytes[0],
bytes[5], bytes[4], bytes[7], bytes[6],
bytes[8], bytes[9], bytes[10], bytes[11],
bytes[12], bytes[13], bytes[14], bytes[15]
]
return "{%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X}" % tuple([x for x in ordered])
def bytes_from_guid(guid):
nums = [
guid[1:3], guid[3:5], guid[5:7], guid[7:9],
guid[10:12], guid[12:14], guid[15:17], guid[17:19],
guid[20:22], guid[22:24], guid[25:27], guid[27:29],
guid[29:31], guid[31:33], guid[33:35], guid[35:37]
]
ordered_nums = [
nums[3], nums[2], nums[1], nums[0],
nums[5], nums[4], nums[7], nums[6],
nums[8], nums[9], nums[10], nums[11],
nums[12], nums[13], nums[14], nums[15],
]
return bytes([int(x, 16) for x in ordered_nums])
def assert_lnk_signature(f):
f.seek(0)
sig = f.read(4)
guid = f.read(16)
if sig != _SIGNATURE:
raise FormatException("This is not a .lnk file.")
if guid != _GUID:
raise FormatException("Cannot read this kind of .lnk file.")
def is_lnk(f):
if hasattr(f, 'name'):
if f.name.split(os.path.extsep)[-1] == "lnk":
assert_lnk_signature(f)
return True
else:
return False
else:
try:
assert_lnk_signature(f)
return True
except FormatException:
return False
def path_levels(p):
dirname, base = ntpath.split(p)
if base != '':
for level in path_levels(dirname):
yield level
yield p
def is_drive(data):
if type(data) not in (str, str):
return False
p = re.compile("[a-zA-Z]:\\\\?$")
return p.match(data) is not None
# ---- data structures
class Flags(object):
def __init__(self, flag_names: Tuple[str, ...], flags_bytes=0):
self._flag_names = flag_names
self._flags: Dict[str, bool] = dict([(name, False) for name in flag_names])
self.set_flags(flags_bytes)
def set_flags(self, flags_bytes):
for pos, flag_name in enumerate(self._flag_names):
self._flags[flag_name] = bool(flags_bytes >> pos & 0x1)
@property
def bytes(self):
bytes = 0
for pos in range(len(self._flag_names)):
bytes = (self._flags[self._flag_names[pos]] and 1 or 0) << pos | bytes
return bytes
def __getitem__(self, key):
if key in self._flags:
return object.__getattribute__(self, '_flags')[key]
return object.__getattribute__(self, key)
def __setitem__(self, key, value):
if key not in self._flags:
raise KeyError("The key '%s' is not defined for those flags." % key)
self._flags[key] = value
def __getattr__(self, key):
if key in self._flags:
return object.__getattribute__(self, '_flags')[key]
return object.__getattribute__(self, key)
def __setattr__(self, key, value):
if '_flags' not in self.__dict__:
object.__setattr__(self, key, value)
elif key in self.__dict__:
object.__setattr__(self, key, value)
else:
self.__setitem__(key, value)
def __str__(self):
return pformat(self._flags, indent=2)
class ModifierKeys(Flags):
def __init__(self, flags_bytes=0):
Flags.__init__(self, _MODIFIER_KEYS, flags_bytes)
def __str__(self):
s = ""
s += self.CONTROL and "CONTROL+" or ""
s += self.SHIFT and "SHIFT+" or ""
s += self.ALT and "ALT+" or ""
return s
# _ROOT_INDEX = {
# 0x00: 'INTERNET_EXPLORER1',
# 0x42: 'LIBRARIES',
# 0x44: 'USERS',
# 0x48: 'MY_DOCUMENTS',
# 0x50: 'MY_COMPUTER',
# 0x58: 'MY_NETWORK_PLACES',
# 0x60: 'RECYCLE_BIN',
# 0x68: 'INTERNET_EXPLORER2',
# 0x70: 'UNKNOWN',
# 0x80: 'MY_GAMES',
# }
class RootEntry(object):
def __init__(self, root):
if root is not None:
# create from text representation
if root in list(_ROOT_LOCATION_GUIDS.keys()):
self.root = root
self.guid = _ROOT_LOCATION_GUIDS[root]
return
# from binary
root_type = root[0]
index = root[1]
guid_bytes = root[2:18]
self.guid = guid_from_bytes(guid_bytes)
self.root = _ROOT_LOCATIONS.get(self.guid, f"UNKNOWN {self.guid}")
# if self.root == "UNKNOWN":
# self.root = _ROOT_INDEX.get(index, "UNKNOWN")
@property
def bytes(self):
guid = self.guid[1:-1].replace('-', '')
chars = [bytes([int(x, 16)]) for x in [guid[i:i+2] for i in range(0, 32, 2)]]
return (
b'\x1F\x50'
+ chars[3] + chars[2] + chars[1] + chars[0]
+ chars[5] + chars[4] + chars[7] + chars[6]
+ b''.join(chars[8:])
)
def __str__(self):
return "<RootEntry: %s>" % self.root
class DriveEntry(object):
def __init__(self, drive: str):
if len(drive) == 23:
# binary data from parsed lnk
self.drive = drive[1:3]
else:
# text representation
m = _DRIVE_PATTERN.match(drive.strip())
if m:
self.drive = m.groups()[0].upper() + ':'
self.drive = self.drive.encode()
else:
raise FormatException("This is not a valid drive: " + str(drive))
@property
def bytes(self):
drive = self.drive
padded_str = drive + b'\\' + b'\x00' * 19
return b'\x2F' + padded_str
# drive = self.drive
# if isinstance(drive, str):
# drive = drive.encode()
# return b'/' + drive + b'\\' + b'\x00' * 19
def __str__(self):
return "<DriveEntry: %s>" % self.drive
class PathSegmentEntry(object):
def __init__(self, bytes=None):
self.type = None
self.file_size = None
self.modified = None
self.short_name = None
self.created = None
self.accessed = None
self.full_name = None
if bytes is None:
return
buf = BytesIO(bytes)
self.type = _ENTRY_TYPES.get(read_short(buf), 'UNKNOWN')
short_name_is_unicode = self.type.endswith('(UNICODE)')
if self.type == 'ROOT_KNOWN_FOLDER':
self.full_name = '::' + guid_from_bytes(buf.read(16))
# then followed Beef0026 structure:
# short size
# short version
# int signature == 0xBEEF0026
# (16 bytes) created timestamp
# (16 bytes) modified timestamp
# (16 bytes) accessed timestamp
return
if self.type == 'KNOWN_FOLDER':
_ = read_short(buf) # extra block size
extra_signature = read_int(buf)
if extra_signature == 0x23FEBBEE:
_ = read_short(buf) # unknown
_ = read_short(buf) # guid len
# that format recognized by explorer
self.full_name = '::' + guid_from_bytes(buf.read(16))
return
self.file_size = read_int(buf)
self.modified = read_dos_datetime(buf)
unknown = read_short(buf) # FileAttributesL
if short_name_is_unicode:
self.short_name = read_cunicode(buf)
else:
self.short_name = read_cstring(buf, padding=True)
extra_size = read_short(buf)
extra_version = read_short(buf)
extra_signature = read_int(buf)
if extra_signature == 0xBEEF0004:
# indicator_1 = read_short(buf) # see below
# only_83 = read_short(buf) < 0x03
# unknown = read_short(buf) # 0x04
# self.is_unicode = read_short(buf) == 0xBeef
self.created = read_dos_datetime(buf) # 4 bytes
self.accessed = read_dos_datetime(buf) # 4 bytes
offset_unicode = read_short(buf) # offset from start of extra_size
# only_83_2 = offset_unicode >= indicator_1 or offset_unicode < 0x14
if extra_version >= 7:
offset_ansi = read_short(buf)
file_reference = read_double(buf)
unknown2 = read_double(buf)
long_string_size = 0
if extra_version >= 3:
long_string_size = read_short(buf)
if extra_version >= 9:
unknown4 = read_int(buf)
if extra_version >= 8:
unknown5 = read_int(buf)
if extra_version >= 3:
self.full_name = read_cunicode(buf)
if long_string_size > 0:
if extra_version >= 7:
self.localized_name = read_cunicode(buf)
else:
self.localized_name = read_cstring(buf)
version_offset = read_short(buf)
@classmethod
def create_for_path(cls, path):
entry = cls()
entry.type = os.path.isdir(path) and TYPE_FOLDER or TYPE_FILE
try:
st = os.stat(path)
entry.file_size = st.st_size
entry.modified = datetime.fromtimestamp(st.st_mtime)
entry.created = datetime.fromtimestamp(st.st_ctime)
entry.accessed = datetime.fromtimestamp(st.st_atime)
except FileNotFoundError:
now = datetime.now()
entry.file_size = 0
entry.modified = now
entry.created = now
entry.accessed = now
entry.short_name = ntpath.split(path)[1]
entry.full_name = entry.short_name
return entry
def _validate(self):
if self.type is None:
raise MissingInformationException("Type is missing, choose either TYPE_FOLDER or TYPE_FILE.")
if self.file_size is None:
if self.type.startswith('FOLDER') or self.type in ['KNOWN_FOLDER', 'ROOT_KNOWN_FOLDER']:
self.file_size = 0
else:
raise MissingInformationException("File size missing")
if self.created is None:
self.created = datetime.now()
if self.modified is None:
self.modified = datetime.now()
if self.accessed is None:
self.accessed = datetime.now()
# if self.modified is None or self.accessed is None or self.created is None:
# raise MissingInformationException("Date information missing")
if self.full_name is None:
raise MissingInformationException("A full name is missing")
if self.short_name is None:
self.short_name = self.full_name
@property
def bytes(self):
if self.full_name is None:
return
self._validate()
out = BytesIO()
entry_type = self.type
if entry_type == 'KNOWN_FOLDER':
write_short(_ENTRY_TYPE_IDS[entry_type], out)
write_short(0x1A, out) # size
write_int(0x23FEBBEE, out) # extra signature
write_short(0x00, out) # extra signature
write_short(0x10, out) # guid size
out.write(bytes_from_guid(self.full_name.strip(':')))
return out.getvalue()
if entry_type == 'ROOT_KNOWN_FOLDER':
write_short(_ENTRY_TYPE_IDS[entry_type], out)
out.write(bytes_from_guid(self.full_name.strip(':')))
write_short(0x26, out) # 0xBEEF0026 structure size
write_short(0x01, out) # version
write_int(0xBEEF0026, out) # extra signature
write_int(0x11, out) # some flag for containing datetime
write_double(0x00, out) # created datetime
write_double(0x00, out) # modified datetime
write_double(0x00, out) # accessed datetime
write_short(0x14, out) # unknown
return out.getvalue()
short_name_len = len(self.short_name) + 1
try:
self.short_name.encode("ascii")
short_name_is_unicode = False
short_name_len += short_name_len % 2 # padding
except (UnicodeEncodeError, UnicodeDecodeError):
short_name_is_unicode = True
short_name_len = short_name_len * 2
self.type += " (UNICODE)"
write_short(_ENTRY_TYPE_IDS[entry_type], out)
write_int(self.file_size, out)
write_dos_datetime(self.modified, out)
write_short(0x10, out)
if short_name_is_unicode:
write_cunicode(self.short_name, out)
else:
write_cstring(self.short_name, out, padding=True)
indicator = 24 + 2 * len(self.short_name)
write_short(indicator, out) # size
write_short(0x03, out) # version
write_short(0x04, out) # signature part1
write_short(0xBeef, out) # signature part2
write_dos_datetime(self.created, out)
write_dos_datetime(self.accessed, out)
offset_unicode = 0x14 # fixed data structure, always the same
write_short(offset_unicode, out)
offset_ansi = 0 # we always write unicode
write_short(offset_ansi, out) # long_string_size
write_cunicode(self.full_name, out)
offset_part2 = 0x0E + short_name_len
write_short(offset_part2, out)
return out.getvalue()
def __str__(self):
return "<PathSegmentEntry: %s>" % self.full_name
class UwpSubBlock:
block_names = {
0x11: 'PackageFamilyName',
# 0x0e: '',
# 0x19: '',
0x15: 'PackageFullName',
0x05: 'Target',
0x0f: 'Location',
0x20: 'RandomGuid',
0x0c: 'Square150x150Logo',
0x02: 'Square44x44Logo',
0x0d: 'Wide310x150Logo',
# 0x04: '',
# 0x05: '',
0x13: 'Square310x310Logo',
# 0x0e: '',
0x0b: 'DisplayName',
0x14: 'Square71x71Logo',
0x64: 'RandomByte',
0x0a: 'DisplayName',
# 0x07: '',
}
block_types = {
'string': [0x11, 0x15, 0x05, 0x0f, 0x0c, 0x02, 0x0d, 0x13, 0x0b, 0x14, 0x0a],
}
def __init__(self, bytes=None, type=None, value=None):
self._data = bytes or b''
self.type = type
self.value = value
self.name = None
if self.type is not None:
self.name = self.block_names.get(self.type, 'UNKNOWN')
if not bytes:
return
buf = BytesIO(bytes)
self.type = read_byte(buf)
self.name = self.block_names.get(self.type, 'UNKNOWN')
self.value = self._data[1:] # skip type
if self.type in self.block_types['string']:
unknown = read_int(buf)
probably_type = read_int(buf)
if probably_type == 0x1f:
string_len = read_int(buf)
self.value = read_cunicode(buf)
def __str__(self):
string = f'UwpSubBlock {self.name} ({hex(self.type)}): {self.value}'
return string.strip()
@property
def bytes(self):
out = BytesIO()
if self.value:
if isinstance(self.value, str):
string_len = len(self.value) + 1
write_byte(self.type, out)
write_int(0, out)
write_int(0x1f, out)
write_int(string_len, out)
write_cunicode(self.value, out)
if string_len % 2 == 1: # padding
write_short(0, out)
elif isinstance(self.value, bytes):
write_byte(self.type, out)
out.write(self.value)
result = out.getvalue()
return result
class UwpMainBlock:
magic = b'\x31\x53\x50\x53'
def __init__(self, bytes=None, guid: Optional[str] = None, blocks=None):
self._data = bytes or b''
self._blocks = blocks or []
self.guid: str = guid
if not bytes:
return
buf = BytesIO(bytes)
magic = buf.read(4)
self.guid = guid_from_bytes(buf.read(16))
# read sub blocks
while True:
sub_block_size = read_int(buf)
if not sub_block_size: # last size is zero
break
sub_block_data = buf.read(sub_block_size - 4) # includes block_size
self._blocks.append(UwpSubBlock(sub_block_data))
def __str__(self):
string = f'<UwpMainBlock> {self.guid}:\n'
for block in self._blocks:
string += f' {block}\n'
return string.strip()
@property
def bytes(self):
blocks_bytes = [block.bytes for block in self._blocks]
out = BytesIO()
out.write(self.magic)
out.write(bytes_from_guid(self.guid))
for block in blocks_bytes:
write_int(len(block) + 4, out)
out.write(block)
write_int(0, out)
result = out.getvalue()
return result
class UwpSegmentEntry:
magic = b'APPS'
header = b'\x08\x00\x03\x00\x00\x00\x00\x00\x00\x00'
def __init__(self, bytes=None):
self._blocks = []
self._data = bytes
if bytes is None:
return
buf = BytesIO(bytes)
unknown = read_short(buf)
size = read_short(buf)
magic = buf.read(4) # b'APPS'
blocks_size = read_short(buf)
unknown2 = buf.read(10)
# read main blocks
while True:
block_size = read_int(buf)
if not block_size: # last size is zero
break
block_data = buf.read(block_size - 4) # includes block_size
self._blocks.append(UwpMainBlock(block_data))
def __str__(self):
string = '<UwpSegmentEntry>:\n'
for block in self._blocks:
string += f' {block}\n'
return string.strip()
@property
def bytes(self):
blocks_bytes = [block.bytes for block in self._blocks]
blocks_size = sum([len(block) + 4 for block in blocks_bytes]) + 4 # with terminator
size = (
2 # size
+ len(self.magic)
+ 2 # second size
+ len(self.header)
+ blocks_size # blocks with terminator
)
out = BytesIO()
write_short(0, out)
write_short(size, out)
out.write(self.magic)
write_short(blocks_size, out)
out.write(self.header)
for block in blocks_bytes:
write_int(len(block) + 4, out)
out.write(block)
write_int(0, out) # empty block
write_short(0, out) # ??
result = out.getvalue()
return result
@classmethod
def create(cls, package_family_name, target, location=None, logo44x44=None):
segment = cls()
blocks = [
UwpSubBlock(type=0x11, value=package_family_name),
UwpSubBlock(type=0x0e, value=b'\x00\x00\x00\x00\x13\x00\x00\x00\x02\x00\x00\x00'),
UwpSubBlock(type=0x05, value=target),
]
if location:
blocks.append(UwpSubBlock(type=0x0f, value=location)) # need for relative icon path
main1 = UwpMainBlock(guid='{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}', blocks=blocks)
segment._blocks.append(main1)
if logo44x44:
main2 = UwpMainBlock(
guid='{86D40B4D-9069-443C-819A-2A54090DCCEC}',
blocks=[UwpSubBlock(type=0x02, value=logo44x44)]
)
segment._blocks.append(main2)
return segment
class LinkTargetIDList(object):
def __init__(self, bytes=None):
self.items = []
if bytes is not None:
buf = BytesIO(bytes)
raw = []
entry_len = read_short(buf)
while entry_len > 0:
raw.append(buf.read(entry_len - 2)) # the length includes the size
entry_len = read_short(buf)
self._interpret(raw)
def _interpret(self, raw):
if not raw:
return
elif raw[0][0] == 0x1F:
self.items.append(RootEntry(raw[0]))
if self.items[0].root == ROOT_MY_COMPUTER:
if len(raw[1]) == 0x17:
self.items.append(DriveEntry(raw[1]))
elif raw[1][0:2] == b'\x2E\x80': # ROOT_KNOWN_FOLDER
self.items.append(PathSegmentEntry(raw[1]))
else:
raise ValueError("This seems to be an absolute link which requires a drive as second element.")
items = raw[2:]
elif self.items[0].root == ROOT_NETWORK_PLACES:
raise NotImplementedError(
"Parsing network lnks has not yet been implemented. "
"If you need it just contact me and we'll see..."
)
else:
items = raw[1:]
else:
items = raw
for item in items:
if item[4:8] == b'APPS':
self.items.append(UwpSegmentEntry(item))
else:
self.items.append(PathSegmentEntry(item))
def get_path(self):
segments = []
for item in self.items:
if type(item) == RootEntry:
segments.append('%' + item.root + '%')
elif type(item) == DriveEntry:
segments.append(item.drive.decode())
elif type(item) == PathSegmentEntry:
if item.full_name is not None:
segments.append(item.full_name)
else:
segments.append(item)
return '\\'.join(segments)
def _validate(self):
if not len(self.items):
return
if type(self.items[0]) == RootEntry and self.items[0].root == ROOT_MY_COMPUTER:
if type(self.items[1]) == DriveEntry:
return
if type(self.items[1]) == PathSegmentEntry and self.items[1].full_name.startswith('::'):
return
raise ValueError("A drive is required for absolute lnks")
@property
def bytes(self):
self._validate()
out = BytesIO()
for item in self.items:
bytes = item.bytes
# skip invalid
if bytes is None:
continue
write_short(len(bytes) + 2, out) # len + terminator
out.write(bytes)
out.write(b'\x00\x00')
return out.getvalue()
def __str__(self):
string = '<LinkTargetIDList>:\n'
for item in self.items:
string += f' {item}\n'
return string.strip()
class LinkInfo(object):
def __init__(self, lnk=None):
if lnk is not None:
self.start = lnk.tell()
self.size = read_int(lnk)
self.header_size = read_int(lnk)
link_info_flags = read_int(lnk)
self.local = link_info_flags & 1
self.remote = link_info_flags & 2
self.offs_local_volume_table = read_int(lnk)
self.offs_local_base_path = read_int(lnk)
self.offs_network_volume_table = read_int(lnk)
self.offs_base_name = read_int(lnk)
if self.header_size >= _LINK_INFO_HEADER_OPTIONAL:
print("TODO: read the unicode stuff") # TODO: read the unicode stuff
self._parse_path_elements(lnk)
else:
self.size = None
self.header_size = _LINK_INFO_HEADER_DEFAULT
self.local = 0
self.remote = 0