FANDOM


HAProxy

  • http://www.haproxy.org/
  • Desc. : a free, very fast and reliable solution offering high availability, load balancing, and proxying for TCP and HTTP-based applications
  • License:
  • Written in:
  • Sources:

References

 
  Proxy ----------- Gateway
             |
             +----- Forward Proxy
             |
             +----- Reverse Proxy ----------- SSL Acceleration Proxy
                                       |
                                       +----- SSL Termination Proxy
                                       |
                                       +----- Load Balancer
  • HAProxy Configuration
config = global + defaults* + frontend* + backend* + listen*

global = process management and security parameters
         + performance tuning parameters
         + debugging parameters
         + user lists
         + peers
         + mailers

Global Parameters

Process management and security parameters
Parameter Description Remarks
cpu-map Specifies CPU sets for process or thread sets Linux 2.6+,
log Adds a global syslog server
log-tag <string> Sets the tag field in the syslog header to this string.
nbproc <number> Creates <number> processes when going daemon default: 1
nbthread <number> Creates <number> threads for each created processes
ulimit-n Sets the maximum number of per-process file-descriptors Recommended not to use this option
ssl-default-bind-options Sets default ssl-options to force on all "bind" lines.
stats socket Binds a UNIX socket to path or a TCPv4/v6 address to address:port.
Performance tuning parameters
Parameter Description Remarks
tune.ssl.cachesize <number> Sets the size of the global SSL session cache, in a number of blocks. default: 20,000
tune.ssl.lifetime <timeout> Sets how long a cached SSL session may remain valid in seconds. default: 300s (5 min)
Access control parameters
Parameter Description Remarks
user <username> [password|insecure-password <password>] [groups <group>,<group>,(...)] Adds user <username> to the current userlist.

Proxy Keywords

General
Keywords Description DF/FE/LI/BE Remarks
mode { tcp|http|health } Set the running mode or protocol of the instance
monitor-uri <uri> Intercept a URI used by external components' monitor requests O/O/O/X Monitor requests cannot be logged either.
retries <value> Set the number of retries to perform on a server after a connection failure O/X/O/O applies to the number of connection attempts, not full requests
bind [<address>]:<port_range> [, ...] [param*] Define one or several listening addresses and/or ports in a frontend X/O/O/X
tcp-request inspect-delay <timeout> Set the maximum allowed time to wait for data during content inspection
tcp-response content <action> [{if | unless} <condition>] Perform an action on a session response depending on a layer 4-7 condition
option http_proxy Enable or disable plain HTTP proxy mode Forward Proxy
option http-keep-alive Enable or disable HTTP keep-alive from client to server
option httpclose Enable or disable passive HTTP connection closing "Connection: close" header
Deprecated
option forwardfor Enable insertion of the X-Forwarded-For header to requests sent to servers "X-Forwarded-For" header
option socket-stats Enable or disable collecting & providing separate statistics for each socket.
capture request header <name> len <length> Capture and log the last occurrence of the specified request header. X/O/O/X Not for Back-end
use_backend <backend> [{if | unless} <condition>] Switch to a specific backend if/unless an ACL-based condition is matched. X/O/O/X
source <addr>[:<port>] [usesrc ...] Set the source address for outgoing connections
server <name> <address>[:[port]] [param*] Declare a server in a backend
default-server [param*] Change default options for a server in a backend O/X/O/O default-server inter 4s rise 2 fall 3
  • http-request
    • defines a set of rules which apply to layer 7 processing.
Action Description Remarks
http-request allow Stops the evaluation of the rules and lets the request pass the check.
http-request deny Stops the evaluation of the rules and immediately rejects the request.
http-request auth Stops the evaluation of the rules and immediately responds with an HTTP 401 or 407 error code to invite the user to present a valid user name and password
http-request add-header <name> <fmt> Appends an HTTP header field whose name is specified in <name> and whose value is defined by <fmt>
http-request set-header <name> <fmt> the header name is first removed if it existed
http-request del-header <name> removes all HTTP header fields whose name is specified in <name>.
http-request replace-header <name> <match-regex> <replace-fmt>
http-request capture <sample> [ len <length> | id <id> ] Captures sample expression <sample> from the request buffer, and converts it to a string of at most <len> characters.
http-request set-log-level <level> Change the log level of the current request when a certain condition is met. alert | crit | err | warning | notice | info | debug | silent
Timeout
Keywords Description Remarks
timeout connect <timeout> Set the maximum time to wait for a connection attempt to a server to succeed
timeout server <timeout> Set the maximum inactivity time on the server side
timeout client <timeout> Set the maximum inactivity time on the client side
timeout tunnel <timeout> Set the maximum inactivity time on the client and server side for tunnels
timeout server-fin <timeout> Set the inactivity timeout on the server side for half-closed connections
timeout client-fin <timeout> Set the inactivity timeout on the client side for half-closed connections
timeout http-request <timeout> Set the maximum allowed time to wait for a complete HTTP request
timeout http-keep-alive <timeout> Set the maximum allowed time to wait for a new HTTP request to appear
Logging/Tracing
Keywords Description DF/FE/LI/BE Remarks
option httplog Enable logging of HTTP request, session state and timers O/O/O/X Not for Back-end
option dontlognull Enable or disable logging of null connections O/O/O/X
option dontlog-normal Enable or disable logging of normal, successful connections O/O/O/X
option log-health-checks Enable or disable logging of health checks status updates O/X/O/O
log-format Specifies the log format string to use for traffic logs O/O/O/X
log-tag <string> Specifies the log tag to use for all outgoing logs O/O/O/O global log-tag
unique-id-format <string> Generate a unique ID for each request. O/O/O/X unique-id-header
unique-id-header <name> Add a unique ID header in the HTTP request. O/O/O/X X-Unique-ID
Health Check
Keywords Description Remarks
option httpchk <method> <uri> <version> Enable HTTP protocol to check on the servers health
Statistics
Keywords Description DF/FE/LI/BE Remarks
stats enable Enable statistics reporting with default settings O/O/O/O
stats admin { if | unless } <cond> Enable statistics admin level if/unless a condition is matched X/O/O/O
stats auth <user>:<passwd> Enable statistics with authentication and grant access to an account O/O/O/O

Bind Options

Options Description Remarks
ca-ignore-err Sets a comma separated list of errorIDs to ignore during verify at depth > 0
crt-ignore-err Sets a comma separated list of errorIDs to ignore during verify at depth == 0
no-sslv3 Disables support for SSLv3 on any sockets instantiated from the listener when SSL is supported
ssl-min-ver Enforces use of <version> or upper on SSL connections instantiated

from this listener

TLSv1.0 | TLSv1.1 | TLSv1.2 | TLSv1.3
alpn Enables the TLS ALPN extension and advertises the specified protocol list as supported on top of ALPN. ALPN (on Wikipedia)
npn Enables the NPN TLS extension and advertises the specified protocol list as supported on top of NPN.

Server Options

Options Description Remarks
maxconn specifies the maximal number of concurrent connections that will be sent to this server.
check Enables health checks on the server. addr, port, source, inter, rise, fall
inter <delay> Sets the interval between two consecutive health checks to <delay> milliseconds. default: 2000ms
check-ssl Forces encryption of all health checks over SSL, regardless of whether the server uses SSL or not for the normal traffic.
ssl Enables SSL ciphering on outgoing connections to the server.
verify [none|required]

ACL

acl <aclname> <criterion> [flags] [operator] [<value>] ...

acl <aclname> <sample fetch method> [flags] [operator] [<value>] ...
Element Description Remarks
ACL Name (aclname) [-_.:A-Za-z0-9]*
Flags (flags) -i, -f, -m, -n, -M, -u, --
ACL Flags
Flag Description Remarks
-i ignore case during matching of all subsequent patterns.
-m found only check if the requested sample could be found in the stream, but do not compare it against any pattern.
-m bool check the value as a boolean.
-m int match the value as an integer.
-m len match the sample's length as an integer.
-m str exact match
-m sub substring match
-m reg regex match
-m beg prefix match
-m end suffix match

Sample Fetch Methods

Method Type Description Remarks
src ip This is the source IPv4 address of the client of the session
Method Type Description Remarks
req.payload_lv binary Extracts a binary block whose size is specified at <offset1> for <length> bytes
res.payload_lv binary extracts a binary block whose size is specified at <offset1> for <length> bytes, and which starts at <offset2> if specified or just after the length in the response buffer.
req.ssl_hello_type integer Returns an integer value containing the type of the SSL hello message found in the request buffer if the buffer contains data that parse as a complete SSL (v3 or superior) client hello message.
res.ssl_hello_type integer Returns an integer value containing the type of the SSL hello message found in the response buffer if the buffer contains data that parses as a complete SSL (v3 or superior) hello message
Method Type Description Remarks
req.hdr([<name>[,<occ>]]) string Extracts the last occurrence of header <name> in an HTTP request When used from an ACL, all occurrences are iterated over until a match is found
res.hdr([<name>[,<occ>]]) string Extracts the last occurrence of header <name> in an HTTP response.
hdr([<name>[,<occ>]]) string Equivalent to req.hdr() when used on requests, and to res.hdr() when used on responses
http_auth(<userlist>) boolean Returns a boolean indicating whether the authentication data received from the client match a username & password stored in the specified userlist.
http_auth_group(<userlist>) string Returns a string corresponding to the user name found in the authentication data received from the client if both the user name and password are valid according to the specified userlist. ACL derivatives
path string Extracts the request's URL path, which starts at the first slash and ends before the question mark (without the host part).

Logging

  • Log Variable Syntax
flag = "Q" | "E" | "X"
flag-part = "+" | "-", flag
variable = "%", [ "{", flag-part, 2 * [ ",", flag-part ], "}" ], ( field | "[", sample-expr , "]" )
  • Default HTTP Log Format
"%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %CC %CS %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq %hr %hs %{+Q}r"
Log Variables
Variable Name Type Description Remarks
%o special variable apply flags on all next var Q, E, X
%ci client_ip IP
%cp client_port numeric
%ft frontend_name_transport string '~' suffix for SSL
%fi frontend_ip IP
%fp frontend_port
%b backend_name string
%si server_IP IP target address
%Ts timestamp numeric
%Tq Th + Ti + TR numeric total time to get the client request from the accept date or since the emission of the last byte of the previous response HTTP mode only
%Tw Tw numeric total time spent in the queues waiting for a connection slot.
%Tc Tc numeric total time to establish the TCP connection to the server.
%Tr response time numeric server response time HTTP mode only
%Tt Tt numeric total session duration time
%ST status_code numeric
%B bytes_read numeric from server to client
%ts termination_state string
%sq srv_queue numeric
%bq backend_queue numeric
%hr captured_request_headers string default style
%r http_request string HTTP mode only
%rt request_counter numeric
%ID unique-id string Unique ID generated by unique-id-header directive
Flags
Flag Description Remarks
Q quote a string
X hexadecimal representation
E escape characters '"', '\' and ']' in a string with '\' as prefix RFC5424
Timings Events
                 first request               2nd request
      |<-------------------------------->|<-------------- ...
      t         tr                       t    tr ...
   ---|----|----|----|----|----|----|----|----|--
      : Th   Ti   TR   Tw   Tc   Tr   Td : Ti   ...
      :<---- Tq ---->:                   :
      :<-------------- Tt -------------->:
                :<--------- Ta --------->:
Event Name Description Remarks
Th handshakes total time to accept tcp connection and execute handshakes for low level protocols.
Ti idle the idle time before the HTTP request.
TR Request total time to get the client request.
Tq total time to get the client request from the accept date or since the emission of the last byte of the previous response. Th + Ti + TR
Tw waiting total time spent in the queues waiting for a connection slot.
Tc connection total time to establish the TCP connection to the server.
Tr response server response time
Td data the data transmission time Tt - (Th + Ti + TR + Tw + Tc + Tr)
Ta active total active time for the HTTP request
Tt total total session duration time

Monitoring

Metric Types Description Remarks
pxname LFBS proxy name
svname LFBS service name FRONTEND | BACKEND | ...
qcur ..BS current queued requests
qmax ..BS max value of qcur
scur LFBS current sessions
smax LFBS max sessions
slim LFBS configured session limit
stot LFBS cumulative number of sessions

CLI

Option Description Remarks
-D goes daemon
-Ws master-worker mode with systemd notify support
-c only check config files and exit check mode
-V enters verbose mode (disables quiet mode)
-p <pidfile> writes pids of all children to this file
-sf finishes/terminates old pids

Readings

ACL

Proxying

SSL

WebSockets

HTTP/2

Load Balancing

Logging, Tracing and Statistics

Health Check

Throttling

Mapping

Samples

Typical Sample for Reverse Proxy

  1. # References
  2. #   http://cbonte.github.io/haproxy-dconv/1.8/configuration.html#3
  3. #   http://cbonte.github.io/haproxy-dconv/1.8/configuration.html#4
  4. #   https://kvz.io/blog/2010/08/11/haproxy-logging/
  5.  
  6. global
  7.   daemon
  8.   log /var/lib/haproxy/dev/log local0 info
  9.   log /var/lib/haproxy/dev/log local1 notice
  10.  
  11.   ca-base /etc/haproxy/ssl/trusted
  12.   crt-base /etc/haproxy/ssl
  13.  
  14.   # https://disablessl3.com/
  15.   ssl-default-bind-options no-sslv3
  16.  
  17.   # 'stats socket' would generate the specified socket file if not exists
  18.   stats socket /var/run/haproxy.sock mode 660
  19.  
  20.   maxconn 2000
  21.   tune.ssl.default-dh-param 2048
  22.  
  23.  
  24. defaults
  25.   mode http
  26.   monitor-uri /liveness
  27.  
  28.   log global
  29.   option httplog
  30.   option dontlognull
  31.   no option log-health-checks
  32.   # http://cbonte.github.io/haproxy-dconv/1.8/configuration.html#8.2.4
  33.   log-format %ci\ %ft\ %b\ %si\ %Tq/%Tw/%Tc/%Tr/%Tt\ %ST\ %B\ %ts\ %sq/%bq\ %hr\ %{+Q}r
  34.  
  35.   # Add 'X-Forwared-For' header automatically
  36.   option forwardfor
  37.   #option http-server-close
  38.  
  39.   timeout connect 5s
  40.   timeout client 10s
  41.   timeout server 10s
  42.   timeout tunnel 600s
  43.   timeout server-fin 10s
  44.   timeout client-fin 10s
  45.   timeout http-request 5s
  46.   timeout http-keep-alive 2s
  47.  
  48.   errorfile 400 /etc/haproxy/errors/400.http
  49.   errorfile 403 /etc/haproxy/errors/403.http
  50.   errorfile 408 /etc/haproxy/errors/408.http
  51.   errorfile 500 /etc/haproxy/errors/500.http
  52.   errorfile 502 /etc/haproxy/errors/502.http
  53.   errorfile 503 /etc/haproxy/errors/503.http
  54.   errorfile 504 /etc/haproxy/errors/504.http
  55.  
  56.   default-server inter 5s rise 2 fall 3
  57.  
  58.  
  59. listen stats
  60.   bind 192.168.1.11:8070
  61.  
  62.   stats enable
  63.   stats admin if FALSE
  64.   stats auth haproxystat:dontuse1234
  65.   stats hide-version
  66.   stats realm HAProxy\ Statistics
  67.   stats uri /stats
  68.  
  69. frontend http
  70.   bind 192.168.1.11:8080
  71.  
  72.   capture request header Host len 20
  73.   #capture request header Forwarded len 50
  74.   capture request header X-Forwarded-For len 20
  75.  
  76.   http-request set-header X-Forwarded-Host %[req.hdr(Host)]
  77.   http-request set-header X-Forwarded-Proto http
  78.  
  79.   default_backend http-rear
  80.  
  81.  
  82. frontend https
  83.   # http://cbonte.github.io/haproxy-dconv/1.8/configuration.html#5.1-verify
  84.   bind 192.168.1.11:8443 ssl crt server-tls.pem ca-file ca.crt verify none
  85.   # bind 192.168.1.11:8443 ssl crt server-tls.pem ca-file ca.crt verify optional crt-ignore-err all ca-ignore-err all   # For mutual auth
  86.  
  87.   capture request header Host len 20
  88.   #capture request header Forwarded len 50
  89.   capture request header X-Forwarded-For len 20
  90.  
  91.   #http-request deny deny_status 400 unless { ssl_fc }
  92.   #http-request deny deny_status 400 unless { ssl_c_used }
  93.   #http-request deny deny_status 400 unless { ssl_c_verify 0 }
  94.  
  95.   # setup request header for logging or backend usage
  96.   # https://www.haproxy.com/blog/ssl-client-certificate-information-in-http-headers-and-logs/
  97.   http-request set-header X-SSL                  %[ssl_fc]
  98.   http-request set-header X-SSL-Session_ID       %[ssl_fc_session_id,hex]
  99.   http-request set-header X-SSL-Client-Verify    %[ssl_c_verify]    
  100.   http-request set-header X-SSL-Client-DN        %{+Q}[ssl_c_s_dn]
  101.   http-request set-header X-SSL-Client-CN        %{+Q}[ssl_c_s_dn(cn)]
  102.   http-request set-header X-SSL-Issuer           %{+Q}[ssl_c_i_dn]
  103.   http-request set-header X-SSL-Client-NotBefore %{+Q}[ssl_c_notbefore]
  104.   http-request set-header X-SSL-Client-NotAfter  %{+Q}[ssl_c_notafter]
  105.  
  106.   http-request set-header X-Forwarded-Host %[req.hdr(Host)]
  107.   http-request set-header X-Forwarded-Proto http
  108.  
  109.   default_backend http-rear
  110.  
  111.  
  112. frontend ws
  113.   bind 192.168.1.11:8090
  114.  
  115.   capture request header Host len 20
  116.   #capture request header Forwarded len 50
  117.   capture request header X-Forwarded-For len 20
  118.  
  119.   acl is_connection_upgrade hdr(Connection) -i upgrade
  120.   acl is_upgrade_websocket hdr(Upgrade) -i websocket
  121.   acl has_websocket_key hdr_cnt(Sec-WebSocket-Key) eq 1
  122.   acl has_websocket_ver hdr_cnt(Sec-WebSocket-Version) eq 1
  123.  
  124.   http-request deny unless is_connection_upgrade is_upgrade_websocket has_websocket_key has_websocket_ver
  125.  
  126.   http-request set-header X-Forwarded-Host %[req.hdr(Host)]
  127.   http-request set-header X-Forwarded-Proto http
  128.  
  129.   default_backend ws-rear
  130.  
  131.  
  132. frontend wss
  133.   bind 192.168.1.11:8453 ssl crt server-tls.pem ca-file ca.crt verify none
  134.   # bind 192.168.1.11:8453 ssl crt server-tls.pem ca-file ca.crt verify optional crt-ignore-err all ca-ignore-err all   # For mutual auth
  135.  
  136.   capture request header Host len 20
  137.   #capture request header Forwarded len 50
  138.   capture request header X-Forwarded-For len 20
  139.  
  140.   #http-request deny deny_status 400 unless { ssl_fc }
  141.   #http-request deny deny_status 400 unless { ssl_c_used }
  142.   #http-request deny deny_status 400 unless { ssl_c_verify 0 }
  143.  
  144.   acl is_connection_upgrade hdr(Connection) -i upgrade
  145.   acl is_upgrade_websocket hdr(Upgrade) -i websocket
  146.   acl has_websocket_key hdr_cnt(Sec-WebSocket-Key) eq 1
  147.   acl has_websocket_ver hdr_cnt(Sec-WebSocket-Version) eq 1
  148.  
  149.   http-request deny unless is_connection_upgrade is_upgrade_websocket has_websocket_key has_websocket_ver
  150.  
  151.   http-request set-header X-Forwarded-Host %[req.hdr(Host)]
  152.   http-request set-header X-Forwarded-Proto http
  153.  
  154.   default_backend ws-rear
  155.  
  156.  
  157. backend http-rear
  158.   # https://serverfault.com/questions/622567/haproxy-error-some-configuration-options-require-full-privileges-so-global-uid
  159.   #source 0.0.0.0 usesrc clientip
  160.  
  161.   option http-keep-alive
  162.   http-request set-header X-User ...
  163.   http-request set-header Authorization 'Basic ...'
  164.  
  165.   option httpchk POST / HTTP/1.1\r\nHost:\ 127.0.0.1\r\nContent-Length:\ 25\r\nAuthorization:\ Basic\ ...\r\nX-User:\ ...\r\n\r\n
  166.  
  167.   server s1 127.0.0.1:80 check
  168.  
  169.  
  170. backend ws-rear
  171.   # https://serverfault.com/questions/622567/haproxy-error-some-configuration-options-require-full-privileges-so-global-uid
  172.   #source 0.0.0.0 usesrc clientip
  173.  
  174.   option http-keep-alive
  175.   http-request set-header X-User ...
  176.   http-request set-header Authorization 'Basic ...'
  177.  
  178.   server s1 127.0.0.1:90 check

Typical Sample for Forward Proxy

  1. # Sample HAProxy configuration for dedicated forward proxy
  2.  
  3. # References
  4. #    https://stackoverflow.com/questions/49433417/setup-https-forward-proxy-with-haproxy
  5. #    https://serverfault.com/questions/477642/using-haproxy-for-transparent-forwarding-and-selective-redirection
  6.  
  7. global
  8.   daemon
  9.   log /var/lib/haproxy/dev/log local0 info
  10.   log /var/lib/haproxy/dev/log local1 notice
  11.  
  12.   ca-base /etc/haproxy/ssl/trusted
  13.   crt-base /etc/haproxy/ssl
  14.  
  15.   maxconn 2048
  16.   tune.ssl.default-dh-param 2048
  17.   ssl-default-bind-options no-sslv3
  18.  
  19. userlist users
  20.   group regular-users
  21.  
  22.   user tom password ... groups regular-users
  23.  
  24. defaults
  25.   mode http
  26.   log global
  27.  
  28.   timeout connect 5s
  29.   timeout client 10s
  30.   timeout server 10s
  31.   timeout tunnel 600s
  32.   timeout server-fin 10s
  33.   timeout client-fin 10s
  34.   timeout http-request 5s
  35.   timeout http-keep-alive 2s
  36.  
  37.   errorfile 400 /etc/haproxy/errors/400.http
  38.   errorfile 403 /etc/haproxy/errors/403.http
  39.   errorfile 408 /etc/haproxy/errors/408.http
  40.   errorfile 500 /etc/haproxy/errors/500.http
  41.   errorfile 502 /etc/haproxy/errors/502.http
  42.   errorfile 503 /etc/haproxy/errors/503.http
  43.   errorfile 504 /etc/haproxy/errors/504.http
  44.  
  45. listen stats
  46.   bind 192.168.1.11:8070
  47.  
  48.   stats enable
  49.   stats hide-version
  50.   stats realm HAProxy\ Statistics
  51.   stats uri /stats
  52.   stats auth proxyadmin:p8dp8d
  53.  
  54. resolvers dns
  55.   nameserver dns1 8.8.8.8
  56.   nameserver dns2 8.8.4.4
  57.   hold valid 10s
  58.  
  59. frontend http
  60.   bind 192.168.1.11:8080
  61.  
  62.   option http-use-proxy-header
  63.   option httplog
  64.   option dontlognull
  65.   log-format %ci\ [%t]\ %ft\ %b\ %Tq/%Tw/%Tc/%Tr/%Tt\ %ST\ %B\ %ts\ %sq/%bq\ %{+Q}r
  66.  
  67.   acl is-allowed-users http_auth_groups(users) regular-users
  68.   http-request auth unless is-allowed-users   # 407 for unauthorized access
  69.  
  70.   default_backend outside
  71.  
  72. backend outside
  73.  
  74.   option httpclose
  75.   option http_proxy

Log Format and Grok Pattern

Log Format %ci\ %ft\ %b\ %si\ %Tq/%Tw/%Tc/%Tr/%Tt\ %ST\ %B\ %ts\ %sq/%bq\ %hr\ %{+Q}r
Grok Pattern %{IPV4:client_ip} %{NOTSPACE:fe} %{NOTSPACE:be} %{IPV4:server_ip} %{NONNEGINT:tq}/%{NONNEGINT:tw}/%{NONNEGINT:tc}/%{NONNEGINT:tr}/${NONNEGINT:tt} %{POSINT:resp_code} %{NONNEGINT:read_byte} %{NOTSPACE:term_state} %{NOTSPACE:server_q}/%{NOTSPACE:be_q} {%{NOTSPACE:client}(?:|)%{NOTSPACE:host}} %{DATA:req}

Wireshark

References

Operator Symbol Description Remarks
eq == Equal
ne != Not Equal
gt > Greater Than
lt < Less Than
ge >= Greater than or Equal to
le <= Less than or Equal to
contains Does the protocol, field or slice contain a value
matches ~ Does the protocol or text string match the given case-insensitive Perl-compatible regex
[i:j] Slices with i = start_offset, j = length
[i-j] Slices with i = start_offset, j = end_offset, inclusive
[i] Slices with i = start_offset, length = 1
[:j] Slices with start_offset = 0, length = j
[i:] Slices with start_offset = i, end_offset = end_of_field
and && Logical AND
or || Logical OR
not ! Logical NOT
Protocol Typical Fields Description Remarks
tcp port Transmission Control Protocol
ip addr, dst, src Internet Protocol Version 4
http Hypertext Transfer Protocol
ssl Secure Sockets Layer
websocket WebSocket

Readings

Tips and Tricks

Typical display filters

ip.src == 192.168.1.31 and ip.addr == 203.252.150.28 and http

tcpdump

tcpdump [ -AbdDefhHIJKlLnNOpqStuUvxX# ] [ -B buffer_size ] 
 
         [ -c count ] [ -C file_size ] 
         [ -E spi@ipaddr algo:secret,... ] 
         [ -F file ] [ -G rotate_seconds ] [ -i interface ] 
         [ --immediate-mode ] [ -j tstamp_type ] [ -m module ] 
         [ -M secret ] [ --number ] [ --print ] [ -Q in|out|inout ] 
         [ -r file ] [ -s snaplen ] [ -T type ] [ --version ] 
         [ -V file ] [ -w file ] [ -W filecount ] [ -y datalinktype ] 
         [ -z postrotate-command ] [ -Z user ] 
         [ --time-stamp-precision=tstamp_precision ] 
         [ expression ]

Options

Option Description Remarks
-n Don't convert addresses
-i interface Listen on interface
-A Print each packet (minus its link level header) in ASCII Handy for capturing web pages
-s n Snarf n bytes of data from each packet rather than the default of 262144 bytes Setting n to 0 sets it to the default of 262144
-x When parsing and printing, in addition to printing the headers of each packet, print the data of each packet (minus its link level header) in hex

Filter Expression

Primitive Description Remarks
host host True if either the IPv4/v6 source or destination of the packet is host
dst host host True if the IPv4/v6 destination field of the packet is host
src host host True if the IPv4/v6 source field of the packet is host
port port True if either the source or destination port of the packet is port.
dst port port True if the packet is ip/tcp, ip/udp, ip6/tcp or ip6/udp and has a destination port value of port.
src port port True if the packet has a source port value of port.
ip proto protocol True if the packet is an IPv4 packet of protocol type protocol.
tcp = ip proto tcp
Community content is available under CC-BY-SA unless otherwise noted.