proxy - HAProxy: Take the middle IP from X-Forwarded-For into a new header -


in haproxy.cfg i'm trying extract proper ip address x-forwarded-for header new custom header.

my input request header like

x-forwarded-for: 1.2.3.4, 2.3.4.5, 3.4.5.6

and expected new header like:

x-custom-ip: 2.3.4.5

thanks

original answer:

you can use field sample-fetcher transformation keyword: https://cbonte.github.io/haproxy-dconv/configuration-1.6.html#7.3.1-field

since there's no way count fields in current haproxy, i'd write several simple acls regexp on x-forwarded-for header detect 0, 1, 2, 3, 4, 5 different ips (or actually, comma separator) , based on that, select proper field put in x-custom-ip.

e.g. (not tested)

acl x_forwarded_for_1_ips hdr(x-forwarded-for) -i (?:[0-9]{1,3}\.){3}[0-9]{1,3} acl x_forwarded_for_2_ips hdr(x-forwarded-for) -i ((?:[0-9]{1,3}\.){3}[0-9]{1,3},){1}(?:[0-9]{1,3}\.){3}[0-9]{1,3} acl x_forwarded_for_3_ips hdr(x-forwarded-for) -i ((?:[0-9]{1,3}\.){3}[0-9]{1,3},){2}(?:[0-9]{1,3}\.){3}[0-9]{1,3} acl x_forwarded_for_4_ips hdr(x-forwarded-for) -i ((?:[0-9]{1,3}\.){3}[0-9]{1,3},){3}(?:[0-9]{1,3}\.){3}[0-9]{1,3} acl x_forwarded_for_5_ips hdr(x-forwarded-for) -i ((?:[0-9]{1,3}\.){3}[0-9]{1,3},){4}(?:[0-9]{1,3}\.){3}[0-9]{1,3}  http-request add-header x-custom-ip %[hdr(x-forwarded-for)] if x_forwarded_for_1_ips http-request add-header x-custom-ip %[hdr(x-forwarded-for),field(2,\,)] if x_forwarded_for_2_ips http-request add-header x-custom-ip %[hdr(x-forwarded-for),field(2,\,)] if x_forwarded_for_3_ips http-request add-header x-custom-ip %[hdr(x-forwarded-for),field(3,\,)] if x_forwarded_for_4_ips http-request add-header x-custom-ip %[hdr(x-forwarded-for),field(3,\,)] if x_forwarded_for_5_ips 

let me know if works you, or found different better solution :)


edit: funny, didn't take 5 minutes me find better solution.

use hdr_ip sample-fetcher: https://cbonte.github.io/haproxy-dconv/configuration-1.5.html#7.3.6-hdr_ip

you'd still need acls count ips, can use hdr_ip(x-forwarded-for,2) , hdr_ip(x-forwarded-for,3) directly, no need field().


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -