Python3 port

This commit is contained in:
adisbladis 2017-05-05 12:35:40 +08:00
parent 8496b3e4a7
commit 380c0d9edc
Failed to generate hash of commit
6 changed files with 43 additions and 39 deletions

View file

@ -1,4 +1,4 @@
#!/usr/bin/env python2
#!/usr/bin/env python3
# This file is part of OpenSnitch.
#
# Copyright(c) 2017 Simone Margaritelli
@ -45,9 +45,11 @@ else:
from opensnitch.version import VERSION
logging.basicConfig( format = '[%(asctime)s] (%(levelname)s) %(message)s',
level = logging.INFO if options.debug == False else logging.DEBUG,
filename = '/dev/stdout' if options.logfile is None else options.logfile )
logging.basicConfig(
format = '[%(asctime)s] (%(levelname)s) %(message)s',
level = logging.INFO if options.debug == False else logging.DEBUG,
filename = options.logfile)
# At some point Scapy devs will realize how bothering their fucking warnings
# are while importing scapy.all ...
@ -63,7 +65,7 @@ def main():
try:
logging.info( "OpenSnitch v%s running with pid %d." % ( VERSION, os.getpid() ) )
snitch.start()
except KeyboardInterrupt, e:
except KeyboardInterrupt as e:
pass
logging.info( "Quitting ..." )

View file

@ -17,7 +17,7 @@
# or write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from opensnitch.proc import get_pid_by_connection
from opensnitch.app import Application
from opensnitch.app import Application
from dpkt import ip
from socket import inet_ntoa, getservbyport
@ -47,7 +47,7 @@ class Connection:
self.service = getservbyport( int(self.dst_port), self.proto )
except:
self.service = None
self.pid, self.app_path = get_pid_by_connection( procmon,
self.src_addr,
self.src_port,
@ -56,7 +56,7 @@ class Connection:
self.proto )
self.app = Application( procmon, self.pid, self.app_path )
self.app_path = self.app.path
def get_app_name(self):
if self.app_path == 'Unknown':
return self.app_path
@ -69,13 +69,16 @@ class Connection:
def get_app_name_and_cmdline(self):
if self.app.cmdline is not None:
if self.app.cmdline.startswith( self.app.path ):
return self.app.cmdline
# TODO: Figure out why we get mixed types here
cmdline = self.app.cmdline if isinstance(self.app.cmdline, str) else self.app.cmdline.decode()
path = self.app.path if isinstance(self.app.path, str) else self.app.path.decode()
if cmdline.startswith(self.app.path):
return cmdline
else:
return "%s %s" % ( self.app.path, self.app.cmdline )
return "%s %s" % (path, cmdline)
else:
return self.app.path
return path
def __repr__(self):
return "[%s] %s (%s) -> %s:%s" % ( self.pid, self.app_path, self.proto, self.dst_addr, self.dst_port )

View file

@ -42,19 +42,19 @@ class DNSCollector:
address = packet[0][i].rdata
i -= 1
if hostname == '.':
if hostname == b'.':
continue
elif hostname.endswith('.'):
elif hostname.endswith(b'.'):
hostname = hostname[:-1]
# for CNAME records
if address.endswith('.'):
address = address[:-1]
logging.debug( "Adding DNS response: %s => %s" % ( address, hostname ) )
self.hosts[address] = hostname
except Exception, e:
logging.debug("Adding DNS response: %s => %s" % (address, hostname))
self.hosts[address] = hostname.decode()
except Exception as e:
logging.debug("Error while parsing DNS response: %s" % e)
def get_hostname( self, address ):

View file

@ -118,39 +118,39 @@ class ProcMon(threading.Thread):
logging.info( "ProcMon running ..." )
self.running = True
with open("/sys/kernel/debug/tracing/trace_pipe") as pipe:
with open("/sys/kernel/debug/tracing/trace_pipe", 'rb') as pipe:
while True:
try:
line = pipe.readline()
if ProcMon.PROBE_NAME in line:
m = re.search(r'^.*?\-(\d+)\s*\[', line)
if ProcMon.PROBE_NAME.encode() in line:
m = re.search(b'^.*?\-(\d+)\s*\[', line)
if m is not None:
pid = int(m.group(1))
#"walk" over every argument field, 'fault' is our terminator.
# If we see it it means that there are more cmdline args.
if '(fault)' in line:
line = line[:line.find('(fault)')]
if b'(fault)' in line:
line = line[:line.find(b'(fault)')]
args = ' '.join(re.findall(r'arg\d+="(.*?)"', line))
args = b' '.join(re.findall(b'arg\d+="(.*?)"', line))
self._on_args( pid, args )
self._on_args( pid, args.decode() )
else:
m = re.search(r'sched_process_(.*?):', line)
m = re.search(b'sched_process_(.*?):', line)
if m is not None:
event = m.group(1)
if event == 'exec':
filename = re.search(r'filename=(.*?)\s+pid=', line).group(1)
pid = int(re.search(r'\spid=(\d+)', line).group(1))
if event == b'exec':
filename = re.search(b'filename=(.*?)\s+pid=', line).group(1)
pid = int(re.search(b'\spid=(\d+)', line).group(1))
self._on_exec( pid, filename )
self._on_exec( pid, filename.decode() )
elif event == 'exit':
mm = re.search(r'\scomm=(.*?)\s+pid=(\d+)', line)
command = mm.group(1)
elif event == b'exit':
mm = re.search(b'\scomm=(.*?)\s+pid=(\d+)', line)
# command = mm.group(1)
pid = int(mm.group(2))
self._on_exit( pid )

View file

@ -36,7 +36,7 @@ class Rule:
self.address = address
self.port = port
self.proto = proto
def matches( self, c ):
if self.app_path != c.app_path:
return False
@ -100,7 +100,7 @@ class Rules:
class RulesDB:
def __init__(self):
if os.environ.has_key('SUDO_USER'):
if 'SUDO_USER' in os.environ:
self.home = expanduser("~%s" % os.environ['SUDO_USER'] )
else:
self.home = expanduser("~%s" % os.environ['USER'] )
@ -129,4 +129,3 @@ class RulesDB:
c = self.conn.cursor()
c.execute("DELETE FROM rules WHERE app_path=?", (app_path,))
self.conn.commit()

View file

@ -52,8 +52,8 @@ class Snitch:
verdict = self.rules.get_verdict(c)
if verdict is None:
with self.lock:
c.hostname = self.dns.get_hostname(c.dst_addr)
with self.lock:
c.hostname = self.dns.get_hostname(c.dst_addr)
( save_option, verdict, apply_for_all ) = self.qt_app.prompt_user(c)
if save_option != Rule.ONCE:
self.rules.add_rule( c, verdict, apply_for_all, save_option )
@ -81,7 +81,7 @@ class Snitch:
else:
verd = self.get_verdict( conn )
except Exception, e:
except Exception as e:
logging.exception( "Exception on packet callback:" )
if verd == Rule.DROP: