-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
__init__.py
2086 lines (1620 loc) · 71.5 KB
/
__init__.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.7
"""
::
File: buskill.py
Authors: Michael Altfield <michael@buskill.in>
Co-Auth: Steven Johnson <steven.j2019@protonmail.com>
Created: 2020-06-23
Updated: 2022-07-11
Version: 0.4
This is the heart of the buskill app, shared by both the cli and gui
For more info, see: https://buskill.in/
"""
################################################################################
# IMPORTS #
################################################################################
import platform, multiprocessing, traceback, subprocess
import urllib.request, re, json, certifi, sys, os, math, shutil, tempfile, random, gnupg
import os.path
from buskill_version import BUSKILL_VERSION
from distutils.version import LooseVersion
from hashlib import sha256
import logging
logger = logging.getLogger( __name__ )
# platform-specific modules
CURRENT_PLATFORM = platform.system().upper()
if CURRENT_PLATFORM.startswith( 'LINUX' ):
import usb1
msg = "usb1.__version__:|" +str(usb1.__version__)+ "|"
print( msg ); logger.debug( msg )
if CURRENT_PLATFORM.startswith( 'WIN' ):
import win32api, win32con, win32gui
from ctypes import *
if CURRENT_PLATFORM.startswith( 'DARWIN' ):
import usb1, ctypes, ctypes.util
from ctypes import byref
msg = "usb1.__version__:|" +str(usb1.__version__)+ "|"
print( msg ); logger.debug( msg )
################################################################################
# SETTINGS #
################################################################################
# APP_DIR is the dir in which our buskill executable lives, which often
# is some dir on the USB drive itself or could be somewhere on the computer
global APP_DIR
APP_DIR = sys.path[0]
UPGRADE_MIRRORS = [
'https://raw.githubusercontent.com/BusKill/buskill-app/master/updates/v1/meta.json',
'https://gitlab.com/buskill/buskill-app/-/raw/master/updates/v1/meta.json',
'https://repo.buskill.in/buskill-app/v1/meta.json',
'https://repo.michaelaltfield.net/buskill-app/v1/meta.json',
]
random.shuffle(UPGRADE_MIRRORS)
RELEASE_KEY_FINGERPRINT = 'E0AFFF57DC00FBE0563587614AE21E1936CE786A'
RELEASE_KEY_SUB_FINGERPRINT = '798DC1101F3DEC428ADE124D68B8BCB0C5023905'
#####################
# WINDOWS CONSTANTS #
#####################
if CURRENT_PLATFORM.startswith( 'WIN' ):
# Device change events (WM_DEVICECHANGE wParam)
DBT_DEVICEARRIVAL = 0x8000
DBT_DEVICEQUERYREMOVE = 0x8001
DBT_DEVICEQUERYREMOVEFAILED = 0x8002
DBT_DEVICEMOVEPENDING = 0x8003
DBT_DEVICEREMOVECOMPLETE = 0x8004
DBT_DEVICETYPESSPECIFIC = 0x8005
DBT_CONFIGCHANGED = 0x0018
# type of device in DEV_BROADCAST_HDR
DBT_DEVTYP_OEM = 0x00000000
DBT_DEVTYP_DEVNODE = 0x00000001
DBT_DEVTYP_VOLUME = 0x00000002
DBT_DEVTYPE_PORT = 0x00000003
DBT_DEVTYPE_NET = 0x00000004
# media types in DBT_DEVTYP_VOLUME
DBTF_MEDIA = 0x0001
DBTF_NET = 0x0002
WORD = c_ushort
DWORD = c_ulong
################################################################################
# OBJECTS #
################################################################################
##########################
# WINDOWS HELPER CLASSES #
##########################
if CURRENT_PLATFORM.startswith( 'WIN' ):
# The windows WM_DEVICECHANGE code below was adapted from the following sources:
# * http://timgolden.me.uk/python/win32_how_do_i/detect-device-insertion.html
# * https://stackoverflow.com/questions/38689090/detect-media-insertion-on-windows-in-python
class DEV_BROADCAST_HDR(Structure):
_fields_ = [
("dbch_size", DWORD),
("dbch_devicetype", DWORD),
("dbch_reserved", DWORD)
]
class DEV_BROADCAST_VOLUME(Structure):
_fields_ = [
("dbcv_size", DWORD),
("dbcv_devicetype", DWORD),
("dbcv_reserved", DWORD),
("dbcv_unitmask", DWORD),
("dbcv_flags", WORD)
]
def drive_from_mask(mask):
n_drive = 0
while 1:
if (mask & (2 ** n_drive)):
return n_drive
else:
n_drive += 1
class Notification:
def __init__( self, buskill ):
self.bk = buskill
message_map = {
win32con.WM_DEVICECHANGE: self.hotplugCallbackWin
}
wc = win32gui.WNDCLASS()
hinst = wc.hInstance = win32api.GetModuleHandle(None)
wc.lpszClassName = "DeviceChangeDemo"
wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW
wc.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW)
wc.hbrBackground = win32con.COLOR_WINDOW
wc.lpfnWndProc = message_map
classAtom = win32gui.RegisterClass(wc)
style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
self.hwnd = win32gui.CreateWindow(
classAtom,
"Device Change Demo",
style,
0, 0,
win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT,
0, 0,
hinst, None
)
# this is a callback function that is registered to be called when a usb
# hotplug event occurs in windows
# WM_DEVICECHANGE:
# wParam - type of change: arrival, removal etc.
# lParam - what's changed?
# if it's a volume then...
# lParam - what's changed more exactly
def hotplugCallbackWin(self, hwnd, message, wparam, lparam):
dev_broadcast_hdr = DEV_BROADCAST_HDR.from_address(lparam)
if wparam == DBT_DEVICEREMOVECOMPLETE:
self.bk.triggerWin()
msg = "hwnd:|" +str(hwnd)+ "|"
print( msg ); logger.debug( msg )
msg = "message:|" +str(message)+ "|"
print( msg ); logger.debug( msg )
msg= "wparam:|" +str(wparam)+ "|"
print( msg ); logger.debug( msg )
msg = "lparam:|" +str(lparam)+ "|"
print( msg ); logger.debug( msg )
dev_broadcast_volume = DEV_BROADCAST_VOLUME.from_address(lparam)
msg = "dev_broadcast_volume:|" +str(dev_broadcast_volume)+ "|"
print( msg ); logger.debug( msg )
drive_letter = drive_from_mask(dev_broadcast_volume.dbcv_unitmask)
msg = "drive_letter:|" +str(drive_letter)+ "|"
print( msg ); logger.debug( msg )
msg = "ch( ord('A') + drive_letter):|" +str( chr(ord('A') + drive_letter) )+ '|'
print( msg ); logger.debug( msg )
return 1
class BusKill:
def __init__(self):
###############################
# instantiate instance fields #
###############################
self.CURRENT_PLATFORM = None
self.KERNEL_VERSION = None
self.IS_PLATFORM_SUPPORTED = False
self.OS_NAME_SHORT = None
self.ERR_PLATFORM_NOT_SUPPORTED = None
self.ARM_FUNCTION = None
self.DISARM_FUNCTION = None
self.TRIGGER_FUNCTION = None
self.EXECUTED_AS_SCRIPT = None
self.LOG_FILE_PATH = logger.root.handlers[0].baseFilename
self.EXE_PATH = None
self.EXE_DIR = None
self.EXE_FILE = None
self.APP_DIR = None
self.APPS_DIR = None
self.SRC_DIR = None
self.DATA_DIR = None
self.CACHE_DIR = None
self.GNUPGHOME = None
self.UPGRADED_FROM = None
self.UPGRADED_TO = None
# stores the process object for a child process running as root, if needed
self.root_child = None
self.is_armed = None
self.usb_handler = None
self.upgrade_status_msg = None
self.upgrade_result = None
self.SUPPORTED_TRIGGERS = ['lock-screen', 'soft-shutdown']
self.trigger = 'lock-screen'
self.trigger_softshutdown_lin_shutdown_path = None
self.trigger_softshutdown_lin_poweroff_path = None
self.trigger_softshutdown_lin_systemctl_path = None
# documentation links
if BUSKILL_VERSION['VERSION'] == '':
ver = 'stable'
else:
ver = BUSKILL_VERSION['VERSION']
self.url_website = "https://buskill.in"
self.url_documentation = "https://docs.buskill.in"
self.url_documentation_contribute = "https://docs.buskill.in/buskill-app/en/stable/contributing.html"
self.url_documentation_bug_report = 'https://docs.buskill.in/buskill-app/en/' +str(ver)+ '/support.html'
self.url_documentation_gui = 'https://docs.buskill.in/buskill-app/en/' +str(ver)+ '/software_usr/gui.html'
self.CURRENT_PLATFORM = platform.system().upper()
self.ERR_PLATFORM_NOT_SUPPORTED = 'ERROR: Your platform (' +str(platform.system())+ ') is not supported. If you believe this is an error, please file a bug report:\n\nhttps://github.com/BusKill/buskill-app/issues'
# NOTE about instance fields used for storing path info relative to the
# buskill executable:
#
# 1. EXE_PATH = the absolute path to the executable for running BusKill,
# which is:
# [a] the 'buskill-<version>.AppImage' file in Linux
# [b] the 'buskill.exe' file in Windows
# [c] the 'buskill' binary file in MacOS
# 2. EXE_FILE = just the filename (basename) of the EXE_PATH
# 3. EXE_DIR = the directory (dirname) where EXE_FILE lives
# 4. APP_DIR = the root directory for a given version of the buskill app,
# which is 'buskill-<lin|win|mac>-<version>-x86_64' and:
# [a] the dir containing the EXE_FILE file in Linux
# [b] 1 dir above the dir containing the EXE_FILE in
# Windows
# [c] 2 dirs above the dir containing the EXE_FILE in
# MacOS
# 4. APPS_DIR = the directory where the app dirs live (one dir above
# APP_DIR)
# 5. SRC_DIR = the absolute path to the directory where the 'src' directory
# lives. This is where files like 'KEYS' and directories like
# 'packages' are stored. On some platforms like Linux, this is
# distinct from the APP_DIR because the contents of the AppImage
# is extracted to a temp dir at runtime
# get the absolute path to the file that the user executes to start buskill
self.EXE_PATH = sys.executable
# if the executable is actually just the python interpreter, then what
# we want is the first argument
if re.match( ".*python([1-9]\.?)*$", self.EXE_PATH ):
self.EXE_PATH = os.path.abspath( sys.argv[0] )
# split the EXE_PATH into dir & file parts
self.EXE_DIR = os.path.split(self.EXE_PATH)[0]
self.EXE_FILE = os.path.split(self.EXE_PATH)[1]
# platform-specific setup
if CURRENT_PLATFORM.startswith( 'LINUX' ):
self.IS_PLATFORM_SUPPORTED = True
self.OS_NAME_SHORT = 'lin'
self.ARM_FUNCTION = self.armNix
self.TRIGGER_FUNCTION = self.triggerLin
# on Linux, the buskill AppImage is directly inside the APP_DIR
self.APP_DIR = self.EXE_DIR
# on Linux, the AppImage is extracted to a root-owned temporary directory
# at runtime
self.SRC_DIR = sys.path[0]
if CURRENT_PLATFORM.startswith( 'WIN' ):
self.IS_PLATFORM_SUPPORTED = True
self.OS_NAME_SHORT = 'win'
self.ARM_FUNCTION = self.armWin
self.TRIGGER_FUNCTION = self.triggerWin
# on Windows, the buskill binary is 1 dir below the APP_DIR
self.APP_DIR = self.EXE_PATH.split( os.sep )[0:-2]
self.APP_DIR = os.sep.join( self.APP_DIR )
# on Windows, the exe lives in the same dir with all our other src files
self.SRC_DIR = self.EXE_DIR
if CURRENT_PLATFORM.startswith( 'DARWIN' ):
self.IS_PLATFORM_SUPPORTED = True
self.OS_NAME_SHORT = 'mac'
self.KERNEL_VERSION = str(platform.release()).split('.')[0]
self.ARM_FUNCTION = self.armNix
self.TRIGGER_FUNCTION = self.triggerMac
# on MacOS, the binary is 2 dirs below the .app dir
self.APP_DIR = self.EXE_PATH.split( os.sep )[0:-3]
self.APP_DIR = os.sep.join( self.APP_DIR )
# on MacOS, the exe lives in the same dir with all our other src files
self.SRC_DIR = self.EXE_DIR
# normally the BusKill app is built into a platform-specific executable with
# PyInstaller. But if we're executing it directly as a script, then some of
# the logic will change throught the app
#if self.EXE_FILE == 'main.py' and os.path.split(self.APP_DIR)[1] == 'src':
if self.EXE_FILE == 'main.py':
self.EXECUTED_AS_SCRIPT = True
self.APP_DIR = os.path.abspath(
os.path.join( self.APP_DIR, os.pardir)
)
else:
self.EXECUTED_AS_SCRIPT = False
# We package our .zip inside a single root dir to prevent zip-bombing.
# When extracted on most platforms, this root dir is dropped into the
# the cwd. But when using the Windows file Explorer GUI to extract
# our .zip release, it actually creates an additional root dir with
# the same name as our .zip file (minus the .zip extension). This
# inconsistency means that we may have to go one dir up again
if re.match(
"^buskill-" +str(self.OS_NAME_SHORT)+ "-.*",
self.APP_DIR.split(os.sep)[-2]
):
# the dir that we expected to be our APP_DIR is actually inside of
# another dir that has the name "buskil-...", so let's make
# *that* dir our APP_DIR
self.APP_DIR = os.path.abspath(
os.path.join( self.APP_DIR, os.pardir)
)
# the APPS_DIR is one dir above the APP_DIR
self.APPS_DIR = os.path.abspath( os.path.join(self.APP_DIR, os.pardir) )
# update PATH to include the dir where main.py lives (the second one is
# MacOS .app compatibility weirdness) so that we can find `gpg` there
os.environ['PATH'] += \
os.pathsep+ self.EXE_DIR + \
os.pathsep+ self.APP_DIR
# also fallback on loading libraries from our self-contained app
# this may be needed by gpg for gettext's libintl
# * https://github.com/BusKill/buskill-app/issues/36
os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = self.SRC_DIR
# also update sys.python, so `import` statements will look in there (eg:
# for upgraded_from.py)
sys.path.append( self.EXE_DIR )
msg = "DEBUG: EXECUTED_AS_SCRIPT:|" +str(self.EXECUTED_AS_SCRIPT)+ "|\n"
msg+= "DEBUG: EXE_PATH:|" +str(self.EXE_PATH)+ "|\n"
msg+= "DEBUG: EXE_DIR:|" +str(self.EXE_DIR)+ "|\n"
msg+= "DEBUG: EXE_FILE:|" +str(self.EXE_FILE)+ "|\n"
msg+= "DEBUG: APP_DIR:|" +str(self.APP_DIR)+ "|\n"
msg+= "DEBUG: APPS_DIR:|" +str(self.APPS_DIR)+ "|\n"
msg+= "DEBUG: SRC_DIR:|" +str(self.SRC_DIR)+ "|\n"
msg+= "DEBUG: os.environ['PATH']:|" +str(os.environ['PATH'])+ "|\n"
print( msg ); logger.debug( msg )
# create a data dir in some safe place where we have write access
# TODO: move this to main.py so the log file gets put in the CACHE_DIR
# (that--or maybe just move the buskill.init() into main.py)
self.setupDataDir()
# handle conditions where this version was already upgraded by a newer
# version or if this is a version that upgraded an older version
self.handle_upgrades()
# this function is necessary to be able to execute non-static methods on
# the `self` instance of this object in a child process. Without this, we'll
# get "TypeError: can't pickle weakref objects" errors in python >= 3.7.0
# because some of the instance fields of this object are not pickleable
# * https://bugs.python.org/issue34034
# * https://docs.python.org/3/library/pickle.html#object.__reduce__
# * https://docs.python.org/3/library/pickle.html#object.__getstate__
def __getstate__(self):
state = self.__dict__.copy()
msg = "DEBUG:__getstate__() pre:" +str( state.keys() )+ "|"
print( msg ); logger.debug( msg )
# remove instances of multiprocessing.Process() because they're not
# pickleable
unpickleable = [
'upgrade_process', 'usb_handler', 'root_child'
]
for instance_field in unpickleable:
if instance_field in state:
del state[instance_field]
msg = "DEBUG:__getstate__() post:|" +str( state.keys() )+ "|"
print( msg ); logger.debug( msg )
return state
# this is called when the GUI is closed
# TODO: use 'fuckit' python module https://stackoverflow.com/questions/63436916/how-to-ignore-exceptions-and-proceed-with-whole-blocks-multiple-lines-in-pytho/
def close(self):
# do what we can as fast as we can; don't get stuck by errors
try:
# if we don't kill this child process on exit, the UI will freeze
try:
self.usb_handler.kill()
except ProcessLookupError as e:
msg = "DEBUG: Ignoring ProcessLookupError " +str(e)
msg += "\n\t" +str(e)+ "\n"
print( msg ); logger.debug( msg )
self.usb_handler.join()
except:
pass
try:
# if we don't kill this child process on exit, the UI will freeze
try:
self.upgrade_process.kill()
except ProcessLookupError as e:
msg = "DEBUG: Ignoring ProcessLookupError " +str(e)
msg += "\n\t" +str(e)+ "\n"
print( msg ); logger.debug( msg )
self.upgrade_process.join()
except:
pass
try:
# delete cache dir
self.wipeCache()
except:
pass
def is_platform_supported(self):
if self.OS_NAME_SHORT in ['lin','win','mac']:
return True
else:
return False
# function to set the trigger (and to check sanity)
def set_trigger(self, trigger):
msg = "DEBUG: Attempting to set 'trigger' set to '" +str(trigger)+ "'"
print( msg ); logger.debug( msg )
if trigger not in self.SUPPORTED_TRIGGERS:
msg = "WARNING: Attempting to set trigger to invalid value (" +str(trigger)+ ")"
print( msg ); logger.debug( msg )
raise Exception( msg )
self.trigger = trigger
# check sanity of the soft shutdown trigger
if trigger == 'soft-shutdown':
if self.OS_NAME_SHORT == 'lin':
# list of paths where binaries like 'shutdown' could be
bin_paths = [
os.sep+'sbin',
os.sep+'usr'+os.sep+'sbin',
os.sep+'bin',
os.sep+'usr'+os.sep+'bin'
]
for path in bin_paths:
# shutdown
shutdown_path = path + os.sep + 'shutdown'
if os.path.exists( shutdown_path ):
self.trigger_softshutdown_lin_shutdown_path = shutdown_path
# poweroff
poweroff_path = path + os.sep + 'poweroff'
if os.path.exists( poweroff_path ):
self.trigger_softshutdown_lin_poweroff_path = poweroff_path
# systemctl
systemctl_path = path + os.sep + 'systemctl'
if os.path.exists( systemctl_path ):
self.trigger_softshutdown_lin_systemctl_path = systemctl_path
# were we able to find at least one of their paths?
if self.trigger_softshutdown_lin_shutdown_path == None and \
self.trigger_softshutdown_lin_poweroff_path == None and \
self.trigger_softshutdown_lin_systemctl_path == None:
# we couldn't figure any of the paths; don't continue with this trigger
msg = "ERROR: Unable to find paths to soft shutdown binaries"
print( msg ); logger.error( msg )
raise Exception( msg )
# TODO: check to see if the user has permission to shutdown the system. If not, throw an exception and tell them to re-run BusKill as root.
# * https://unix.stackexchange.com/questions/719465/cross-platform-way-to-determine-if-the-current-user-has-privlige-to-shutdown-the
# * https://stackoverflow.com/questions/73923097/best-practice-way-to-run-a-python-program-that-needs-root-privliges-for-subset-o
msg = "DEBUG: shutdown binary path:|" \
+str(self.trigger_softshutdown_lin_shutdown_path)+ "|"
print( msg ); logger.error( msg )
msg = "DEBUG: poweroff binary path:|" \
+str(self.trigger_softshutdown_lin_poweroff_path)+ "|"
print( msg ); logger.error( msg )
msg = "DEBUG: systemctl binary path:|" \
+str(self.trigger_softshutdown_lin_systemctl_path)+ "|"
print( msg ); logger.error( msg )
#elif self.OS_NAME_SHORT == 'win':
# n/a currently there's no checks needed for the soft-shutdown on windows
elif self.OS_NAME_SHORT == 'mac':
# the soft shutdown trigger on mac requires root permissions
self.spawn_root_child()
self.trigger = trigger
msg = "INFO: BusKill 'trigger' set to '" +str(self.trigger)+ "'"
print( msg ); logger.info( msg )
def get_trigger(self):
return str(self.trigger)
# launches a root child process
def spawn_root_child(self):
msg = "DEBUG: Called spawn_root_child()"
print( msg ); logger.debug( msg )
# SECURITY NOTE:
#
# Whenever you execute something as root, it's very important that you know
# _what_ you're executing. For example, never execute a script as root that is
# world-writeable. In general, assuming the script is named 'root_child.py':
#
# 1. Make sure root_child.py has permissions root:root 0500 (and therefore only
# writeable and executable by root)
# 2. Make sure I specify the absolute path to root_child.py, and that path
# cannot be maliciously manipulated
# 3. Make sure that root_child.py isn't actually a (sym)link
#
# See also:
# * https://github.com/BusKill/buskill-app/issues/14#issuecomment-1272449172
if self.OS_NAME_SHORT == 'lin':
msg = "ERROR: root_child_lin.py not yet implemented"
print( msg ); logger.error( msg )
elif self.OS_NAME_SHORT == 'win':
msg = "ERROR: root_child_win.py not yet implemented"
print( msg ); logger.error( msg )
elif self.OS_NAME_SHORT == 'mac':
# is the root child process already started?
if self.root_child == None:
# the root child process hasn't been started; start it
msg = "DEBUG: No root_child detected. Attempting to spawn one."
print( msg ); logger.debug( msg )
msg = "INFO: You have requested BusKill to do something that requires elevated privliges on your platform. If you'd like to proceed, please authorize BusKill to preform actions as Administrator. Your system may prompt you for your password to proceed."
print( msg ); logger.info( msg )
# To spawn a child process as root in MacOS, we use
# AuthorizationExecuteWithPrivileges(), which triggers the OS to
# display an auth challenge in the GUI for the user. See also
# * https://stackoverflow.com/a/74001980/1174102
# * https://stackoverflow.com/a/74083291/1174102
# * https://github.com/BusKill/buskill-app/issues/14
# was BusKill called as a binary or a script?
if self.EXECUTED_AS_SCRIPT == False:
# this execution was a binary
# let's call the root child binary
root_child_path = self.SRC_DIR +os.sep+ 'root_child_mac'
# and we'll be calling the binary directly
exe = [root_child_path, self.LOG_FILE_PATH]
else:
# this execution was a script; let's call the root child script
root_child_path = self.SRC_DIR +os.sep+ 'packages' +os.sep+ 'buskill' +os.sep+ 'root_child_mac.py'
# and we'll pass the script as an argument to the python
# interpreter
exe = [sys.executable, root_child_path, self.LOG_FILE_PATH]
msg = "DEBUG: root_child_path:|" +str(root_child_path)+ "|"
print( msg ); logger.debug( msg )
# SANITY CHECKS
mode = oct(os.stat(root_child_path).st_mode)[-4:]
owner = os.stat(root_child_path).st_uid
group = os.stat(root_child_path).st_gid
# verify the mode of the file is exactly 0500 (octal)
if mode != '0500':
msg = 'ERROR: Permissions on root_child are not 0500. Refusing to spawn script as root!'
print( msg ); logger.error( msg )
return False
# unfortunaetly we can't package a .dmg with a file owned by root, so on
# first run, we expect that the root child script will be owned by the
# user that executed the BusKill app
# https://github.com/BusKill/buskill-app/issues/14#issuecomment-1279975783
# verify the file is owned by user = root (or current user)
if owner != 0 and owner != os.getuid():
msg = 'ERROR: root_child is not owned by root nor your user. Refusing to spawn script as root!'
print( msg ); logger.error( msg )
return False
# verify the file is owned by group = root (or current group)
if group != 0 and group != os.getgid():
msg = 'ERROR: root_child is not owned by gid=0 nor your group. Refusing to spawn script as root!'
print( msg ); logger.error( msg )
return False
# verify the "file" isn't actually a symlink
if os.path.islink( root_child_path ):
msg = 'ERROR: root_child is a link. Refusing to spawn script as root!'
print( msg ); logger.error( msg )
return False
# import some C libraries for interacting via ctypes with the MacOS API
libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c"))
# https://developer.apple.com/documentation/security
sec = ctypes.cdll.LoadLibrary(ctypes.util.find_library("Security"))
kAuthorizationFlagDefaults = 0
auth = ctypes.c_void_p()
r_auth = byref(auth)
sec.AuthorizationCreate(None,None,kAuthorizationFlagDefaults,r_auth)
args = (ctypes.c_char_p * len(exe))()
for i,arg in enumerate(exe[1:]):
args[i] = arg.encode('utf8')
if self.root_child == None:
self.root_child = dict()
self.root_child['io'] = ctypes.c_void_p()
msg = "DEBUG: Attempting to spawn root child (" +str(exe)+ ")"
print( msg ); logger.debug( msg )
err = sec.AuthorizationExecuteWithPrivileges(
auth,
exe[0].encode('utf8'),
0,
args,
byref(self.root_child['io'])
)
msg = "DEBUG: AuthorizationExecuteWithPrivileges.err:|" +str(err)+ "|"
print( msg ); logger.debug( msg )
# did the attempt to spawn the child process return an error?
if err == -60007:
# https://developer.apple.com/documentation/security/1540004-authorization_services_result_co/errauthorizationinteractionnotallowed
msg = 'ERROR: root_child spwan attempt returned errAuthorizationInteractionNotAllowed = -60007. Did you execute BusKill from a headless CLI? The credential challenge requires a GUI when launching a child process as root.'
print( msg ); logger.error( msg )
return False
elif err == -60031:
# https://developer.apple.com/documentation/security/1540004-authorization_services_result_co/errauthorizationtoolexecutefailure
msg = 'ERROR: root_child spwan attempt returned errAuthorizationToolExecuteFailure = -60031. Is the root child binary executable? Check permissions.'
print( msg ); logger.error( msg )
return False
elif err != 0:
# catch all other errors
msg = 'ERROR: root_child spawn attempt returned ' +str(err)+ '. Please see reference documentation for Apple Authorization Services Result Codes @ https://developer.apple.com/documentation/security/1540004-authorization_services_result_co'
print( msg ); logger.error( msg )
return False
msg = "DEBUG: Root child spawned successfully!"
print( msg ); logger.debug( msg )
return True
# this basically just re-implmenets python's readline().strip() but in C
def read_from_root_child_mac(self):
libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c"))
# get the output from the child process character-by-character until we hit a new line
buf = ctypes.create_string_buffer(1)
result = ''
for x in range(1,100):
# read one byte from the child process' communication PIPE and store it to the buffer
libc.fread( byref(buf), 1, 1, self.root_child['io'] )
# decode the byte stored to the buffer as ascii
char = buf.raw[:1].decode('ascii')
# is the character a newline?
if char == "\n":
# the character is a newline; stop reading
break
else:
# the character is not a newline; append it to the string and continue reading
result += char
return result
def handle_upgrades(self):
# check to see if we're currently running a new version that is being
# executed for the first time after replacing an old version
if os.path.isfile( os.path.join( self.EXE_DIR, 'upgraded_from.py' ) ):
from upgraded_from import UPGRADED_FROM
if os.path.isdir( UPGRADED_FROM['APP_DIR'] ):
msg = "DEBUG: Detected first-run of new version. Deleting old version."
msg += "\n\t" +str(UPGRADED_FROM)+ "\n"
print( msg ); logger.debug( msg )
# only proceed with this delete if the dir matches what we'd expect
if os.path.exists( os.path.join( UPGRADED_FROM['APP_DIR'], '.git' ) ):
msg = "DEBUG: Cowardly refusing to recursively delete an app that actually looks like a git sandbox."
print( msg ); logger.debug( msg )
# note that this actually works for both *nix & windows and doesn't
# fail with "unterminated character" errors
# * https://stackoverflow.com/a/54134464
elif re.match( ".*buskill-[^\\" +os.sep+ "]*$", UPGRADED_FROM['APP_DIR'] ):
# delete the old version's APP_DIR entirely
self.UPGRADED_FROM = UPGRADED_FROM
# don't exit on error
try:
# TODO: fix the restart on Windows so that the recursive
# delete after upgrade works and doesn't require a
# manual restart. See Also:
# * buskill_gui.py's handle_upgrades()
# * buskill_gui.py's upgrade5_restart()
self.UPGRADED_FROM['DELETE_FAILED'] = False
shutil.rmtree( self.UPGRADED_FROM['APP_DIR'] )
# and delete the 'upgraded_from.py' file so we don't try to
# delete the old version again
os.unlink( os.path.join( self.EXE_DIR, 'upgraded_from.py' ) )
except Exception as e:
self.UPGRADED_FROM['DELETE_FAILED'] = True
msg = "WARNING: Unable to delete old release (" +str(self.UPGRADED_FROM['APP_DIR'])+ ")"
msg+= "\n\t" +str(e)
print( msg ); logger.warn( msg )
else:
msg = "DEBUG: Cowardly refusing to recursively delete an old version that doesn't match our expected regex"
print( msg ); logger.debug( msg )
# check to see if we're currently running an old version whose
# replacement version has already been installed
if os.path.isfile( os.path.join( self.EXE_DIR, 'upgraded_to.py' ) ):
from upgraded_to import UPGRADED_TO
if os.path.exists( UPGRADED_TO['EXE_PATH'] ):
self.UPGRADED_TO = UPGRADED_TO
msg = "DEBUG: Detected that this version has already been upgraded. New version is:"
msg += "\n\t" +str(self.UPGRADED_TO)+ "\n"
print( msg ); logger.debug( msg )
def setupDataDir(self):
# first we choose where our data dir based on where we have write access
data_dirs = list()
# first try to create our data dir in the same dir that holds the dir
# where the buskill app was installed (and where future updates will be
# installed). This may be the BusKill USB drive itself.
data_dirs.append( self.APPS_DIR )
# Fall-back to the dir in which the executable is located
data_dirs.append( self.APP_DIR )
# finally, try the users's $HOME dir
data_dirs.append( os.path.join( os.path.expanduser('~') ) )
# iterate though our list of potential data dirs and pick the first one
# that we can actually write to
for data_dir in data_dirs:
try:
testfile = tempfile.TemporaryFile( dir=data_dir )
testfile.close()
except Exception as e:
# we were unable to write to this data_dir; try the next one
msg = "DEBUG: Unable to write to '" +data_dir+ "'; skipping."
msg += "\n\t" +str(e)+ "\n"
print( msg ); logger.debug( msg )
continue
# if we made it this far, we've confirmed that we can write to this
# data_dir. store it and exit the loop; we'll use this one.
self.DATA_DIR = os.path.join( data_dir, '.buskill' )
break
try:
msg = "INFO: using DATA_DIR:|" +str(self.DATA_DIR)+ "|"
print( msg ); logger.info( msg )
except:
msg = "WARNING: Unable to write to any DATA_DIR; not using one"
print( msg ); logger.warn( msg )
self.DATA_DIR = ''
return
# create cache dir (and clean if necessary) and data dir
self.CACHE_DIR = os.path.join( self.DATA_DIR, 'cache' )
self.wipeCache()
contents = "This is a runtime cache dir for BusKill that is deleted every time the BusKill app is launched or exits.\n\nFor more information, see https://buskill.in\n"
with open( os.path.join(self.CACHE_DIR, 'README.txt'), 'w' ) as fd:
fd.write( contents )
self.GNUPGHOME = os.path.join( self.CACHE_DIR, '.gnupg' )
def toggle(self):
if self.is_armed:
msg = "DEBUG: attempting to disarm BusKill"
print( msg ); logger.debug( msg )
# disarm just means to terminate the child process in which the arm
# function was spawned. this works on all platforms.
try:
self.usb_handler.kill()
self.usb_handler.join()
except:
pass
self.is_armed = False
msg = "INFO: BusKill is disarmed."
print( msg ); logger.info( msg )
else:
msg = "DEBUG: attempting to arm BusKill via " +str(self.ARM_FUNCTION)+ "()"
print( msg ); logger.debug( msg )
# launch an asynchronous child process that'll loop and listen for
# usb events
# self.usb_handler = self.Process(
self.usb_handler = multiprocessing.Process(
target = self.ARM_FUNCTION
)
self.usb_handler.start()
self.is_armed = True
msg = "INFO: BusKill is armed. Listening for removal event.\n"
msg+= "INFO: To disarm the CLI, exit with ^C or close this terminal"
print( msg ); logger.info( msg )
# this is a callback function that is registered to be called when a usb
# hotplug event occurs using libusb (linux & macos)
def hotplugCallbackNix( self, *argv ):
(context, device, event) = argv
msg = "DEBUG: called hotplugCallbackNix()"
print( msg ); logger.debug( msg )
msg = "context:|" +str(context)+ "|"
print( msg ); logger.debug( msg )
msg = "device:|" +str(device)+ "|"
print( msg ); logger.debug( msg )
msg = "event:|" +str(event)+ "|"
print( msg ); logger.debug( msg )
msg = "usb1.HOTPLUG_EVENT_DEVICE_LEFT:|" +str(usb1.HOTPLUG_EVENT_DEVICE_LEFT)+ "|"
print( msg ); logger.debug( msg )
# is this from a usb device being inserted or removed?
if event == usb1.HOTPLUG_EVENT_DEVICE_LEFT:
# this is a usb removal event
msg = "INFO: Detected USB removal event"
print( msg ); logger.info( msg )
msg = "calling " +str(self.TRIGGER_FUNCTION)
print( msg ); logger.debug( msg )
self.TRIGGER_FUNCTION()
# simulates a fake hotplug removal event
def simulate_hotplug_removal( self ):
if self.OS_NAME_SHORT == 'lin' or self.OS_NAME_SHORT == 'mac':
self.simulate_hotplug_removal_nix()
elif self.OS_NAME_SHORT == 'win':
self.simulate_hotplug_removal_win()
# simulates a fake hotplug removal event on *nix platforms
def simulate_hotplug_removal_nix( self ):
# call the callback for hotplug events with 'simulation' for both 'context'
# and 'event'. The last argument is the constant signifying that the
# hotplug event is specifically a *removal* event
self.hotplugCallbackNix( 'simulation', 'simulation', usb1.HOTPLUG_EVENT_DEVICE_LEFT )
# TODO: test this. DBT_DEVICEREMOVALCOMPLETE may not be avaialble and so this
# may need to move wayy up (next to the actual hotplugCallbackWin() function's definition
def simulate_hotplug_removal_win( self ):
# call the callback for hotplug events with 'simulation' for 'hwnd',
# 'message', and 'lparam'. The second-to-last argument is the constant
# signifying that the hotplug event is specifically a *removal* event
self.hotplugCallbackWin(
'simulation',
'simulation',
DBT_DEVICEREMOVECOMPLETE,
'simulation'
)
####################
# ARMING FUNCTIONS #
####################
# this works for both linux and mac
def armNix(self):
with usb1.USBContext() as context:
if not context.hasCapability(usb1.CAP_HAS_HOTPLUG):
msg = 'ERROR: Hotplug support is missing'
print( msg ); logger.error( msg )
return msg
opaque = context.hotplugRegisterCallback( self.hotplugCallbackNix )
try:
while True:
# this call is blocking (with a default timeout of 60 seconds)
# afaik there's no way to tell USBContext.handleEvents() to exit
# safely, so instead we just make the whole call to this arming
# function in a new child process and kill it on disarm with
# kill() this approach isn't very nice and it dumps a
# traceback to output, but it *does* immediately disarm without
# having wait for the timeout..
context.handleEvents()
except (KeyboardInterrupt, SystemExit) as e:
msg = "DEBUG: Exiting armNix() loop: " +str(e)
print( msg ); logger.info( msg )