Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python3 port #43

Merged
merged 1 commit into from
May 5, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions bin/opensnitch
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python2
#!/usr/bin/env python3
# This file is part of OpenSnitch.
#
# Copyright(c) 2017 Simone Margaritelli
Expand Down Expand Up @@ -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 ...
Expand 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 ..." )
Expand Down
19 changes: 11 additions & 8 deletions opensnitch/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -47,7 +47,7 @@ def __init__( self, procmon, payload ):
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,
Expand All @@ -56,7 +56,7 @@ def __init__( self, procmon, payload ):
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
Expand All @@ -69,13 +69,16 @@ def get_app_name(self):

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 )

10 changes: 5 additions & 5 deletions opensnitch/dns.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,19 @@ def add_response( self, packet ):
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 ):
Expand Down
30 changes: 15 additions & 15 deletions opensnitch/procmon.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,39 +118,39 @@ def run(self):
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 )
Expand Down
5 changes: 2 additions & 3 deletions opensnitch/rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def __init__( self, app_path=None, verdict=ACCEPT, address=None, port=None, prot
self.address = address
self.port = port
self.proto = proto

def matches( self, c ):
if self.app_path != c.app_path:
return False
Expand Down Expand Up @@ -100,7 +100,7 @@ def add_rule( self, connection, verdict, apply_to_all=False, save_option=Rule.UN

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'] )
Expand Down Expand Up @@ -129,4 +129,3 @@ def remove_all_app_rules ( self, app_path ):
c = self.conn.cursor()
c.execute("DELETE FROM rules WHERE app_path=?", (app_path,))
self.conn.commit()

6 changes: 3 additions & 3 deletions opensnitch/snitch.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ def get_verdict(self,c):
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 )
Expand Down Expand Up @@ -81,7 +81,7 @@ def pkt_callback(self,pkt):
else:
verd = self.get_verdict( conn )

except Exception, e:
except Exception as e:
logging.exception( "Exception on packet callback:" )

if verd == Rule.DROP:
Expand Down