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

[Python] Cmd line parameter to log proxied clients #351

Closed
wants to merge 1 commit into from
Closed
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
3 changes: 3 additions & 0 deletions websockify/websocketproxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,9 @@ def websockify_init():
parser.add_option("--log-file", metavar="FILE",
dest="log_file",
help="File where logs will be saved")
parser.add_option("--log-proxied-client", action="store_true",
help="prepends the content of the X-Forwarded-For "
"header (if present) to the immediate client's IP in logs")


(opts, args) = parser.parse_args()
Expand Down
8 changes: 8 additions & 0 deletions websockify/websocketserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from websockify.websocket import WebSocket, WebSocketWantReadError, WebSocketWantWriteError


Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Noise. :)

class WebSocketRequestHandler(BaseHTTPRequestHandler):
"""WebSocket request handler base class.

Expand All @@ -35,6 +36,13 @@ class WebSocketRequestHandler(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
BaseHTTPRequestHandler.__init__(self, request, client_address, server)

def address_string(self, show_proxied=False):
immediate_client = super(WebSocketRequestHandler, self).address_string()
fwd_for = self.headers.get("X-Forwarded-For", None)
if show_proxied and fwd_for:
return "{},{}".format(fwd_for, immediate_client)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This format string isn't compatible with Python 2.6, which is our current baseline.

return immediate_client

def handle_one_request(self):
"""Extended request handler

Expand Down
38 changes: 30 additions & 8 deletions websockify/websockifyserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,24 +88,29 @@ def __init__(self, req, addr, server):
self.daemon = getattr(server, "daemon", False)
self.record = getattr(server, "record", False)
self.run_once = getattr(server, "run_once", False)
self.rec = None
self.rec = None
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More noise

self.handler_id = getattr(server, "handler_id", False)
self.file_only = getattr(server, "file_only", False)
self.traffic = getattr(server, "traffic", False)
self.log_proxied_client = getattr(server, "log_proxied_client", False)

self.logger = getattr(server, "logger", None)
if self.logger is None:
self.logger = WebSockifyServer.get_logger()

WebSocketRequestHandler.__init__(self, req, addr, server)

def log_message(self, format, *args):
self.logger.info("%s - - [%s] %s" % (self.address_string(), self.log_date_time_string(), format % args))

#
# WebSocketRequestHandler logging/output functions
#

def log_message(self, format, *args):
self.logger.info(
"%s - - [%s] %s" % (
self.address_string(show_proxied=self.log_proxied_client),
self.log_date_time_string(),
format % args))

def print_traffic(self, token="."):
""" Show traffic flow mode. """
if self.traffic:
Expand Down Expand Up @@ -216,7 +221,13 @@ def send_ping(self, data=''.encode('ascii')):

def handle_upgrade(self):
# ensure connection is authorized, and determine the target
self.validate_connection()
try:
self.validate_connection()
except WebSockifyServer.EClose as e:
# Add info on remote client and re-raise
if self.log_proxied_client:
e.orig_client = self.address_string(show_proxied=self.log_proxied_client)
raise

WebSocketRequestHandler.handle_upgrade(self)

Expand Down Expand Up @@ -332,7 +343,8 @@ def __init__(self, RequestHandlerClass, listen_fd=None,
file_only=False,
run_once=False, timeout=0, idle_timeout=0, traffic=False,
tcp_keepalive=True, tcp_keepcnt=None, tcp_keepidle=None,
tcp_keepintvl=None):
tcp_keepintvl=None,
log_proxied_client=False):

# settings
self.RequestHandlerClass = RequestHandlerClass
Expand Down Expand Up @@ -361,6 +373,8 @@ def __init__(self, RequestHandlerClass, listen_fd=None,
self.tcp_keepidle = tcp_keepidle
self.tcp_keepintvl = tcp_keepintvl

self.log_proxied_client = log_proxied_client

# keyfile path must be None if not specified
self.key = None

Expand Down Expand Up @@ -411,6 +425,8 @@ def __init__(self, RequestHandlerClass, listen_fd=None,
self.msg(" - Backgrounding (daemon)")
if self.record:
self.msg(" - Recording to '%s.*'", self.record)
if self.log_proxied_client:
self.msg(" - Logging IP of intermediate proxies")

#
# WebSockifyServer static methods
Expand Down Expand Up @@ -671,11 +687,17 @@ def top_new_client(self, startsock, address):
try:
try:
client = self.do_handshake(startsock, address)
except self.EClose:
except self.EClose as e:
_, exc, _ = sys.exc_info()
# Connection was not a WebSockets connection
if exc.args[0]:
self.msg("%s: %s" % (address[0], exc.args[0]))
orig_client = getattr(e, 'orig_client', None)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we should start piggy-backing extra information on the exception object. Better to add this information to the connection object somewhere.

if orig_client:
# this allowes to log IP of possibly
# proxied clients
self.msg("%s: %s" % (orig_client, exc.args[0]))
else:
self.msg("%s: %s" % (address[0], exc.args[0]))
except WebSockifyServer.Terminate:
raise
except Exception:
Expand Down