Compare commits

...

13 commits

Author SHA1 Message Date
2186d32e60 update README 2023-07-20 11:17:53 +02:00
2d95669928 feat(log): separate sensitive logs
- Adds the --log-sensitive option.
- Tag with [SENSITIVE] in the logs.
- Avoid formatting within logging calls.
2023-07-20 11:11:14 +02:00
550b884367 Merge branch 'master' of nojhan.github:nojhan/tunnelmon 2023-01-10 11:32:17 +01:00
8da6025673 fix cmd parsing
Was crashing when cmd was not an iterable.
2023-01-10 11:30:47 +01:00
5efc386485
fix(doc) Mention some dependencies in the readme
Fix #4
2022-08-19 15:53:42 +02:00
1f8304c0a5 Merge branch 'master' of github.com:nojhan/tunnelmon 2022-08-09 11:33:54 +02:00
2ac2d0d957 update documentation
- update changelog to prepare 1.1
- add missing author
- more info in README
- screenshot
2022-08-09 11:33:08 +02:00
19f676ef0f
Update issue templates 2022-08-09 11:32:36 +02:00
23d83914f8 feat: colors by types
- hide cursor
- same headers in CLI and TUI
2022-08-09 11:20:48 +02:00
346cd17527 feat: show port forwarding types 2022-08-09 09:31:47 +02:00
d517abb6e4 fix issue #2: detect remote an dynamic port forwarding
Not just local port forwarding.
2022-08-08 09:30:52 +02:00
5bfa5ea55a fix(doc): remove former name 2022-08-08 09:30:27 +02:00
64064c7ffc
fix(readme) typo 2022-08-05 13:41:44 +02:00
7 changed files with 306 additions and 102 deletions

38
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View file

@ -0,0 +1,38 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

View file

@ -4,3 +4,8 @@ E:nojhan@nojhan.net
D:2009-06-23 D:2009-06-23
C:Initial code, lead developper C:Initial code, lead developper
N:Ghislain Picard
P:ghislainp
E:ghislain.picard@univ-grenoble-alpes.fr
D:2021-01-22
C:Fixes on tunnels detection

View file

@ -1,24 +0,0 @@
0.5:
* python3
* complete rewrite for portability
* handle autossh tunnels *and* raw ssh tunnels
* better formatting
0.4:
* adds IPv6 support
* bugfixes
0.3:
* added a via_host field (show on which host the tunnel is build)
* don't try to show connections if the user is not root
0.2:
* update from the deprecated popen3 functions to the subprocess module (need python >= 2.4)
* html help page
0.1:
* command line interface
* curses interface
* list of active autossh instances
* associated active ssh connections

34
CHANGELOG.md Normal file
View file

@ -0,0 +1,34 @@
1.1: "Ñìrikarñar"
- handle local, remote and dynamic port forwading tunnels,
- different colors for different types.
1.0: "Ereshkigal"
- python 3.8,
- fix tunnels detection,
- fix logging,
- code formating.
0.5:
- python3,
- complete rewrite for portability,
- handle autossh tunnels *and* raw ssh tunnels,
- better formatting.
0.4:
- adds IPv6 support,
- bugfixes.
0.3:
- added a via_host field (show on which host the tunnel is build),
- don't try to show connections if the user is not root.
0.2:
- update from the deprecated popen3 functions to the subprocess module (need python >= 2.4),
- html help page.
0.1:
- command line interface,
- curses interface,
- list of active autossh instances,
- associated active ssh connections.

View file

@ -5,23 +5,27 @@ tunnelmon -- Monitor and manage autoSSH tunnels
`tunnelmon` [-h] `tunnelmon` [-h]
`tunnelmon` [-c] [-n] [-u] [-l LEVEL] [-g FILE] `tunnelmon` [-c] [-n] [-u] [-l LEVEL] [-g FILE] [-s]
## DESCRIPTION ## DESCRIPTION
`tunnelmon` is an autossh tunnel monitor. It gives a user interface to monitor existing SSH tunnel that are managed with autossh. `tunnelmon` is an autossh tunnel monitor. It gives a user interface to monitor existing SSH tunnel, and tunnels managed with autossh.
It can print the current state of your tunnels or display them in an interactive text-based interface. It can print the current state of your tunnels or display them in an interactive text-based interface.
`tunnelmon` is released under the GNU Public License v3. `tunnelmon` is released under the GNU Public License v3.
![Screenshot](https://raw.github.com/nojhan/tunnelmon/master/screenshot.png)
## INSTALLATION ## INSTALLATION
`tunnelmon` targets Linux operating systems, and depends on: `tunnelmon` targets Linux operating systems, and depends on:
* `openssh-client` * `openssh-client`,
* `python` version 3.8 at least. * `python` version 3.8 at least, you may also need to install the following python modules (for example via `pip`, but you may use any other package management system going along with your installation):
* `psutils`
* `curses`
You may also want to install the recommend packages: You may also want to install the recommend packages:
* `autossh` * `autossh`
@ -51,6 +55,9 @@ Called without option,`tunnelmon` will print the current state of the autossh tu
Log messages are written to the given FILE. Useful to debug the interactive interface. Log messages are written to the given FILE. Useful to debug the interactive interface.
If not set, asking for the curses interface automatically set logging to the "tunnelmon.log" file. If not set, asking for the curses interface automatically set logging to the "tunnelmon.log" file.
* `-s`, `--log-sensitive`:
Allow sensitive information (hostnames, IPs, PIDs, etc.) into the logs.
## INTERACTIVE INTERFACE ## INTERACTIVE INTERFACE
@ -60,7 +67,31 @@ Keyboard commands:
* `R`: Reload the selected autossh instance (i.e. send a `SIGUSR1`, which is interpreted as a reload command by autossh). * `R`: Reload the selected autossh instance (i.e. send a `SIGUSR1`, which is interpreted as a reload command by autossh).
* `C`: Close the selected tunnel (i.e. send a `SIGTERM`). * `C`: Close the selected tunnel (i.e. send a `SIGTERM`).
* `N`: Show the network connections related to each tunnel instances. * `N`: Show the network connections related to each tunnel instances.
* `Q`: Quit tunnelmon. * `Q`: Quit Tunnelmon.
## DISPLAY
Tunnelmon displays a table where lines are [auto]ssh processes that sets up a tunnel.
Columns of the table indicates:
- TYPE: `auto` if the process is managed by autossh, `ssh` if it is a "raw" SSH tunnel;
- FORWARD: the type of port forwarding method (either `local`, `remote` or `dynamic`, see the SSH manual for details);
- SSHPID: the process identifier;
- INPORT: the client port;
- VIA: the client host;
- TARGET: the host address;
- OUTPORT: the host port.
The interactive interface adds a CONNECTIONS columns that displays one vertical bar for each connection set up by the tunnel.
If you ask for showing the connections list (typing `N` in the interactive interface, or not passing `-u` to the command line one),
Tunnelmon will show indented lines with the type of the connection, its status and the related address:port informations.
In the interactive interface, different colors are used for:
- the tunnel type,
- the port forwarding methods,
- privileged and unprivileged ports,
- loopback, private and regular addresses.
## SSH Tunnels in a nutshell ## SSH Tunnels in a nutshell
@ -72,6 +103,7 @@ ssh -N host -L4567:server:1234
You may add `-f` to run ssh in the background. You may add `-f` to run ssh in the background.
Autossh can restart tunnels for you, in case they crash: Autossh can restart tunnels for you, in case they crash:
̏``` ```
autossh -f host -L4567:server:1234 autossh -f host -L4567:server:1234
``` ```

BIN
screenshot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View file

@ -1,7 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# #
# Ereshkigal is an AutoSSH tunnel monitor # Tunnelmon is an AutoSSH tunnel monitor
# It gives a curses user interface to monitor existing SSH tunnel that are managed with autossh. # It gives a curses user interface to monitor existing SSH tunnel that are managed with autossh.
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
@ -36,9 +36,10 @@ import re
import collections import collections
import itertools import itertools
log_sensitive = False
class Tunnel: class Tunnel:
def __init__(self, ssh_pid=None, in_port=None, via_host=None, target_host=None, out_port=None): def __init__(self, ssh_pid=None, in_port=None, via_host=None, target_host=None, out_port=None, forward=None):
# assert ssh_pid is not None # assert ssh_pid is not None
self.ssh_pid = ssh_pid self.ssh_pid = ssh_pid
assert in_port is not None assert in_port is not None
@ -49,11 +50,18 @@ class Tunnel:
self.target_host = target_host self.target_host = target_host
assert out_port is not None assert out_port is not None
self.out_port = out_port self.out_port = out_port
assert forward is not None
self.forwards = {'L':'local', 'R':'remote', 'D': 'dynamic'}
if forward in self.forwards:
self.forward = self.forwards[forward]
else:
self.forward = "unknown"
self.connections = [] self.connections = []
def repr_tunnel(self): def repr_tunnel(self):
return "%i\t%i\t%s\t%s\t%i" % ( return "%s\t%i\t%i\t%s\t%s\t%i" % (
self.forward,
self.ssh_pid, self.ssh_pid,
self.in_port, self.in_port,
self.via_host, self.via_host,
@ -146,25 +154,31 @@ class TunnelsParser:
# only a list of connections OR autossh processes # only a list of connections OR autossh processes
# self.update() # self.update()
self.re_forwarding = re.compile(r"-L\s*(\d+):(.*):(\d+)") self.re_forwarding = re.compile(r"-\w*([LRD])\w*\s*(\d+):(.*):(\d+)")
self.header = 'TYPE\tSSH_PID\tIN_PORT\tVIA_HOST\tTARGET_HOST\tOUT_PORT' self.header = 'TYPE\tFORWARD\tSSHPID\tINPORT\tVIA\tTARGET\tOUTPORT'
def get_tunnel(self, pos): def get_tunnel(self, pos):
pid = list(self.tunnels.keys())[pos] pid = list(self.tunnels.keys())[pos]
return self.tunnels[pid] return self.tunnels[pid]
def parse(self, cmd): def parse(self, cmd):
cmdline = " ".join(cmd) try:
cmdline = " ".join(cmd)
except TypeError:
cmdline = cmd
logging.debug('autossh cmd line: %s', cmdline) if log_sensitive:
logging.debug('forwarding regexp: %s', self.re_forwarding) logging.debug("[SENSITIVE] autossh cmd line: %s", cmdline)
logging.debug("forwarding regexp: %s" % self.re_forwarding)
match = self.re_forwarding.findall(cmdline) match = self.re_forwarding.findall(cmdline)
logging.debug(match) if log_sensitive:
logging.debug("[SENSITIVE] match: %s", match)
if match: if match:
assert len(match) == 1 assert len(match) == 1
in_port, target_host, out_port = match[0] forward, in_port, target_host, out_port = match[0]
logging.debug("matches: %s", match) if log_sensitive:
logging.debug("[SENSITIVE] matches: %s", match)
else: else:
raise ValueError("is not a ssh tunnel") raise ValueError("is not a ssh tunnel")
@ -174,7 +188,8 @@ class TunnelsParser:
# FIXME this is an ugly hack # FIXME this is an ugly hack
i = 1 i = 1
while i < len(cmd): while i < len(cmd):
logging.debug("ici: %i %s", i, cmd[i]) if log_sensitive:
logging.debug("[SENSITIVE] here: %i %s", i, cmd[i])
if cmd[i][0] == '-': if cmd[i][0] == '-':
if cmd[i][1] in '46AaCfGgKkMNnqsTtVvXxYy': if cmd[i][1] in '46AaCfGgKkMNnqsTtVvXxYy':
# flag without argument # flag without argument
@ -188,7 +203,7 @@ class TunnelsParser:
via_host = cmd[i] via_host = cmd[i]
break break
return int(in_port), via_host, target_host, int(out_port) return int(in_port), via_host, target_host, int(out_port), forward
def update(self): def update(self):
"""Gather and parse informations from the operating system""" """Gather and parse informations from the operating system"""
@ -204,36 +219,41 @@ class TunnelsParser:
pass pass
else: else:
if process['name'] == 'ssh': if process['name'] == 'ssh':
logging.debug(process) if log_sensitive:
logging.debug("[SENSITIVE] process: %s ", process)
try: try:
in_port, via_host, target_host, out_port = self.parse(cmd) in_port, via_host, target_host, out_port, forward = self.parse(cmd)
except ValueError: except ValueError:
continue continue
logging.debug("%s %s %s %s", in_port, via_host, target_host, out_port) if log_sensitive:
logging.debug("[SENSITIVE] parsed: %s %s %s %s %s", in_port, via_host, target_host, out_port, forward)
# Check if this ssh tunnel is managed by autossh. # Check if this ssh tunnel is managed by autossh.
parent = psutil.Process(process['ppid']) parent = psutil.Process(process['ppid'])
if parent.name() == 'autossh': if parent.name() == 'autossh':
# Add an autossh tunnel. # Add an autossh tunnel.
pid = parent.pid # autossh pid pid = parent.pid # autossh pid
self.tunnels[pid] = AutoTunnel(pid, process['pid'], in_port, via_host, target_host, out_port) self.tunnels[pid] = AutoTunnel(pid, process['pid'], in_port, via_host, target_host, out_port, forward)
else: else:
# Add a raw tunnel. # Add a raw tunnel.
pid = process['pid'] pid = process['pid']
self.tunnels[pid] = RawTunnel(pid, in_port, via_host, target_host, out_port) self.tunnels[pid] = RawTunnel(pid, in_port, via_host, target_host, out_port, forward)
for c in process['connections']: for c in process['connections']:
logging.debug(c) if log_sensitive:
logging.debug("[SENSITIVE] connection: %s", c)
laddr, lport = c.laddr laddr, lport = c.laddr
if c.raddr: if c.raddr:
raddr, rport = c.raddr raddr, rport = c.raddr
else: else:
raddr, rport = (None, None) raddr, rport = (None, None)
connection = Connection(laddr, lport, raddr, rport, c.status, c.family) connection = Connection(laddr, lport, raddr, rport, c.status, c.family)
logging.debug(connection) if log_sensitive:
logging.debug("[SENSITIVE] connection: %s", connection)
self.tunnels[pid].connections.append(connection) self.tunnels[pid].connections.append(connection)
logging.debug(self.tunnels) if log_sensitive:
logging.debug("[SENSITIVE] %s", self.tunnels)
def __repr__(self): def __repr__(self):
reps = [self.header] reps = [self.header]
@ -251,6 +271,9 @@ class CursesMonitor:
"""Textual user interface to display up-to-date informations about current tunnels""" """Textual user interface to display up-to-date informations about current tunnels"""
def __init__(self, scr): def __init__(self, scr):
# hide cursor
curses.curs_set(0)
# curses screen # curses screen
self.scr = scr self.scr = scr
@ -271,26 +294,74 @@ class CursesMonitor:
self.ui_delay = 0.05 # seconds between two screen update self.ui_delay = 0.05 # seconds between two screen update
# colors # colors
# FIXME different colors for different types of tunnels (auto or raw) # 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white.
self.colors_tunnel = {'kind_auto': 4, 'kind_raw': 5, 'ssh_pid': 0, 'in_port': 3, self.colors_tunnel = {
'via_host': 2, 'target_host': 2, 'out_port': 3, 'tunnels_nb': 4, 'tunnels_nb_none': 1} 'kind_auto' : curses.COLOR_CYAN,
self.colors_highlight = {'kind_auto': 9, 'kind_raw': 9, 'ssh_pid': 9, 'in_port': 9, 'kind_raw' : curses.COLOR_BLUE,
'via_host': 9, 'target_host': 9, 'out_port': 9, 'tunnels_nb': 9, 'tunnels_nb_none': 9} 'ssh_pid' : curses.COLOR_WHITE,
self.colors_connection = {'ssh_pid': 0, 'autossh_pid': 0, 'status': 4, 'status_out': 1, 'in_port' : curses.COLOR_YELLOW,
'local_address': 2, 'in_port': 3, 'foreign_address': 2, 'out_port': 3} 'out_port' : curses.COLOR_YELLOW,
'in_port_priv' : curses.COLOR_RED,
'out_port_priv' : curses.COLOR_RED,
'via_host' : curses.COLOR_GREEN,
'target_host' : curses.COLOR_GREEN,
'via_local' : curses.COLOR_BLUE,
'target_local' : curses.COLOR_BLUE,
'via_priv' : curses.COLOR_CYAN,
'target_priv' : curses.COLOR_CYAN,
'tunnels_nb' : curses.COLOR_RED,
'tunnels_nb_none': curses.COLOR_RED,
'forward_local' : curses.COLOR_BLUE,
'forward_remote' : curses.COLOR_CYAN,
'forward_dynamic': curses.COLOR_YELLOW,
'forward_unknown': curses.COLOR_WHITE,
}
self.colors_highlight = {
'kind_auto' : 9,
'kind_raw' : 9,
'ssh_pid' : 9,
'in_port' : 9,
'out_port' : 9,
'in_port_priv' : 9,
'out_port_priv' : 9,
'via_host' : 9,
'target_host' : 9,
'via_local' : 9,
'target_local' : 9,
'via_priv' : 9,
'target_priv' : 9,
'tunnels_nb' : 9,
'tunnels_nb_none': 9,
'forward_local' : 9,
'forward_remote' : 9,
'forward_dynamic': 9,
'forward_unknown': 9,
}
self.colors_connection = {
'ssh_pid' : curses.COLOR_WHITE,
'autossh_pid' : curses.COLOR_WHITE,
'status' : curses.COLOR_CYAN,
'status_out' : curses.COLOR_RED,
'local_address' : curses.COLOR_BLUE,
'foreign_address': curses.COLOR_GREEN,
'in_port' : curses.COLOR_YELLOW,
'out_port' : curses.COLOR_YELLOW,
'in_port_priv' : curses.COLOR_RED,
'out_port_priv' : curses.COLOR_RED,
}
self.header = ("TYPE", "SSHPID", "INPORT", "VIA", "TARGET", "OUTPORT") self.header = ("TYPE", "FORWARD", "SSHPID", "INPORT", "VIA", "TARGET", "OUTPORT")
def do_Q(self): def do_Q(self):
"""Quit""" """Quit"""
logging.debug("Waited: %s" % self.log_ticks) logging.debug("Waited: %s", self.log_ticks)
self.log_ticks = "" self.log_ticks = ""
logging.debug("Key pushed: Q") logging.debug("Key pushed: Q")
return False return False
def do_R(self): def do_R(self):
"""Reload autossh tunnel""" """Reload autossh tunnel"""
logging.debug("Waited: %s" % self.log_ticks) logging.debug("Waited: %s", self.log_ticks)
self.log_ticks = "" self.log_ticks = ""
logging.debug("Key pushed: R") logging.debug("Key pushed: R")
# if a pid is selected # if a pid is selected
@ -298,7 +369,8 @@ class CursesMonitor:
# send the SIGUSR1 signal # send the SIGUSR1 signal
if type(self.tp.get_tunnel(self.cur_line)) == AutoTunnel: if type(self.tp.get_tunnel(self.cur_line)) == AutoTunnel:
# autossh performs a reload of existing tunnels that it manages # autossh performs a reload of existing tunnels that it manages
logging.debug("SIGUSR1 on PID: %i" % self.cur_pid) if log_sensitive:
logging.debug("[SENSITIVE] SIGUSR1 on PID: %i", self.cur_pid)
os.kill(self.cur_pid, signal.SIGUSR1) os.kill(self.cur_pid, signal.SIGUSR1)
else: else:
logging.debug("Cannot reload a RAW tunnel") logging.debug("Cannot reload a RAW tunnel")
@ -306,7 +378,7 @@ class CursesMonitor:
def do_C(self): def do_C(self):
"""Close tunnel""" """Close tunnel"""
logging.debug("Waited: %s" % self.log_ticks) logging.debug("Waited: %s", self.log_ticks)
self.log_ticks = "" self.log_ticks = ""
logging.debug("Key pushed: C") logging.debug("Key pushed: C")
if self.cur_pid != -1: if self.cur_pid != -1:
@ -316,17 +388,21 @@ class CursesMonitor:
tunnel = self.tp.get_tunnel(self.cur_line) tunnel = self.tp.get_tunnel(self.cur_line)
if type(tunnel) == AutoTunnel: if type(tunnel) == AutoTunnel:
logging.debug("SIGKILL on autossh PID: %i" % self.cur_pid) if log_sensitive:
logging.debug("[SENSITIVE] SIGKILL on autossh PID: %i", self.cur_pid)
try: try:
os.kill(self.cur_pid, signal.SIGKILL) os.kill(self.cur_pid, signal.SIGKILL)
except OSError: except OSError:
logging.error("No such process: %i" % self.cur_pid) if log_sensitive:
logging.error("[SENSITIVE] No such process: %i", self.cur_pid)
logging.debug("SIGKILL on ssh PID: %i" % tunnel.ssh_pid) if log_sensitive:
logging.debug("[SENSITIVE] SIGKILL on ssh PID: %i", tunnel.ssh_pid)
try: try:
os.kill(tunnel.ssh_pid, signal.SIGKILL) os.kill(tunnel.ssh_pid, signal.SIGKILL)
except OSError: except OSError:
logging.error("No such process: %i" % tunnel.ssh_pid) if log_sensitive:
logging.error("[SENSITIVE] No such process: %i", tunnel.ssh_pid)
self.cur_line -= 1 self.cur_line -= 1
self.cur_pid = -1 self.cur_pid = -1
# FIXME update cur_pid or get rid of it everywhere # FIXME update cur_pid or get rid of it everywhere
@ -334,7 +410,7 @@ class CursesMonitor:
def do_N(self): def do_N(self):
"""Show connections""" """Show connections"""
logging.debug("Waited: %s" % self.log_ticks) logging.debug("Waited: %s", self.log_ticks)
self.log_ticks = "" self.log_ticks = ""
logging.debug("Key pushed: N") logging.debug("Key pushed: N")
self.show_connections = not self.show_connections self.show_connections = not self.show_connections
@ -342,7 +418,7 @@ class CursesMonitor:
def do_258(self): def do_258(self):
"""Move down""" """Move down"""
logging.debug("Waited: %s" % self.log_ticks) logging.debug("Waited: %s", self.log_ticks)
self.log_ticks = "" self.log_ticks = ""
logging.debug("Key pushed: down") logging.debug("Key pushed: down")
# if not the end of the list # if not the end of the list
@ -357,7 +433,7 @@ class CursesMonitor:
def do_259(self): def do_259(self):
"""Move up""" """Move up"""
logging.debug("Waited: %s" % self.log_ticks) logging.debug("Waited: %s", self.log_ticks)
self.log_ticks = "" self.log_ticks = ""
logging.debug("Key pushed: up") logging.debug("Key pushed: up")
if self.cur_line > -1: if self.cur_line > -1:
@ -396,10 +472,11 @@ class CursesMonitor:
state = "%s" % self.tp state = "%s" % self.tp
if state != self.last_state: if state != self.last_state:
logging.debug("Waited: %s" % self.log_ticks) logging.debug("Waited: %s", self.log_ticks)
self.log_ticks = "" self.log_ticks = ""
logging.debug("----- Time of screen update: %s -----" % time.time()) logging.debug("----- Time of screen update: %s -----", time.time())
logging.debug("State of tunnels:\n%s" % self.tp) if log_sensitive:
logging.debug("[SENSITIVE] State of tunnels:\n%s", self.tp)
self.last_state = state self.last_state = state
else: else:
self.log_ticks += "." self.log_ticks += "."
@ -418,12 +495,12 @@ class CursesMonitor:
# Call the do_* handler. # Call the do_* handler.
fch = "do_%s" % ch.capitalize() fch = "do_%s" % ch.capitalize()
fkc = "do_%i" % kc fkc = "do_%i" % kc
logging.debug("key func: %s / %s" % (fch, fkc)) logging.debug("key func: %s / %s", fch, fkc)
if fch in dir(self): if fch in dir(self):
notquit = eval("self."+fch+"()") notquit = eval("self."+fch+"()")
elif fkc in dir(self): elif fkc in dir(self):
notquit = eval("self."+fkc+"()") notquit = eval("self."+fkc+"()")
logging.debug("notquit = %s" % notquit) logging.debug("notquit = %s", notquit)
# update the display # update the display
self.display() self.display()
@ -434,14 +511,15 @@ class CursesMonitor:
# end of the loop # end of the loop
def format(self): def format(self):
"""Prepare formating strings to pad with spaces up to the column header width."""
reps = [self.tp.tunnels[t].repr_tunnel() for t in self.tp.tunnels] reps = [self.tp.tunnels[t].repr_tunnel() for t in self.tp.tunnels]
tuns = [t.split() for t in reps] tuns = [t.split() for t in reps]
tuns.append(self.header) tuns.append(self.header)
cols = itertools.zip_longest(*tuns, fillvalue='') cols = itertools.zip_longest(*tuns, fillvalue='')
widths = [max(len(s) for s in col) for col in cols] widths = [max(len(s) for s in col) for col in cols]
logging.debug(widths) logging.debug("Columns widths: %s", widths)
fmt = ['{{: <{}}}'.format(w) for w in widths] fmt = ['{{: <{}}}'.format(w) for w in widths]
logging.debug(fmt) logging.debug("Columns formats: %s", fmt)
return fmt return fmt
def display(self): def display(self):
@ -477,8 +555,6 @@ class CursesMonitor:
self.cur_pid = -1 self.cur_pid = -1
# header line # header line
# header_msg = "TYPE\tINPORT\tVIA \tTARGET \tOUTPORT"
# if os.geteuid() == 0:
header_msg = " ".join(self.format()).format(*self.header) header_msg = " ".join(self.format()).format(*self.header)
header_msg += " CONNECTIONS" header_msg += " CONNECTIONS"
self.scr.addstr(header_msg, curses.color_pair(color)) self.scr.addstr(header_msg, curses.color_pair(color))
@ -533,24 +609,67 @@ class CursesMonitor:
"""Add line corresponding to the line-th autossh process""" """Add line corresponding to the line-th autossh process"""
self.scr.addstr('\n') self.scr.addstr('\n')
# Handle on the current tunnel object.
t = self.tp.get_tunnel(line)
# Highlight selected line.
colors = self.colors_tunnel colors = self.colors_tunnel
if self.cur_line == line: if self.cur_line == line:
colors = self.colors_highlight colors = self.colors_highlight
# TYPE
if type(self.tp.get_tunnel(line)) == AutoTunnel: if type(self.tp.get_tunnel(line)) == AutoTunnel:
# Format 'auto' using the 0th column format string and the related color..
self.scr.addstr(self.format()[0].format('auto'), curses.color_pair(colors['kind_auto'])) self.scr.addstr(self.format()[0].format('auto'), curses.color_pair(colors['kind_auto']))
# Trailing space.
self.scr.addstr(' ', curses.color_pair(colors['kind_auto'])) self.scr.addstr(' ', curses.color_pair(colors['kind_auto']))
else: else:
self.scr.addstr(self.format()[0].format('ssh'), curses.color_pair(colors['kind_raw'])) self.scr.addstr(self.format()[0].format('ssh'), curses.color_pair(colors['kind_raw']))
self.scr.addstr(' ', curses.color_pair(colors['kind_raw'])) self.scr.addstr(' ', curses.color_pair(colors['kind_raw']))
# self.add_tunnel_info('ssh_pid', line) # FORWARD
self.add_tunnel_info('ssh_pid', line, 1) fwd = t.forward
self.add_tunnel_info('in_port', line, 2) self.scr.addstr(self.format()[1].format(fwd), curses.color_pair(colors['forward_'+fwd]))
self.add_tunnel_info('via_host', line, 3) self.scr.addstr(' ', curses.color_pair(colors['forward_'+fwd]))
self.add_tunnel_info('target_host', line, 4)
self.add_tunnel_info('out_port', line, 5)
# SSHPID
self.add_tunnel_info('ssh_pid' , line, 2)
# INPORT
if t.in_port <= 1024:
self.scr.addstr(self.format()[3].format(t.in_port), curses.color_pair(colors['in_port_priv']))
self.scr.addstr(' ', curses.color_pair(colors['in_port_priv']))
else:
self.add_tunnel_info('in_port' , line, 3)
# VIA
if any(re.match(p,t.via_host) for p in ["^127\..*", "::1", "localhost"]): # loopback
self.scr.addstr(self.format()[4].format(t.via_host), curses.color_pair(colors['via_local']))
self.scr.addstr(' ', curses.color_pair(colors['via_local']))
elif any(re.match(p,t.via_host) for p in ["^10\..*", "^172\.[123][0-9]*\..*", "^192\.0\.0\.[0-9]+", "^192\.168\..*", "64:ff9b:1:.*", "fc00::.*"]): # private network
self.scr.addstr(self.format()[4].format(t.via_host), curses.color_pair(colors['via_priv']))
self.scr.addstr(' ', curses.color_pair(colors['via_priv']))
else:
self.add_tunnel_info('via_host' , line, 4)
# TARGET
if any(re.match(p,t.target_host) for p in ["^127\..*", "::1", "localhost"]): # loopback
self.scr.addstr(self.format()[5].format(t.target_host), curses.color_pair(colors['target_local']))
self.scr.addstr(' ', curses.color_pair(colors['target_local']))
elif any(re.match(p,t.target_host) for p in ["^10\..*", "^172\.[123][0-9]*\..*", "^192\.0\.0\.[0-9]+", "^192\.168\..*", "64:ff9b:1:.*", "fc00::.*"]): # private network
self.scr.addstr(self.format()[5].format(t.target_host), curses.color_pair(colors['target_priv']))
self.scr.addstr(' ', curses.color_pair(colors['target_priv']))
else:
self.add_tunnel_info('target_host' , line, 5)
# OUTPORT
if t.out_port <= 1024:
self.scr.addstr(self.format()[6].format(t.out_port), curses.color_pair(colors['out_port_priv']))
self.scr.addstr(' ', curses.color_pair(colors['out_port_priv']))
else:
self.add_tunnel_info('out_port' , line, 6)
# CONNECTIONS
nb = len(self.tp.get_tunnel(line).connections) nb = len(self.tp.get_tunnel(line).connections)
if nb > 0: if nb > 0:
# for each connection related to this process # for each connection related to this process
@ -593,7 +712,7 @@ if __name__ == "__main__":
usage = """%prog [options] usage = """%prog [options]
A user interface to monitor existing SSH tunnel that are managed with autossh. A user interface to monitor existing SSH tunnel that are managed with autossh.
Called without options, ereshkigal displays a list of tunnels on the standard output. Called without options, Tunnelmon displays a list of tunnels on the standard output.
Note: Users other than root will not see tunnels connections. Note: Users other than root will not see tunnels connections.
Version 0.3""" Version 0.3"""
parser = OptionParser(usage=usage) parser = OptionParser(usage=usage)
@ -621,18 +740,22 @@ if __name__ == "__main__":
help="Log to this file, default to standard output. \ help="Log to this file, default to standard output. \
If you use the curses interface, you may want to set this to actually see logs.") If you use the curses interface, you may want to set this to actually see logs.")
parser.add_option("-s", "--log-sensitive",
action="store_true", default=False,
help="Do log sensitive informations (like hostnames, IPs and PIDs).")
parser.add_option('-f', '--config-file', default=None, metavar='FILE', parser.add_option('-f', '--config-file', default=None, metavar='FILE',
help="Use this configuration file (default: '~/.ereshkigal.conf')") help="Use this configuration file (default: '~/.tunnelmon.conf')")
(asked_for, args) = parser.parse_args() (asked_for, args) = parser.parse_args()
logmsg = "----- Started Ereshkigal -----" logmsg = "----- Started Tunnelmon -----"
if asked_for.log_file: if asked_for.log_file:
logfile = asked_for.log_file logfile = asked_for.log_file
logging.basicConfig(filename=logfile, level=LOG_LEVELS[asked_for.log_level]) logging.basicConfig(filename=logfile, level=LOG_LEVELS[asked_for.log_level])
logging.debug(logmsg) logging.debug(logmsg)
logging.debug("Log in %s" % logfile) logging.debug("Log in %s", logfile)
else: else:
if asked_for.curses: if asked_for.curses:
logging.warning("It's a bad idea to log to stdout while in the curses interface.") logging.warning("It's a bad idea to log to stdout while in the curses interface.")
@ -640,7 +763,11 @@ if __name__ == "__main__":
logging.debug(logmsg) logging.debug(logmsg)
logging.debug("Log to stdout") logging.debug("Log to stdout")
logging.debug("Asked for: %s", asked_for) logging.debug("Asked for: %s" % asked_for)
if asked_for.log_sensitive:
logging.debug("Asked for logging sensitive information.")
log_sensitive = True
# unfortunately, asked_for class has no __len__ method in python 2.4.3 (bug?) # unfortunately, asked_for class has no __len__ method in python 2.4.3 (bug?)
# if len(asked_for) > 1: # if len(asked_for) > 1:
@ -654,7 +781,7 @@ if __name__ == "__main__":
logging.error("'%s' contains no known configuration", asked_for.config_file) logging.error("'%s' contains no known configuration", asked_for.config_file)
else: else:
try: try:
config.read('~/.ereshkigal.conf') config.read('~/.tunnelmon.conf')
except configparser.MissingSectionHeaderError: except configparser.MissingSectionHeaderError:
logging.error("'%s' contains no known configuration", asked_for.config_file) logging.error("'%s' contains no known configuration", asked_for.config_file)
@ -710,7 +837,8 @@ if __name__ == "__main__":
tp = TunnelsParser() tp = TunnelsParser()
tp.update() tp.update()
# do not call update() but only get connections # do not call update() but only get connections
logging.debug("UID: %i.", os.geteuid()) if log_sensitive:
logging.debug("[SENSITIVE] UID: %i", os.geteuid())
# if os.geteuid() == 0: # if os.geteuid() == 0:
for t in tp.tunnels: for t in tp.tunnels:
for c in tp.tunnels[t].connections: for c in tp.tunnels[t].connections:
@ -736,12 +864,3 @@ if __name__ == "__main__":
# call the default __repr__ # call the default __repr__
print(tp) print(tp)
#
# In Mesopotamian mythology, Ereshkigal (lit. "great lady under earth")
# was the goddess of Irkalla, the land of the dead or underworld.
#
# Thus, she knows a lot about tunnels...
#
# http://en.wikipedia.org/wiki/Ereshkigal
#