-
Notifications
You must be signed in to change notification settings - Fork 18
/
picosnitch.py
executable file
·2629 lines (2523 loc) · 136 KB
/
picosnitch.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
# picosnitch
# Copyright (C) 2020-2023 Eric Lesiuta
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# https://github.com/elesiuta/picosnitch
import atexit
import collections
import ctypes
import ctypes.util
import curses
import datetime
import fcntl
import functools
import hashlib
import importlib
import importlib.util
import ipaddress
import json
import math
import multiprocessing
import os
import pickle
import pwd
import queue
import resource
import shlex
import shutil
import signal
import site
import socket
import sqlite3
import struct
import subprocess
import sys
import termios
import textwrap
import threading
import time
import typing
# add site dirs for system and user installed packages (to import bcc with picosnitch installed via pipx/venv, or dependencies installed via user)
site.addsitedir("/usr/lib/python3/dist-packages")
site.addsitedir(os.path.expandvars("$PYTHON_USER_SITE"))
import psutil
# picosnitch version and supported platform
VERSION: typing.Final[str] = "1.0.3"
assert sys.version_info >= (3, 8), "Python version >= 3.8 is required"
assert sys.platform.startswith("linux"), "Did not detect a supported operating system"
# warning about -O (optimize) flag since asserts are disabled and some are critical
if sys.flags.optimize > 0:
print("Warning: picosnitch does not function properly with the -O (optimize) flag", file=sys.stderr)
# set constants and RLIMIT_NOFILE if configured
try:
if os.getuid() == 0:
if os.getenv("SUDO_UID"):
home_user = pwd.getpwuid(int(os.getenv("SUDO_UID"))).pw_name
elif os.getenv("SUDO_USER"):
home_user = os.getenv("SUDO_USER")
elif os.getenv("DOAS_USER"):
home_user = os.getenv("DOAS_USER")
else:
for home_user in os.listdir("/home"):
try:
if pwd.getpwnam(home_user).pw_uid >= 1000:
break
except Exception:
pass
home_dir = pwd.getpwnam(home_user).pw_dir
if not os.getenv("SUDO_UID"):
os.environ["SUDO_UID"] = str(pwd.getpwnam(home_user).pw_uid)
if not os.getenv("DBUS_SESSION_BUS_ADDRESS"):
os.environ["DBUS_SESSION_BUS_ADDRESS"] = f"unix:path=/run/user/{pwd.getpwnam(home_user).pw_uid}/bus"
else:
home_dir = os.path.expanduser("~")
if sys.executable.startswith("/snap/"):
home_dir = home_dir.split("/snap/picosnitch")[0]
except Exception:
# fallback if there are no regular users on the system, this will likely be /root
home_dir = os.path.expanduser("~")
BASE_PATH: typing.Final[str] = os.path.join(home_dir, ".config", "picosnitch")
try:
file_path = os.path.join(BASE_PATH, "config.json")
with open(file_path, "r", encoding="utf-8", errors="surrogateescape") as json_file:
nofile = json.load(json_file)["Set RLIMIT_NOFILE"]
if type(nofile) == int:
try:
new_limit = (nofile, resource.getrlimit(resource.RLIMIT_NOFILE)[1])
resource.setrlimit(resource.RLIMIT_NOFILE, new_limit)
time.sleep(0.5)
except Exception as e:
print(type(e).__name__ + str(e.args), file=sys.stderr)
print("Error: Set RLIMIT_NOFILE was found in config.json but it could not be set", file=sys.stderr)
except Exception:
pass
FD_CACHE: typing.Final[int] = resource.getrlimit(resource.RLIMIT_NOFILE)[0] - 128
PID_CACHE: typing.Final[int] = max(8192, 2*FD_CACHE)
st_dev_mask = 0xffffffff
try:
for part in psutil.disk_partitions():
if part.fstype == "btrfs":
st_dev_mask = 0
if not os.path.exists(os.path.join(BASE_PATH, "config.json")):
# only warn users about btrfs on first run (by checking for config.json)
print("Warning: running picosnitch on systems with btrfs is not fully supported due to dev number strangeness and non-unique inodes (this is still fine for most use cases)", file=sys.stderr)
break
file_path = os.path.join(BASE_PATH, "config.json")
with open(file_path, "r", encoding="utf-8", errors="surrogateescape") as json_file:
set_mask = json.load(json_file)["Set st_dev mask"]
if type(set_mask) == int:
st_dev_mask = set_mask
except Exception:
pass
ST_DEV_MASK: typing.Final[int] = st_dev_mask
### classes
class Daemon:
"""A generic daemon class based on http://www.jejik.com/files/examples/daemon3x.py"""
def __init__(self, pidfile):
self.pidfile = pidfile
def daemonize(self):
"""Daemonize class. UNIX double fork mechanism."""
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #1 failed: {0}\n'.format(err))
sys.exit(1)
# decouple from parent environment
os.chdir('/')
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #2 failed: {0}\n'.format(err))
sys.exit(1)
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = open(os.devnull, 'r')
so = open(os.devnull, 'a+')
se = open(os.devnull, 'a+')
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write pidfile
atexit.register(self.delpid)
pid = str(os.getpid())
with open(self.pidfile,'w+') as f:
f.write(pid + '\n')
def delpid(self):
os.remove(self.pidfile)
def getpid(self):
"""Get the pid from the pidfile"""
try:
with open(self.pidfile, "r") as f:
pid = int(f.read().strip())
except IOError:
pid = None
return pid
def start(self):
"""Start the daemon."""
# Check for a pidfile to see if the daemon already runs
pid = self.getpid()
if pid:
message = "pidfile {0} already exist. " + \
"picosnitch already running?\n"
sys.stderr.write(message.format(self.pidfile))
sys.exit(1)
# Start the daemon
self.daemonize()
self.run()
def stop(self):
"""Stop the daemon."""
pid = self.getpid()
if not pid:
message = "pidfile {0} does not exist. " + \
"picosnitch not running?\n"
sys.stderr.write(message.format(self.pidfile))
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
except OSError as err:
e = str(err.args)
if e.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print (str(err.args))
sys.exit(1)
def restart(self):
"""Restart the daemon."""
self.stop()
self.start()
def status(self):
"""Get daemon status."""
pid = self.getpid()
if pid:
try:
with open(f"/proc/{pid}/cmdline", "r") as f:
cmdline = f.read()
except Exception:
cmdline = ""
if "picosnitch" in cmdline:
print(f"picosnitch is currently running with pid {pid}.")
else:
print("pidfile exists however picosnitch was not detected.")
else:
print("picosnitch does not appear to be running.")
def run(self):
"""Subclass Daemon and override this method"""
class ProcessManager:
"""A class for managing a subprocess"""
def __init__(self, name: str, target: typing.Callable, init_args: tuple = ()) -> None:
self.name, self.target, self.init_args = name, target, init_args
self.q_in, self.q_out = multiprocessing.Queue(), multiprocessing.Queue()
self.start()
def start(self) -> None:
self.p = multiprocessing.Process(name=self.name, target=self.target, daemon=True,
args=(*self.init_args, self.q_in, self.q_out)
)
self.p.start()
self.pp = psutil.Process(self.p.pid)
def terminate(self) -> None:
if self.p.is_alive():
self.p.terminate()
self.p.join(timeout=5)
if self.p.is_alive():
self.p.kill()
self.p.join(timeout=5)
self.p.close()
def is_alive(self) -> bool:
return self.p.is_alive()
def is_zombie(self) -> bool:
return self.pp.is_running() and self.pp.status() == psutil.STATUS_ZOMBIE
def memory(self) -> int:
return self.pp.memory_info().rss
class NotificationManager:
"""A singleton for creating system tray notifications, holds notifications in queue if fails, prints if disabled"""
__instance = None
dbus_notifications = False
notifications_ready = False
notification_queue = []
last_notification = ""
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = super(NotificationManager, cls).__new__(cls, *args, **kwargs)
return cls.__instance
def enable_notifications(self):
self.dbus_notifications = True
try:
import dbus
os.seteuid(int(os.getenv("SUDO_UID")))
dbus_session_obj = dbus.SessionBus().get_object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")
interface = dbus.Interface(dbus_session_obj, "org.freedesktop.Notifications")
self.system_notification = lambda msg: interface.Notify("picosnitch", 0, "", "picosnitch", msg, [], [], 2000)
self.notifications_ready = True
except Exception:
pass
finally:
os.seteuid(os.getuid())
def toast(self, msg: str, file=sys.stdout) -> None:
try:
if self.notifications_ready:
if self.last_notification != msg:
self.last_notification = msg
self.system_notification(msg)
else:
print(msg, file=file)
self.notification_queue.append(msg)
if self.dbus_notifications:
self.enable_notifications()
if self.notifications_ready:
for msg in self.notification_queue:
try:
if self.last_notification != msg:
self.last_notification = msg
self.system_notification(msg)
except Exception:
pass
self.notification_queue = []
except Exception:
self.notification_queue.append(msg)
self.notifications_ready = False
class BpfEvent(typing.TypedDict):
"""Process and connection data for each event captured by the BPF program, and sent to the main & secondary processes"""
pid: int
name: str
fd: int
dev: int
ino: int
exe: str
cmdline: str
ppid: int
pname: str
pfd: int
pdev: int
pino: int
pexe: str
pcmdline: str
uid: int
send: int
recv: int
lport: int
rport: int
laddr: str
raddr: str
domain: str
class FanotifyEventMetadata(ctypes.Structure):
"""https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/uapi/linux/fanotify.h"""
_fields_ = [
("event_len", ctypes.c_uint32),
("vers", ctypes.c_uint8),
("reserved", ctypes.c_uint8),
("metadata_len", ctypes.c_uint16),
("mask", ctypes.c_uint64),
("fd", ctypes.c_int32),
("pid", ctypes.c_int32)
]
### functions
def read_snitch() -> dict:
"""read data for the snitch dictionary from config.json and record.json or init new files if not found"""
template = {
"Config": {
"DB retention (days)": 30,
"DB sql log": True,
"DB sql server": {},
"DB text log": False,
"DB write limit (seconds)": 10,
"Dash scroll zoom": True,
"Dash theme": "",
"Desktop notifications": True,
"Every exe (not just conns)": False,
"GeoIP lookup": True,
"Log addresses": True,
"Log commands": True,
"Log ignore": [],
"Log ports": True,
"Perf ring buffer (pages)": 256,
"Set RLIMIT_NOFILE": None,
"Set st_dev mask": None,
"VT API key": "",
"VT file upload": False,
"VT request limit (seconds)": 15
},
"Error Log": [],
"Exe Log": [],
"Executables": {},
"Names": {},
"Parent Executables": {},
"Parent Names": {},
"SHA256": {}
}
data = {k: v for k, v in template.items()}
data["Config"] = {k: v for k, v in template["Config"].items()}
write_config = False
config_path = os.path.join(BASE_PATH, "config.json")
record_path = os.path.join(BASE_PATH, "record.json")
if os.path.exists(config_path):
with open(config_path, "r", encoding="utf-8", errors="surrogateescape") as json_file:
data["Config"] = json.load(json_file)
for key in template["Config"]:
if key not in data["Config"]:
data["Config"][key] = template["Config"][key]
write_config = True
else:
write_config = True
if os.path.exists(record_path):
with open(record_path, "r", encoding="utf-8", errors="surrogateescape") as json_file:
snitch_record = json.load(json_file)
for key in ["Executables", "Names", "Parent Executables", "Parent Names", "SHA256"]:
if key in snitch_record:
data[key] = snitch_record[key]
assert all(type(data[key]) == type(template[key]) for key in template), "Invalid json files"
assert all(key in ["Set RLIMIT_NOFILE", "Set st_dev mask"] or type(data["Config"][key]) == type(template["Config"][key]) for key in template["Config"]), "Invalid config"
if write_config:
write_snitch(data, write_config=True)
return data
def write_snitch(snitch: dict, write_config: bool = False, write_record: bool = True) -> None:
"""write the snitch dictionary to config.json, record.json, exe.log, and error.log"""
config_path = os.path.join(BASE_PATH, "config.json")
record_path = os.path.join(BASE_PATH, "record.json")
exe_log_path = os.path.join(BASE_PATH, "exe.log")
error_log_path = os.path.join(BASE_PATH, "error.log")
assert os.getuid() == 0, "Requires root privileges to write config and log files"
if not os.path.isdir(BASE_PATH):
os.makedirs(BASE_PATH)
if os.stat(BASE_PATH).st_uid == 0 and os.getenv("SUDO_UID"):
os.chown(BASE_PATH, int(os.getenv("SUDO_UID")), int(os.getenv("SUDO_UID")))
snitch_config = snitch["Config"]
try:
if write_config:
with open(config_path, "w", encoding="utf-8", errors="surrogateescape") as json_file:
json.dump(snitch_config, json_file, indent=2, separators=(',', ': '), sort_keys=True, ensure_ascii=False)
del snitch["Config"]
if snitch["Error Log"]:
with open(error_log_path, "a", encoding="utf-8", errors="surrogateescape") as text_file:
text_file.write("\n".join(snitch["Error Log"]) + "\n")
del snitch["Error Log"]
if snitch["Exe Log"]:
with open(exe_log_path, "a", encoding="utf-8", errors="surrogateescape") as text_file:
text_file.write("\n".join(snitch["Exe Log"]) + "\n")
del snitch["Exe Log"]
if write_record:
with open(record_path, "w", encoding="utf-8", errors="surrogateescape") as json_file:
json.dump(snitch, json_file, indent=2, separators=(',', ': '), sort_keys=True, ensure_ascii=False)
except Exception:
NotificationManager().toast("picosnitch write error", file=sys.stderr)
snitch["Config"] = snitch_config
snitch["Error Log"] = []
snitch["Exe Log"] = []
@functools.lru_cache(maxsize=None)
def reverse_dns_lookup(ip: str) -> str:
"""do a reverse dns lookup, return original ip if fails"""
try:
host = socket.getnameinfo((ip, 0), 0)[0]
try:
_ = ipaddress.ip_address(host)
return ip
except ValueError:
return ".".join(reversed(host.split(".")))
except Exception:
return ip
@functools.lru_cache(maxsize=PID_CACHE)
def get_sha256_fd(path: str, st_dev: int, st_ino: int, _mod_cnt: int) -> str:
"""get sha256 of process executable from /proc/monitor_pid/fd/proc_exe_fd"""
try:
sha256 = hashlib.sha256()
with open(path, "rb") as f:
if not st_ino:
return "!!! FD Stat Error"
if (st_dev, st_ino) != get_fstat(f.fileno()):
return "!!! FD Cache Error"
while data := f.read(1048576):
sha256.update(data)
return sha256.hexdigest()
except Exception:
return "!!! FD Read Error"
@functools.lru_cache(maxsize=PID_CACHE)
def get_sha256_pid(pid: int, st_dev: int, st_ino: int) -> str:
"""get sha256 of process executable from /proc/pid/exe"""
try:
sha256 = hashlib.sha256()
with open(f"/proc/{pid}/exe", "rb") as f:
if (st_dev, st_ino) != get_fstat(f.fileno()):
return "!!! PID Recycled Error"
while data := f.read(1048576):
sha256.update(data)
return sha256.hexdigest()
except Exception:
return "!!! PID Read Error"
@functools.lru_cache(maxsize=PID_CACHE)
def get_sha256_fuse(q_in: multiprocessing.Queue, q_out: multiprocessing.Queue, path: str, pid: int, st_dev: int, st_ino: int, _mod_cnt: int) -> str:
"""get sha256 of process executable from a fuse mount"""
q_in.put(pickle.dumps((path, pid, st_dev, st_ino)))
try:
return q_out.get()
except Exception:
return "!!! FUSE Subprocess Error"
def get_fstat(fd: int) -> typing.Tuple[int, int]:
"""get (st_dev, st_ino) or (0, 0) if fails"""
try:
stat = os.fstat(fd)
return stat.st_dev & ST_DEV_MASK, stat.st_ino
except Exception:
return 0, 0
def get_fanotify_events(fan_fd: int, fan_mod_cnt: dict, q_error: multiprocessing.Queue) -> None:
"""check if any watched executables were modified and increase count to trigger rehash"""
sizeof_event = ctypes.sizeof(FanotifyEventMetadata)
bytes_avail = ctypes.c_int()
fcntl.ioctl(fan_fd, termios.FIONREAD, bytes_avail)
for i in range(0, bytes_avail.value, sizeof_event):
try:
fanotify_event_metadata = FanotifyEventMetadata()
buf = os.read(fan_fd, sizeof_event)
ctypes.memmove(ctypes.addressof(fanotify_event_metadata), buf, sizeof_event)
st_dev, st_ino = get_fstat(fanotify_event_metadata.fd)
fan_mod_cnt[f"{st_dev} {st_ino}"] += 1
os.close(fanotify_event_metadata.fd)
except Exception as e:
q_error.put("Fanotify Event %s%s on line %s" % (type(e).__name__, str(e.args), sys.exc_info()[2].tb_lineno))
def get_vt_results(snitch: dict, q_vt: multiprocessing.Queue, q_out: multiprocessing.Queue, check_pending: bool = False) -> None:
"""get virustotal results from subprocess and update snitch, q_vt = q_in if check_pending else q_out"""
if check_pending:
for exe in snitch["SHA256"]:
for sha256 in snitch["SHA256"][exe]:
if snitch["SHA256"][exe][sha256] in ["VT Pending", "File not analyzed (no api key)", "", None]:
if exe in snitch["Executables"] and snitch["Executables"][exe]:
name = snitch["Executables"][exe][0]
elif exe in snitch["Parent Executables"] and snitch["Parent Executables"][exe]:
name = snitch["Parent Executables"][exe][0]
else:
name = exe
proc = {"exe": exe, "name": name}
q_vt.put(pickle.dumps((proc, sha256)))
else:
while not q_vt.empty():
proc, sha256, result, suspicious = pickle.loads(q_vt.get())
q_out.put(pickle.dumps({"type": "vt_result", "name": proc["name"], "exe": proc["exe"], "sha256": sha256, "result": result, "suspicious": suspicious}))
def monitor_subprocess_initial_poll() -> list:
"""poll initial processes and connections using psutil"""
initial_processes = []
for pid in psutil.pids():
try:
proc = psutil.Process(pid).as_dict(attrs=["name", "exe", "pid", "ppid", "uids"], ad_value="")
proc["uid"] = proc["uids"][0]
proc["pname"] = psutil.Process(proc["ppid"]).name()
proc["raddr"] = ""
proc["rport"] = -1
proc["laddr"] = ""
proc["lport"] = -1
initial_processes.append(proc)
except Exception:
pass
for conn in psutil.net_connections(kind="all"):
try:
proc = psutil.Process(conn.pid).as_dict(attrs=["name", "exe", "pid", "ppid", "uids"], ad_value="")
proc["uid"] = proc["uids"][0]
proc["pname"] = psutil.Process(proc["ppid"]).name()
proc["raddr"] = conn.raddr.ip
proc["rport"] = conn.raddr.port
proc["laddr"] = conn.laddr.ip
proc["lport"] = conn.laddr.port
initial_processes.append(proc)
except Exception:
pass
return initial_processes
def secondary_subprocess_sha_wrapper(snitch: dict, fan_mod_cnt: dict, proc: dict, p_rfuse: ProcessManager, q_vt: multiprocessing.Queue, q_out: multiprocessing.Queue, q_error: multiprocessing.Queue) -> str:
"""get sha256 of executable and submit to primary_subprocess or virustotal_subprocess if necessary"""
sha_fd_error = ""
sha_pid_error = ""
sha256 = get_sha256_fd(proc["fd"], proc["dev"], proc["ino"], fan_mod_cnt["%d %d" % (proc["dev"], proc["ino"])])
if sha256.startswith("!"):
# fallback on trying to read directly (if still alive) if fd_cache fails, probable causes include:
# system suspends in the middle of hashing (since cache is reset)
# process too short lived to open fd or stat in time (then fallback will fail too)
# too many executables on system (see Set RLIMIT_NOFILE)
sha_fd_error = sha256
sha256 = get_sha256_pid(proc["pid"], proc["dev"], proc["ino"])
if sha256.startswith("!"):
# fallback to trying to read from fuse mount
# this is meant for appimages that are run as the same user as the one running picosnitch, since they are not readable as root
sha_pid_error = sha256
sha256 = get_sha256_fuse(p_rfuse.q_in, p_rfuse.q_out, proc["fd"], proc["pid"], proc["dev"], proc["ino"], fan_mod_cnt["%d %d" % (proc["dev"], proc["ino"])])
if sha256.startswith("!"):
# notify user with what went wrong (may be cause for suspicion)
sha256_error = sha_fd_error[4:] + " and " + sha_pid_error[4:] + " and " + sha256[4:]
sha256 = sha_fd_error + " " + sha_pid_error + " " + sha256
q_error.put(sha256_error + " for " + str(proc))
elif proc["exe"] not in snitch["SHA256"] or sha256 not in snitch["SHA256"][proc["exe"]]:
q_error.put("Fallback to FUSE hash successful on " + sha_fd_error[4:] + " and " + sha_pid_error[4:] + " for " + str(proc))
elif proc["exe"] not in snitch["SHA256"] or sha256 not in snitch["SHA256"][proc["exe"]]:
q_error.put("Fallback to PID hash successful on " + sha_fd_error[4:] + " for " + str(proc))
if proc["exe"] in snitch["SHA256"]:
if sha256 not in snitch["SHA256"][proc["exe"]]:
snitch["SHA256"][proc["exe"]][sha256] = "SUBMITTED"
q_vt.put(pickle.dumps((proc, sha256)))
q_out.put(pickle.dumps({"type": "sha256", "name": proc["name"], "exe": proc["exe"], "sha256": sha256}))
elif snitch["SHA256"][proc["exe"]][sha256] == "Failed to read process for upload":
snitch["SHA256"][proc["exe"]][sha256] = "RETRY"
q_vt.put(pickle.dumps((proc, sha256)))
else:
snitch["SHA256"][proc["exe"]] = {sha256: "SUBMITTED"}
q_vt.put(pickle.dumps((proc, sha256)))
q_out.put(pickle.dumps({"type": "sha256", "name": proc["name"], "exe": proc["exe"], "sha256": sha256}))
return sha256
def secondary_subprocess_helper(snitch: dict, fan_mod_cnt: dict, new_processes: typing.List[bytes], p_rfuse: ProcessManager, q_vt: multiprocessing.Queue, q_out: multiprocessing.Queue, q_error: multiprocessing.Queue) -> typing.List[tuple]:
"""iterate over the list of process/connection data to generate a list of entries for the sql database"""
datetime_now = time.strftime("%Y-%m-%d %H:%M:%S")
traffic_counter = collections.defaultdict(int)
transaction = set()
for proc_pickle in new_processes:
proc: BpfEvent = pickle.loads(proc_pickle)
if type(proc) != dict:
q_error.put("sync error between secondary and primary, received '%s' in middle of transfer" % str(proc))
continue
# get the sha256 of the process executable and its parent
sha256 = secondary_subprocess_sha_wrapper(snitch, fan_mod_cnt, proc, p_rfuse, q_vt, q_out, q_error)
pproc = {"pid": proc["ppid"], "name": proc["pname"], "exe": proc["pexe"], "fd": proc["pfd"], "dev": proc["pdev"], "ino": proc["pino"]}
psha256 = secondary_subprocess_sha_wrapper(snitch, fan_mod_cnt, pproc, p_rfuse, q_vt, q_out, q_error)
# join or omit commands from logs
if snitch["Config"]["Log commands"]:
proc["cmdline"] = shlex.join(proc["cmdline"].encode("utf-8", "ignore").decode("utf-8", "ignore").strip("\0\t\n ").split("\0"))
proc["pcmdline"] = shlex.join(proc["pcmdline"].encode("utf-8", "ignore").decode("utf-8", "ignore").strip("\0\t\n ").split("\0"))
else:
proc["cmdline"] = ""
proc["pcmdline"] = ""
# reverse dns lookup or omit with IP from logs
if snitch["Config"]["Log addresses"]:
if not proc["domain"]:
proc["domain"] = reverse_dns_lookup(proc["raddr"])
else:
proc["domain"], proc["raddr"] = "", ""
if not snitch["Config"]["Log ports"]:
proc["lport"] = min(0, proc["lport"])
proc["rport"] = min(0, proc["rport"])
# omit entry from logs
ignored = False
for ignore in snitch["Config"]["Log ignore"]:
if ((proc["rport"] == ignore) or
(proc["lport"] == ignore) or
(sha256 == ignore) or
(type(ignore) == str and proc["domain"].startswith(ignore))
):
ignored = True
break
if ignored:
continue
if snitch["Config"]["Log ignore IP"] and proc["raddr"]:
raddr = ipaddress.ip_address(proc["raddr"])
if (any(raddr in network for network in snitch["Config"]["Log ignore IP"])):
continue
laddr = ipaddress.ip_address(proc["laddr"])
if (any(laddr in network for network in snitch["Config"]["Log ignore IP"])):
continue
# create sql entry
event = (proc["exe"], proc["name"], proc["cmdline"], sha256, proc["pexe"], proc["pname"], proc["pcmdline"], psha256, proc["uid"], proc["lport"], proc["rport"], proc["laddr"], proc["raddr"], proc["domain"])
traffic_counter["send " + str(event)] += proc["send"]
traffic_counter["recv " + str(event)] += proc["recv"]
transaction.add(event)
return [(datetime_now, traffic_counter["send " + str(event)], traffic_counter["recv " + str(event)], *event) for event in transaction]
def primary_subprocess_helper(snitch: dict, new_processes: typing.List[bytes]) -> None:
"""iterate over the list of process/connection data to update the snitch dictionary and create notifications on new entries"""
datetime_now = time.strftime("%Y-%m-%d %H:%M:%S")
for proc_pickle in new_processes:
proc: BpfEvent = pickle.loads(proc_pickle)
proc_name, proc_exe, snitch_names, snitch_executables, parent = proc["name"], proc["exe"], snitch["Names"], snitch["Executables"], ""
for i in range(2):
notification = []
if proc_name in snitch_names:
if proc_exe not in snitch_names[proc_name]:
snitch_names[proc_name].append(proc_exe)
else:
snitch_names[proc_name] = [proc_exe]
notification.append("name")
if proc_exe in snitch_executables:
if proc_name not in snitch_executables[proc_exe]:
snitch_executables[proc_exe].append(proc_name)
else:
snitch_executables[proc_exe] = [proc_name]
notification.append("exe")
if proc_exe not in snitch["SHA256"]:
snitch["SHA256"][proc_exe] = {}
if notification:
snitch["Exe Log"].append(f"{datetime_now} {proc_name:<16.16} {proc_exe} (new {', '.join(notification)}){parent}")
NotificationManager().toast(f"picosnitch: {proc_name} {proc_exe}")
proc_name, proc_exe, snitch_names, snitch_executables, parent = proc["pname"], proc["pexe"], snitch["Parent Names"], snitch["Parent Executables"], " (parent)"
### processes
def primary_subprocess(snitch, snitch_pipes, secondary_pipe, q_error, q_in, _q_out):
"""first to receive connection data from monitor, more responsive than secondary, creates notifications and writes exe.log, error.log, and record.json"""
try:
os.nice(-20)
except Exception:
pass
# init variables for loop
parent_process = multiprocessing.parent_process()
snitch_record = pickle.dumps([snitch["Executables"], snitch["Names"], snitch["Parent Executables"], snitch["Parent Names"], snitch["SHA256"]])
last_write = 0
write_record = False
processes_to_send = []
# init notifications
if snitch["Config"]["Desktop notifications"]:
NotificationManager().enable_notifications()
# init signal handlers
def write_snitch_and_exit(snitch: dict, q_error: multiprocessing.Queue, snitch_pipes):
while not q_error.empty():
error = q_error.get()
snitch["Error Log"].append(time.strftime("%Y-%m-%d %H:%M:%S") + " " + error)
# shorten some common error messages before displaying them and after writing them to error.log
error = error.replace("FD Read Error and PID Read Error and FUSE Read Error for", "Read Error for")
if len(error) > 50:
error = error[:47] + "..."
NotificationManager().toast(error, file=sys.stderr)
write_snitch(snitch)
for snitch_pipe in snitch_pipes:
snitch_pipe.close()
sys.exit(0)
signal.signal(signal.SIGTERM, lambda *args: write_snitch_and_exit(snitch, q_error, snitch_pipes))
signal.signal(signal.SIGINT, lambda *args: write_snitch_and_exit(snitch, q_error, snitch_pipes))
# init thread to receive new connection data over pipe
def snitch_pipe_thread(snitch_pipes, pipe_data: list, listen: threading.Event, ready: threading.Event):
while True:
listen.wait()
new_processes = pipe_data[0]
while listen.is_set():
for i in range(5):
if any(snitch_pipe.poll() for snitch_pipe in snitch_pipes):
break
time.sleep(1)
for snitch_pipe in snitch_pipes:
while snitch_pipe.poll():
new_processes.append(snitch_pipe.recv_bytes())
ready.set()
listen, ready = threading.Event(), threading.Event()
pipe_data = [[]]
thread = threading.Thread(target=snitch_pipe_thread, args=(snitch_pipes, pipe_data, listen, ready,), daemon=True)
thread.start()
listen.set()
# main loop
while True:
if not parent_process.is_alive():
q_error.put("picosnitch has stopped")
write_snitch_and_exit(snitch, q_error, snitch_pipes)
try:
# check for errors
while not q_error.empty():
error = q_error.get()
snitch["Error Log"].append(time.strftime("%Y-%m-%d %H:%M:%S") + " " + error)
# shorten some common error messages before displaying them and after writing them to error.log
error = error.replace("FD Read Error and PID Read Error and FUSE Read Error for", "Read Error for")
if len(error) > 50:
error = error[:47] + "..."
# don't need to toast fallback success messages
if error.startswith("Fallback to FUSE hash successful on ") or error.startswith("Fallback to PID hash successful on "):
continue
NotificationManager().toast(error, file=sys.stderr)
# get list of new processes and connections since last update
listen.clear()
if not ready.wait(timeout=300):
q_error.put("thread timeout error for primary subprocess")
write_snitch_and_exit(snitch, q_error, snitch_pipes)
new_processes = pipe_data[0]
pipe_data[0] = []
ready.clear()
listen.set()
# process the list and update snitch, send new process/connection data to secondary subprocess if ready
primary_subprocess_helper(snitch, new_processes)
processes_to_send += new_processes
while not q_in.empty():
msg: dict = pickle.loads(q_in.get())
if msg["type"] == "ready":
secondary_pipe.send_bytes(pickle.dumps(len(processes_to_send)))
for proc_pickle in processes_to_send:
secondary_pipe.send_bytes(proc_pickle)
secondary_pipe.send_bytes(pickle.dumps("done"))
processes_to_send = []
break
elif msg["type"] == "sha256":
if msg["exe"] in snitch["SHA256"]:
if msg["sha256"] not in snitch["SHA256"][msg["exe"]]:
snitch["SHA256"][msg["exe"]][msg["sha256"]] = "VT Pending"
snitch["Exe Log"].append(f"{time.strftime('%Y-%m-%d %H:%M:%S')} {msg['sha256']:<16.16} {msg['exe']} (new hash)")
NotificationManager().toast(f"New sha256: {msg['exe']}")
else:
snitch["SHA256"][msg["exe"]] = {msg["sha256"]: "VT Pending"}
elif msg["type"] == "vt_result":
if msg["exe"] in snitch["SHA256"]:
if msg["sha256"] not in snitch["SHA256"][msg["exe"]]:
snitch["Exe Log"].append(f"{time.strftime('%Y-%m-%d %H:%M:%S')} {msg['sha256']:<16.16} {msg['exe']} (new hash)")
NotificationManager().toast(f"New sha256: {msg['exe']}")
snitch["SHA256"][msg["exe"]][msg["sha256"]] = msg["result"]
else:
snitch["SHA256"][msg["exe"]] = {msg["sha256"]: msg["result"]}
if msg["suspicious"]:
snitch["Exe Log"].append(f"{time.strftime('%Y-%m-%d %H:%M:%S')} {msg['sha256']:<16.16} {msg['exe']} (suspicious)")
NotificationManager().toast(f"Suspicious VT results: {msg['exe']}")
else:
snitch["Exe Log"].append(f"{time.strftime('%Y-%m-%d %H:%M:%S')} {msg['sha256']:<16.16} {msg['exe']} (clean)")
# write the snitch dictionary to record.json, error.log, and exe.log (limit writes to reduce disk wear)
if snitch["Error Log"] or snitch["Exe Log"] or time.time() - last_write > 30:
new_record = pickle.dumps([snitch["Executables"], snitch["Names"], snitch["Parent Executables"], snitch["Parent Names"], snitch["SHA256"]])
if new_record != snitch_record:
snitch_record = new_record
write_record = True
write_snitch(snitch, write_record=write_record)
last_write = time.time()
write_record = False
except Exception as e:
q_error.put("primary subprocess %s%s on line %s" % (type(e).__name__, str(e.args), sys.exc_info()[2].tb_lineno))
def secondary_subprocess(snitch, fan_fd, p_rfuse: ProcessManager, p_virustotal: ProcessManager, secondary_pipe, q_primary_in, q_error, _q_in, _q_out):
"""second to receive connection data from monitor, less responsive than primary, coordinates connection data with virustotal subprocess and checks fanotify, updates connection logs and reports sha256/vt_results back to primary_subprocess if needed"""
parent_process = multiprocessing.parent_process()
# maintain a separate copy of the snitch dictionary here and coordinate with the primary_subprocess (sha256 and vt_results)
get_vt_results(snitch, p_virustotal.q_in, q_primary_in, True)
# init sql
# (contime text, send integer, recv integer, exe text, name text, cmdline text, sha256 text, pexe text, pname text, pcmdline text, psha256 text, uid integer, lport integer, rport integer, laddr text, raddr text, domain text)
# (datetime_now, traffic_counter["send " + str(event)], traffic_counter["recv " + str(event)], *(proc["exe"], proc["name"], proc["cmdline"], sha256, proc["pexe"], proc["pname"], proc["pcmdline"], psha256, proc["uid"], proc["lport"], proc["rport"], proc["laddr"], proc["raddr"], proc["domain"]))
sqlite_query = ''' INSERT INTO connections VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) '''
file_path = os.path.join(BASE_PATH, "snitch.db")
text_path = os.path.join(BASE_PATH, "conn.log")
if snitch["Config"]["DB sql log"]:
con = sqlite3.connect(file_path)
cur = con.cursor()
cur.execute(''' PRAGMA user_version ''')
assert cur.fetchone()[0] == 3, f"Incorrect database version of snitch.db for picosnitch v{VERSION}"
cur.execute(''' DELETE FROM connections WHERE contime < datetime("now", "localtime", "-%d days") ''' % int(snitch["Config"]["DB retention (days)"]))
con.commit()
con.close()
if sql_kwargs := snitch["Config"]["DB sql server"]:
sql_client = sql_kwargs.pop("client", "no client error")
table_name = sql_kwargs.pop("table_name", "connections")
sql = importlib.import_module(sql_client)
sql_query = sqlite_query.replace("?", "%s").replace("connections", table_name)
log_destinations = int(bool(snitch["Config"]["DB sql log"])) + int(bool(sql_kwargs)) + int(bool(snitch["Config"]["DB text log"]))
# init fanotify mod counter = {"st_dev st_ino": modify_count}, and traffic counter = {"send|recv pid socket_ino": bytes}
fan_mod_cnt = collections.defaultdict(int)
# get network address and mask for ignored IP subnets
ignored_ips = []
for ip_subnet in reversed(snitch["Config"]["Log ignore"]):
try:
ignored_ips.append(ipaddress.ip_network(ip_subnet))
snitch["Config"]["Log ignore"].remove(ip_subnet)
except Exception as e:
pass
snitch["Config"]["Log ignore IP"] = ignored_ips
# main loop
transaction = []
new_processes = []
last_write = 0
while True:
if not parent_process.is_alive():
return 0
try:
# prep to receive new connections
if secondary_pipe.poll():
q_error.put("sync error between secondary and primary on ready (pipe not empty)")
else:
q_primary_in.put(pickle.dumps({"type": "ready"}))
secondary_pipe.poll(timeout=300)
if not secondary_pipe.poll():
q_error.put("sync error between secondary and primary on ready (secondary timed out waiting for first message)")
# receive first message, should be transfer size
transfer_size = 0
if secondary_pipe.poll():
first_pickle = secondary_pipe.recv_bytes()
if type(pickle.loads(first_pickle)) == int:
transfer_size = pickle.loads(first_pickle)
elif pickle.loads(first_pickle) == "done":
q_error.put("sync error between secondary and primary on ready (received done)")
else:
q_error.put("sync error between secondary and primary on ready (did not receive transfer size)")
new_processes.append(first_pickle)
# receive new connections until "done"
timeout_counter = 0
while True:
while secondary_pipe.poll(timeout=1):
new_processes.append(secondary_pipe.recv_bytes())
transfer_size -= 1
timeout_counter += 1
if pickle.loads(new_processes[-1]) == "done":
_ = new_processes.pop()
transfer_size += 1
break
elif timeout_counter > 30:
q_error.put("sync error between secondary and primary on receive (did not receive done)")
if transfer_size > 0:
q_error.put("sync error between secondary and primary on receive (did not receive all messages)")
elif transfer_size < 0:
q_error.put("sync error between secondary and primary on receive (received extra messages)")
# check for other pending data (vt, fanotify)
get_vt_results(snitch, p_virustotal.q_out, q_primary_in, False)
get_fanotify_events(fan_fd, fan_mod_cnt, q_error)
# process connection data
if time.time() - last_write > snitch["Config"]["DB write limit (seconds)"] and (transaction or new_processes):
current_write = time.time()
transaction += secondary_subprocess_helper(snitch, fan_mod_cnt, new_processes, p_rfuse, p_virustotal.q_in, q_primary_in, q_error)
new_processes = []
transaction_success = False
try:
if snitch["Config"]["DB sql log"]:
con = sqlite3.connect(file_path)
with con:
con.executemany(sqlite_query, transaction)
con.close()
transaction_success = True
except Exception as e:
q_error.put("SQLite execute %s%s on line %s, lost %s entries" % (type(e).__name__, str(e.args), sys.exc_info()[2].tb_lineno, len(transaction)))
try:
if sql_kwargs:
con = sql.connect(**sql_kwargs)
with con.cursor() as cur:
cur.executemany(sql_query, transaction)
con.commit()
con.close()
transaction_success = True
except Exception as e:
q_error.put("SQL server execute %s%s on line %s, lost %s entries" % (type(e).__name__, str(e.args), sys.exc_info()[2].tb_lineno, len(transaction)))
try:
if snitch["Config"]["DB text log"]:
with open(text_path, "a", encoding="utf-8", errors="surrogateescape") as text_file:
for entry in transaction:
clean_entry = [str(value).replace(",", "").replace("\n", "").replace("\0", "") for value in entry]
text_file.write(",".join(clean_entry) + "\n")
transaction_success = True
except Exception as e:
q_error.put("text log %s%s on line %s, lost %s entries" % (type(e).__name__, str(e.args), sys.exc_info()[2].tb_lineno, len(transaction)))
if transaction_success or log_destinations == 0:
transaction = []
else:
q_error.put("secondary subprocess all log desinations failed, will retry %s entries with next write" % (len(transaction)))
last_write = current_write
except Exception as e:
q_error.put("secondary subprocess %s%s on line %s" % (type(e).__name__, str(e.args), sys.exc_info()[2].tb_lineno))
def rfuse_subprocess(config: dict, q_error, q_in, q_out):
"""runs as user to read executables for FUSE/AppImage (since real, effective, and saved UID must match)"""
parent_process = multiprocessing.parent_process()
try:
os.setgid(int(os.getenv("SUDO_UID")))
os.setuid(int(os.getenv("SUDO_UID")))
except Exception:
pass
while True:
if not parent_process.is_alive():
return 0
try:
path, pid, st_dev, st_ino = pickle.loads(q_in.get(block=True, timeout=15))
sha256 = get_sha256_fd.__wrapped__(path, st_dev, st_ino, 0)
if sha256.startswith("!"):
sha256 = get_sha256_pid.__wrapped__(pid, st_dev, st_ino)
if sha256.startswith("!"):
sha256 = "!!! FUSE Read Error"
q_out.put(sha256)
except queue.Empty:
pass
except Exception as e:
q_error.put("rfuse subprocess %s%s on line %s" % (type(e).__name__, str(e.args), sys.exc_info()[2].tb_lineno))