From c9cd62507660565ea7189495e98b779f55979f45 Mon Sep 17 00:00:00 2001 From: Gilles Filippini Date: Tue, 2 Mar 2021 08:27:27 +0000 Subject: [PATCH] Honor HTTP header 'X-Real-IP' when available And because X-Real-IP can be spoofed, gate this feature with TRUST_X_REAL_IP environment variable. Fix #5. --- config/prod.exs | 3 ++- lib/tmate/ws_api/websocket.ex | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/config/prod.exs b/config/prod.exs index d2b0323..e116179 100644 --- a/config/prod.exs +++ b/config/prod.exs @@ -26,7 +26,8 @@ config :tmate, :websocket, Keyword.merge(websocket_ranch_opts, cowboy_opts: %{ compress: true, proxy_header: System.get_env("USE_PROXY_PROTOCOL") == "1"}, - base_url: System.get_env("WEBSOCKET_BASE_URL") + base_url: System.get_env("WEBSOCKET_BASE_URL"), + trust_x_real_ip: System.get_env("TRUST_X_REAL_IP") == "1" ) config :tzdata, :autoupdate, :disabled diff --git a/lib/tmate/ws_api/websocket.ex b/lib/tmate/ws_api/websocket.ex index 2d667fd..f4c4d40 100644 --- a/lib/tmate/ws_api/websocket.ex +++ b/lib/tmate/ws_api/websocket.ex @@ -24,8 +24,12 @@ defmodule Tmate.WsApi.WebSocket do {mode, session} -> case Tmate.Session.ws_verify_auth(session) do :ok -> + trust_x_real_ip = Application.get_env(:tmate, :websocket)[:trust_x_real_ip] ip = case req do %{proxy_header: %{src_address: ip}} -> ip + %{headers: %{"x-real-ip" => ipstring}} when trust_x_real_ip -> + {_, ip} = :inet.parse_address(ipstring |> to_charlist) + ip %{peer: {ip, _port}} -> ip end ip = :inet_parse.ntoa(ip) |> to_string