Get client IP-address

Hi!

I need some starting help for a LUA script to extract a client’s IP-address from an inbound request to check its location. I do not need the IP-address in any of the backends nor in the logs (which is already there).

Background: HAProxy is running on a Linux firewall and already works perfectly as a reverse proxy.

Now, I would like to implement a GeoIP checking against a location database already available on the firewall which offers a LUA interface already.

My haproxy.cfg (shortend):

...
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  httpchk
    option                  http-server-close
    option                  forwardfor except 127.0.0.0/8
    option                  redispatch except 172.0.0.0/8 
...
listen stats # Define a listen section called "stats"
  bind :9000 # Listen on localhost:9000
  mode http
  stats enable  # Enable stats page
...
frontend http_https
    mode http
...
    # https://thisinterestsme.com/x-forwarded-for-spoofing-haproxy/
    #Deprecated: reqidel ^X-Forwarded-For:.*
    http-request del-header ^X-Forwarded-For:.*
   
    bind 172.17.0.2:80
    
    # Bind all available LE certs to ext. IPFire IP address
    bind 172.17.0.2:443 ssl crt /etc/haproxy/certs/ alpn h2,http/1.1

FWIW, the firewall is behind a cable router that redirects all traffic from external to the firewall as an exposed host. So the firewall get’s all client’s IP-addresses, so should HAproxy.

Basically, I need some lines of code to start from. Which coding is necessary to intercept the client’s request and to check against the location database. I do not need any coding for the check itself, but on how to retrieve the IP from the request.

I’m struggling with the register functions of HAProxy. Which one do I need in my case? core.register_service, core.register_action or core.register_fetches? Maybe a different one?

I’ve programming skills in various programming languages, however, LUA is a very specific language. With HAProxy and its LUA interface it not very easy to understand the basic concept behind but I’m still learning. I’ve already read through various documentations, including the one on Introduction to HAProxy Lua programming | HAProxy Lua API and How Lua runs in HAProxy — haproxy-lua 3.0.5 (Wed Sep 25 02:04:10 CEST 2024) 1.0 documentation but those does not make it easier to understand the LUA interface with HAProxy.

I was the same issue to get client IP from request header.

You need to run LUA like below -

-- Import HTTP client module
local http = require("socket.http")
-- local ltn12 = require("ltn12")

local function myfunction(txn)
    my_ip = tostring(txn.f:src())
end

core.register_action("call2", {"http-req" }, myfunction)

Then you can set another custom header like
txn.set_var(txn, "txn.myip", my_ip)

Call LUA from HAProxy at frontend like -
http-request lua.call2

1 Like