Asciiテーブルメモ

はじめに ネット検索で毎回違うページを探しているので、自分用にまとめる。 man ascii より引用 ascii(7) Miscellaneous Information Manual ascii(7) NAME ascii - ASCII character set encoded in octal, decimal, and hexadecimal DESCRIPTION ASCII is the American Standard Code for Information Interchange. It is a 7-bit code. Many 8-bit codes (e.g., ISO/IEC 8859-1) contain ASCII as their lower half. The international counterpart of ASCII is known as ISO/IEC 646-IRV. The following table contains the 128 ASCII characters. C program '\X' escapes are noted. Oct Dec Hex Char Oct Dec Hex Char ──────────────────────────────────────────────────────────────────────── 000 0 00 NUL '\0' (null character) 100 64 40 @ 001 1 01 SOH (start of heading) 101 65 41 A 002 2 02 STX (start of text) 102 66 42 B 003 3 03 ETX (end of text) 103 67 43 C 004 4 04 EOT (end of transmission) 104 68 44 D 005 5 05 ENQ (enquiry) 105 69 45 E 006 6 06 ACK (acknowledge) 106 70 46 F 007 7 07 BEL '\a' (bell) 107 71 47 G 010 8 08 BS '\b' (backspace) 110 72 48 H 011 9 09 HT '\t' (horizontal tab) 111 73 49 I 012 10 0A LF '\n' (new line) 112 74 4A J 013 11 0B VT '\v' (vertical tab) 113 75 4B K 014 12 0C FF '\f' (form feed) 114 76 4C L 015 13 0D CR '\r' (carriage ret) 115 77 4D M 016 14 0E SO (shift out) 116 78 4E N 017 15 0F SI (shift in) 117 79 4F O 020 16 10 DLE (data link escape) 120 80 50 P 021 17 11 DC1 (device control 1) 121 81 51 Q 022 18 12 DC2 (device control 2) 122 82 52 R 023 19 13 DC3 (device control 3) 123 83 53 S 024 20 14 DC4 (device control 4) 124 84 54 T 025 21 15 NAK (negative ack.) 125 85 55 U 026 22 16 SYN (synchronous idle) 126 86 56 V 027 23 17 ETB (end of trans. blk) 127 87 57 W 030 24 18 CAN (cancel) 130 88 58 X 031 25 19 EM (end of medium) 131 89 59 Y 032 26 1A SUB (substitute) 132 90 5A Z 033 27 1B ESC (escape) 133 91 5B [ 034 28 1C FS (file separator) 134 92 5C \ '\\' 035 29 1D GS (group separator) 135 93 5D ] 036 30 1E RS (record separator) 136 94 5E ^ 037 31 1F US (unit separator) 137 95 5F _ 040 32 20 SPACE 140 96 60 ` 041 33 21 ! 141 97 61 a 042 34 22 " 142 98 62 b 043 35 23 # 143 99 63 c 044 36 24 $ 144 100 64 d 045 37 25 % 145 101 65 e 046 38 26 & 146 102 66 f 047 39 27 ' 147 103 67 g 050 40 28 ( 150 104 68 h 051 41 29 ) 151 105 69 i 052 42 2A * 152 106 6A j 053 43 2B + 153 107 6B k 054 44 2C , 154 108 6C l 055 45 2D - 155 109 6D m 056 46 2E . 156 110 6E n 057 47 2F / 157 111 6F o 060 48 30 0 160 112 70 p 061 49 31 1 161 113 71 q 062 50 32 2 162 114 72 r 063 51 33 3 163 115 73 s 064 52 34 4 164 116 74 t 065 53 35 5 165 117 75 u 066 54 36 6 166 118 76 v 067 55 37 7 167 119 77 w 070 56 38 8 170 120 78 x 071 57 39 9 171 121 79 y 072 58 3A : 172 122 7A z 073 59 3B ; 173 123 7B { 074 60 3C < 174 124 7C | 075 61 3D = 175 125 7D } 076 62 3E > 176 126 7E ~ 077 63 3F ? │ 177 127 7F DEL │ Tables │ For convenience, below are more compact tables in hex and decimal. 2 3 4 5 6 7 30 40 50 60 70 80 90 100 110 120 ------------- --------------------------------- 0: 0 @ P ` p 0: ( 2 < F P Z d n x 1: ! 1 A Q a q 1: ) 3 = G Q [ e o y 2: " 2 B R b r 2: * 4 > H R \ f p z 3: # 3 C S c s 3: ! + 5 ? I S ] g q { 4: $ 4 D T d t 4: " , 6 @ J T ^ h r | 5: % 5 E U e u 5: # - 7 A K U _ i s } 6: & 6 F V f v 6: $ . 8 B L V ` j t ~ 7: ' 7 G W g w 7: % / 9 C M W a k u DEL 8: ( 8 H X h x 8: & 0 : D N X b l v 9: ) 9 I Y i y 9: ' 1 ; E O Y c m w A: * : J Z j z B: + ; K [ k { C: , < L \ l | D: - = M ] m } E: . > N ^ n ~ F: / ? O _ o DEL NOTES History /etc/ascii (VII) appears in the UNIX Programmer's Manual. On older terminals, the underscore code is displayed as a left arrow, called backarrow, the caret is displayed as an up-arrow and the verti‐ cal bar has a hole in the middle. Uppercase and lowercase characters differ by just one bit and the ASCII character 2 differs from the double quote by just one bit, too. That made it much easier to encode characters mechanically or with a non-mi‐ crocontroller-based electronic keyboard and that pairing was found on old teletypes. The ASCII standard was published by the United States of America Stan‐ dards Institute (USASI) in 1968. SEE ALSO charsets(7), iso_8859-1(7), iso_8859-2(7), iso_8859-3(7), iso_8859-4(7), iso_8859-5(7), iso_8859-6(7), iso_8859-7(7), iso_8859-8(7), iso_8859-9(7), iso_8859-10(7), iso_8859-11(7), iso_8859-13(7), iso_8859-14(7), iso_8859-15(7), iso_8859-16(7), utf-8(7) Linux man-pages 6.7 2024-01-28 ascii(7)

March 20, 2025

aptコマンドメモ

はじめに よく忘れるのでメモ man aptより引用 APT(8) APT APT(8) NAME apt - command-line interface SYNOPSIS apt [-h] [-o=config_string] [-c=config_file] [-t=target_release] [-a=architecture] {list | search | show | update | install pkg [{=pkg_version_number | /target_release}]... | remove pkg... | upgrade | full-upgrade | edit-sources | {-v | --version} | {-h | --help}} DESCRIPTION apt provides a high-level commandline interface for the package management system. It is intended as an end user interface and enables some options better suited for interactive usage by default compared to more specialized APT tools like apt-get(8) and apt- cache(8). Much like apt itself, its manpage is intended as an end user interface and as such only mentions the most used commands and options partly to not duplicate information in multiple places and partly to avoid overwhelming readers with a cornucopia of options and details. update (apt-get(8)) update is used to download package information from all configured sources. Other commands operate on this data to e.g. perform package upgrades or search in and display details about all packages available for installation. upgrade (apt-get(8)) upgrade is used to install available upgrades of all packages currently installed on the system from the sources configured via sources.list(5). New packages will be installed if required to satisfy dependencies, but existing packages will never be removed. If an upgrade for a package requires the removal of an installed package the upgrade for this package isn't performed. When a package is supplied as an argument, the package will be installed prior to the upgrade action. full-upgrade (apt-get(8)) full-upgrade performs the function of upgrade but will remove currently installed packages if this is needed to upgrade the system as a whole. When a package is supplied as an argument, the package will be installed prior to the upgrade action. install, reinstall, remove, purge (apt-get(8)) Performs the requested action on one or more packages specified via regex(7), glob(7) or exact match. The requested action can be overridden for specific packages by appending a plus (+) to the package name to install this package or a minus (-) to remove it. A specific version of a package can be selected for installation by following the package name with an equals (=) and the version of the package to select. Alternatively the version from a specific release can be selected by following the package name with a forward slash (/) and codename (bookworm, trixie, sid ...) or suite name (stable, testing, unstable). This will also select versions from this release for dependencies of this package if needed to satisfy the request. Removing a package removes all packaged data, but leaves usually small (modified) user configuration files behind, in case the remove was an accident. Just issuing an installation request for the accidentally removed package will restore its function as before in that case. On the other hand you can get rid of these leftovers by calling purge even on already removed packages. Note that this does not affect any data or configuration stored in your home directory. autoremove (apt-get(8)) autoremove is used to remove packages that were automatically installed to satisfy dependencies for other packages and are now no longer needed as dependencies changed or the package(s) needing them were removed in the meantime. You should check that the list does not include applications you have grown to like even though they were once installed just as a dependency of another package. You can mark such a package as manually installed by using apt-mark(8). Packages which you have installed explicitly via install are also never proposed for automatic removal. satisfy (apt-get(8)) satisfy satisfies dependency strings, as used in Build-Depends. It also handles conflicts, by prefixing an argument with "Conflicts: ". Example: apt satisfy "foo, bar (>= 1.0)" "Conflicts: baz, fuzz" search (apt-cache(8)) search can be used to search for the given regex(7) term(s) in the list of available packages and display matches. This can e.g. be useful if you are looking for packages having a specific feature. If you are looking for a package including a specific file try apt-file(1). show (apt-cache(8)) Show information about the given package(s) including its dependencies, installation and download size, sources the package is available from, the description of the packages content and much more. It can e.g. be helpful to look at this information before allowing apt(8) to remove a package or while searching for new packages to install. list list is somewhat similar to dpkg-query --list in that it can display a list of packages satisfying certain criteria. It supports glob(7) patterns for matching package names, apt-patterns(7), as well as options to list installed (--installed), upgradeable (--upgradeable) or all available (--all-versions) versions. edit-sources (work-in-progress) edit-sources lets you edit your sources.list(5) files in your preferred text editor while also providing basic sanity checks. showsrc, depends, rdepends, policy (summarised in apt-cache(8)) source, build-dep, download, changelog, clean, distclean, autoclean (summarised in apt- get(8)) SCRIPT USAGE AND DIFFERENCES FROM OTHER APT TOOLS The apt(8) commandline is designed as an end-user tool and it may change behavior between versions. While it tries not to break backward compatibility this is not guaranteed either if a change seems beneficial for interactive use. All features of apt(8) are available in dedicated APT tools like apt-get(8) and apt- cache(8) as well. apt(8) just changes the default value of some options (see apt.conf(5) and specifically the Binary scope). So you should prefer using these commands (potentially with some additional options enabled) in your scripts as they keep backward compatibility as much as possible. SEE ALSO apt-get(8), apt-cache(8), sources.list(5), apt.conf(5), apt-config(8), apt-patterns(7), The APT User's guide in /usr/share/doc/apt-doc/, apt_preferences(5), the APT Howto. DIAGNOSTICS apt returns zero on normal operation, decimal 100 on error. BUGS APT bug page[1]. If you wish to report a bug in APT, please see /usr/share/doc/debian/bug-reporting.txt or the reportbug(1) command. AUTHOR APT team NOTES 1. APT bug page https://bugs.debian.org/src:apt APT 2.7.14 12 March 2024 APT(8)

March 13, 2025

nftコマンドメモ

はじめに nftコマンドについてメモ。 man nftより引用 NFT(8) NFT(8) NAME nft - Administration tool of the nftables framework for packet filtering and classification SYNOPSIS nft [ -nNscaeSupyjtT ] [ -I directory ] [ -f filename | -i | cmd ...] nft -h nft -v DESCRIPTION nft is the command line tool used to set up, maintain and inspect packet filtering and classification rules in the Linux kernel, in the nftables framework. The Linux kernel subsystem is known as nf_tables, and ‘nf’ stands for Netfilter. OPTIONS The command accepts several different options which are documented here in groups for better understanding of their meaning. You can get information about options by running nft --help. General options: -h, --help Show help message and all options. -v, --version Show version. -V Show long version information, including compile-time configuration. Ruleset input handling options that specify to how to load rulesets: -f, --file filename Read input from filename. If filename is -, read from stdin. -D, --define name=value Define a variable. You can only combine this option with -f. -i, --interactive Read input from an interactive readline CLI. You can use quit to exit, or use the EOF marker, normally this is CTRL-D. -I, --includepath directory Add the directory directory to the list of directories to be searched for included files. This option may be specified multiple times. -c, --check Check commands validity without actually applying the changes. -o, --optimize Optimize your ruleset. You can combine this option with -c to inspect the proposed optimizations. Ruleset list output formatting that modify the output of the list ruleset command: -a, --handle Show object handles in output. -s, --stateless Omit stateful information of rules and stateful objects. -t, --terse Omit contents of sets from output. -S, --service Translate ports to service names as defined by /etc/services. -N, --reversedns Translate IP address to names via reverse DNS lookup. This may slow down your listing since it generates network traffic. -u, --guid Translate numeric UID/GID to names as defined by /etc/passwd and /etc/group. -n, --numeric Print fully numerical output. -y, --numeric-priority Display base chain priority numerically. -p, --numeric-protocol Display layer 4 protocol numerically. -T, --numeric-time Show time, day and hour values in numeric format. Command output formatting: -e, --echo When inserting items into the ruleset using add, insert or replace commands, print notifications just like nft monitor. -j, --json Format output in JSON. See libnftables-json(5) for a schema description. -d, --debug level Enable debugging output. The debug level can be any of scanner, parser, eval, netlink, mnl, proto-ctx, segtree, all. You can combine more than one by separating by the , symbol, for example -d eval,mnl. INPUT FILE FORMATS LEXICAL CONVENTIONS Input is parsed line-wise. When the last character of a line, just before the newline character, is a non-quoted backslash (\), the next line is treated as a continuation. Multiple commands on the same line can be separated using a semicolon (;). A hash sign (#) begins a comment. All following characters on the same line are ignored. Identifiers begin with an alphabetic character (a-z,A-Z), followed by zero or more alphanumeric characters (a-z,A-Z,0-9) and the characters slash (/), backslash (\), underscore (_) and dot (.). Identifiers using different characters or clashing with a keyword need to be enclosed in double quotes ("). INCLUDE FILES include filename Other files can be included by using the include statement. The directories to be searched for include files can be specified using the -I/--includepath option. You can override this behaviour either by prepending ‘./’ to your path to force inclusion of files located in the current working directory (i.e. relative path) or / for file location expressed as an absolute path. If -I/--includepath is not specified, then nft relies on the default directory that is specified at compile time. You can retrieve this default directory via the -h/--help option. Include statements support the usual shell wildcard symbols (,?,[]). Having no matches for an include statement is not an error, if wildcard symbols are used in the include statement. This allows having potentially empty include directories for statements like include "/etc/firewall/rules/". The wildcard matches are loaded in alphabetical order. Files beginning with dot (.) are not matched by include statements. SYMBOLIC VARIABLES define variable = expr undefine variable redefine variable = expr $variable Symbolic variables can be defined using the define statement. Variable references are expressions and can be used to initialize other variables. The scope of a definition is the current block and all blocks contained within. Symbolic variables can be undefined using the undefine statement, and modified using the redefine statement. Using symbolic variables. define int_if1 = eth0 define int_if2 = eth1 define int_ifs = { $int_if1, $int_if2 } redefine int_if2 = wlan0 undefine int_if2 filter input iif $int_ifs accept ADDRESS FAMILIES Address families determine the type of packets which are processed. For each address family, the kernel contains so called hooks at specific stages of the packet processing paths, which invoke nftables if rules for these hooks exist. ip IPv4 address family. ip6 IPv6 address family. inet Internet (IPv4/IPv6) address family. arp ARP address family, handling IPv4 ARP packets. bridge Bridge address family, handling packets which traverse a bridge device. netdev Netdev address family, handling packets on ingress and egress. All nftables objects exist in address family specific namespaces, therefore all identifiers include an address family. If an identifier is specified without an address family, the ip family is used by default. IPV4/IPV6/INET ADDRESS FAMILIES The IPv4/IPv6/Inet address families handle IPv4, IPv6 or both types of packets. They contain five hooks at different packet processing stages in the network stack. Table 1. IPv4/IPv6/Inet address family hooks ┌─────────────┬──────────────────────────────────┐ │ Hook │ Description │ ├─────────────┼──────────────────────────────────┤ │ │ │ │ prerouting │ All packets entering the system │ │ │ are processed by the prerouting │ │ │ hook. It is invoked before the │ │ │ routing process and is used for │ │ │ early filtering or changing │ │ │ packet attributes that affect │ │ │ routing. │ ├─────────────┼──────────────────────────────────┤ │ │ │ │ input │ Packets delivered to the local │ │ │ system are processed by the │ │ │ input hook. │ ├─────────────┼──────────────────────────────────┤ │ │ │ │ forward │ Packets forwarded to a different │ │ │ host are processed by the │ │ │ forward hook. │ ├─────────────┼──────────────────────────────────┤ │ │ │ │ output │ Packets sent by local processes │ │ │ are processed by the output │ │ │ hook. │ ├─────────────┼──────────────────────────────────┤ │ │ │ │ postrouting │ All packets leaving the system │ │ │ are processed by the postrouting │ │ │ hook. │ ├─────────────┼──────────────────────────────────┤ │ │ │ │ ingress │ All packets entering the system │ │ │ are processed by this hook. It │ │ │ is invoked before layer 3 │ │ │ protocol handlers, hence before │ │ │ the prerouting hook, and it can │ │ │ be used for filtering and │ │ │ policing. Ingress is only │ │ │ available for Inet family (since │ │ │ Linux kernel 5.10). │ └─────────────┴──────────────────────────────────┘ ARP ADDRESS FAMILY The ARP address family handles ARP packets received and sent by the system. It is commonly used to mangle ARP packets for clustering. Table 2. ARP address family hooks ┌────────┬──────────────────────────────────┐ │ Hook │ Description │ ├────────┼──────────────────────────────────┤ │ │ │ │ input │ Packets delivered to the local │ │ │ system are processed by the │ │ │ input hook. │ ├────────┼──────────────────────────────────┤ │ │ │ │ output │ Packets send by the local system │ │ │ are processed by the output │ │ │ hook. │ └────────┴──────────────────────────────────┘ BRIDGE ADDRESS FAMILY The bridge address family handles Ethernet packets traversing bridge devices. The list of supported hooks is identical to IPv4/IPv6/Inet address families above. NETDEV ADDRESS FAMILY The Netdev address family handles packets from the device ingress and egress path. This family allows you to filter packets of any ethertype such as ARP, VLAN 802.1q, VLAN 802.1ad (Q-in-Q) as well as IPv4 and IPv6 packets. Table 3. Netdev address family hooks ┌─────────┬─────────────────────────────────┐ │ Hook │ Description │ ├─────────┼─────────────────────────────────┤ │ │ │ │ ingress │ All packets entering the system │ │ │ are processed by this hook. It │ │ │ is invoked after the network │ │ │ taps (ie. tcpdump), right after │ │ │ tc ingress and before layer 3 │ │ │ protocol handlers, it can be │ │ │ used for early filtering and │ │ │ policing. │ ├─────────┼─────────────────────────────────┤ │ │ │ │ egress │ All packets leaving the system │ │ │ are processed by this hook. It │ │ │ is invoked after layer 3 │ │ │ protocol handlers and before tc │ │ │ egress. It can be used for late │ │ │ filtering and policing. │ └─────────┴─────────────────────────────────┘ Tunneled packets (such as vxlan) are processed by netdev family hooks both in decapsulated and encapsulated (tunneled) form. So a packet can be filtered on the overlay network as well as on the underlying network. Note that the order of netfilter and tc is mirrored on ingress versus egress. This ensures symmetry for NAT and other packet mangling. Ingress packets which are redirected out some other interface are only processed by netfilter on egress if they have passed through netfilter ingress processing before. Thus, ingress packets which are redirected by tc are not subjected to netfilter. But they are if they are redirected by netfilter on ingress. Conceptually, tc and netfilter can be thought of as layers, with netfilter layered above tc: If the packet hasn’t been passed up from the tc layer to the netfilter layer, it’s not subjected to netfilter on egress. RULESET {list | flush} ruleset [family] The ruleset keyword is used to identify the whole set of tables, chains, etc. currently in place in kernel. The following ruleset commands exist: list Print the ruleset in human-readable format. flush Clear the whole ruleset. Note that, unlike iptables, this will remove all tables and whatever they contain, effectively leading to an empty ruleset - no packet filtering will happen anymore, so the kernel accepts any valid packet it receives. It is possible to limit list and flush to a specific address family only. For a list of valid family names, see the section called “ADDRESS FAMILIES” above. By design, list ruleset command output may be used as input to nft -f. Effectively, this is the nft-equivalent of iptables-save and iptables-restore. TABLES {add | create} table [family] table [ {comment comment ;} { flags 'flags ; }] {delete | destroy | list | flush} table [family] table list tables [family] delete table [family] handle handle destroy table [family] handle handle Tables are containers for chains, sets and stateful objects. They are identified by their address family and their name. The address family must be one of ip, ip6, inet, arp, bridge, netdev. The inet address family is a dummy family which is used to create hybrid IPv4/IPv6 tables. The meta expression nfproto keyword can be used to test which family (ipv4 or ipv6) context the packet is being processed in. When no address family is specified, ip is used by default. The only difference between add and create is that the former will not return an error if the specified table already exists while create will return an error. Table 4. Table flags ┌─────────┬─────────────────────────────────┐ │ Flag │ Description │ ├─────────┼─────────────────────────────────┤ │ │ │ │ dormant │ table is not evaluated any more │ │ │ (base chains are unregistered). │ └─────────┴─────────────────────────────────┘ Add, change, delete a table. # start nft in interactive mode nft --interactive # create a new table. create table inet mytable # add a new base chain: get input packets add chain inet mytable myin { type filter hook input priority filter; } # add a single counter to the chain add rule inet mytable myin counter # disable the table temporarily -- rules are not evaluated anymore add table inet mytable { flags dormant; } # make table active again: add table inet mytable add Add a new table for the given family with the given name. delete Delete the specified table. destroy Delete the specified table, it does not fail if it does not exist. list List all chains and rules of the specified table. flush Flush all chains and rules of the specified table. CHAINS {add | create} chain [family] table chain [{ type type hook hook [device device] priority priority ; [policy policy ;] [comment comment ;] }] {delete | destroy | list | flush} chain ['family] table chain list chains [family] delete chain [family] table handle handle destroy chain [family] table handle handle rename chain [family] table chain newname Chains are containers for rules. They exist in two kinds, base chains and regular chains. A base chain is an entry point for packets from the networking stack, a regular chain may be used as jump target and is used for better rule organization. add Add a new chain in the specified table. When a hook and priority value are specified, the chain is created as a base chain and hooked up to the networking stack. create Similar to the add command, but returns an error if the chain already exists. delete Delete the specified chain. The chain must not contain any rules or be used as jump target. destroy Delete the specified chain, it does not fail if it does not exist. The chain must not contain any rules or be used as jump target. rename Rename the specified chain. list List all rules of the specified chain. flush Flush all rules of the specified chain. For base chains, type, hook and priority parameters are mandatory. Table 5. Supported chain types ┌────────┬───────────────┬─────────────────────┬─────────────────────┐ │ Type │ Families │ Hooks │ Description │ ├────────┼───────────────┼─────────────────────┼─────────────────────┤ │ │ │ │ │ │ filter │ all │ all │ Standard chain type │ │ │ │ │ to use in doubt. │ ├────────┼───────────────┼─────────────────────┼─────────────────────┤ │ │ │ │ │ │ nat │ ip, ip6, inet │ prerouting, input, │ Chains of this type │ │ │ │ output, postrouting │ perform Native │ │ │ │ │ Address Translation │ │ │ │ │ based on conntrack │ │ │ │ │ entries. Only the │ │ │ │ │ first packet of a │ │ │ │ │ connection actually │ │ │ │ │ traverses this │ │ │ │ │ chain - its rules │ │ │ │ │ usually define │ │ │ │ │ details of the │ │ │ │ │ created conntrack │ │ │ │ │ entry (NAT │ │ │ │ │ statements for │ │ │ │ │ instance). │ ├────────┼───────────────┼─────────────────────┼─────────────────────┤ │ │ │ │ │ │ route │ ip, ip6 │ output │ If a packet has │ │ │ │ │ traversed a chain │ │ │ │ │ of this type and is │ │ │ │ │ about to be │ │ │ │ │ accepted, a new │ │ │ │ │ route lookup is │ │ │ │ │ performed if │ │ │ │ │ relevant parts of │ │ │ │ │ the IP header have │ │ │ │ │ changed. This │ │ │ │ │ allows one to e.g. │ │ │ │ │ implement policy │ │ │ │ │ routing selectors │ │ │ │ │ in nftables. │ └────────┴───────────────┴─────────────────────┴─────────────────────┘ Apart from the special cases illustrated above (e.g. nat type not supporting forward hook or route type only supporting output hook), there are three further quirks worth noticing: • The netdev family supports merely two combinations, namely filter type with ingress hook and filter type with egress hook. Base chains in this family also require the device parameter to be present since they exist per interface only. • The arp family supports only the input and output hooks, both in chains of type filter. • The inet family also supports the ingress hook (since Linux kernel 5.10), to filter IPv4 and IPv6 packet at the same location as the netdev ingress hook. This inet hook allows you to share sets and maps between the usual prerouting, input, forward, output, postrouting and this ingress hook. The device parameter accepts a network interface name as a string, and is required when adding a base chain that filters traffic on the ingress or egress hooks. Any ingress or egress chains will only filter traffic from the interface specified in the device parameter. The priority parameter accepts a signed integer value or a standard priority name which specifies the order in which chains with the same hook value are traversed. The ordering is ascending, i.e. lower priority values have precedence over higher ones. With nat type chains, there’s a lower excluding limit of -200 for priority values, because conntrack hooks at this priority and NAT requires it. Standard priority values can be replaced with easily memorizable names. Not all names make sense in every family with every hook (see the compatibility matrices below) but their numerical value can still be used for prioritizing chains. These names and values are defined and made available based on what priorities are used by xtables when registering their default chains. Most of the families use the same values, but bridge uses different ones from the others. See the following tables that describe the values and compatibility. Table 6. Standard priority names, family and hook compatibility matrix ┌──────────┬───────┬─────────────────────┬─────────────┐ │ Name │ Value │ Families │ Hooks │ ├──────────┼───────┼─────────────────────┼─────────────┤ │ │ │ │ │ │ raw │ -300 │ ip, ip6, inet │ all │ ├──────────┼───────┼─────────────────────┼─────────────┤ │ │ │ │ │ │ mangle │ -150 │ ip, ip6, inet │ all │ ├──────────┼───────┼─────────────────────┼─────────────┤ │ │ │ │ │ │ dstnat │ -100 │ ip, ip6, inet │ prerouting │ ├──────────┼───────┼─────────────────────┼─────────────┤ │ │ │ │ │ │ filter │ 0 │ ip, ip6, inet, arp, │ all │ │ │ │ netdev │ │ ├──────────┼───────┼─────────────────────┼─────────────┤ │ │ │ │ │ │ security │ 50 │ ip, ip6, inet │ all │ ├──────────┼───────┼─────────────────────┼─────────────┤ │ │ │ │ │ │ srcnat │ 100 │ ip, ip6, inet │ postrouting │ └──────────┴───────┴─────────────────────┴─────────────┘ Table 7. Standard priority names and hook compatibility for the bridge family ┌────────┬───────┬─────────────┐ │ │ │ │ │ Name │ Value │ Hooks │ ├────────┼───────┼─────────────┤ │ │ │ │ │ dstnat │ -300 │ prerouting │ ├────────┼───────┼─────────────┤ │ │ │ │ │ filter │ -200 │ all │ ├────────┼───────┼─────────────┤ │ │ │ │ │ out │ 100 │ output │ ├────────┼───────┼─────────────┤ │ │ │ │ │ srcnat │ 300 │ postrouting │ └────────┴───────┴─────────────┘ Basic arithmetic expressions (addition and subtraction) can also be achieved with these standard names to ease relative prioritizing, e.g. mangle - 5 stands for -155. Values will also be printed like this until the value is not further than 10 from the standard value. Base chains also allow one to set the chain’s policy, i.e. what happens to packets not explicitly accepted or refused in contained rules. Supported policy values are accept (which is the default) or drop. RULES {add | insert} rule [family] table chain [handle handle | index index] statement ... [comment comment] replace rule [family] table chain handle handle statement ... [comment comment] {delete | reset} rule [family] table chain handle handle destroy rule [family] table chain handle handle reset rules [family] [table [chain]] Rules are added to chains in the given table. If the family is not specified, the ip family is used. Rules are constructed from two kinds of components according to a set of grammatical rules: expressions and statements. The add and insert commands support an optional location specifier, which is either a handle or the index (starting at zero) of an existing rule. Internally, rule locations are always identified by handle and the translation from index happens in userspace. This has two potential implications in case a concurrent ruleset change happens after the translation was done: The effective rule index might change if a rule was inserted or deleted before the referred one. If the referred rule was deleted, the command is rejected by the kernel just as if an invalid handle was given. A comment is a single word or a double-quoted (") multi-word string which can be used to make notes regarding the actual rule. Note: If you use bash for adding rules, you have to escape the quotation marks, e.g. \"enable ssh for servers\". add Add a new rule described by the list of statements. The rule is appended to the given chain unless a location is specified, in which case the rule is inserted after the specified rule. insert Same as add except the rule is inserted at the beginning of the chain or before the specified rule. replace Similar to add, but the rule replaces the specified rule. delete Delete the specified rule. destroy Delete the specified rule, it does not fail if it does not exist. reset Reset rule-contained state, e.g. counter and quota statement values. add a rule to ip table output chain. nft add rule filter output ip daddr 192.168.0.0/24 accept # 'ip filter' is assumed # same command, slightly more verbose nft add rule ip filter output ip daddr 192.168.0.0/24 accept delete rule from inet table. # nft -a list ruleset table inet filter { chain input { type filter hook input priority filter; policy accept; ct state established,related accept # handle 4 ip saddr 10.1.1.1 tcp dport ssh accept # handle 5 ... # delete the rule with handle 5 nft delete rule inet filter input handle 5 SETS nftables offers two kinds of set concepts. Anonymous sets are sets that have no specific name. The set members are enclosed in curly braces, with commas to separate elements when creating the rule the set is used in. Once that rule is removed, the set is removed as well. They cannot be updated, i.e. once an anonymous set is declared it cannot be changed anymore except by removing/altering the rule that uses the anonymous set. Using anonymous sets to accept particular subnets and ports. nft add rule filter input ip saddr { 10.0.0.0/8, 192.168.0.0/16 } tcp dport { 22, 443 } accept Named sets are sets that need to be defined first before they can be referenced in rules. Unlike anonymous sets, elements can be added to or removed from a named set at any time. Sets are referenced from rules using an @ prefixed to the sets name. Using named sets to accept addresses and ports. nft add rule filter input ip saddr @allowed_hosts tcp dport @allowed_ports accept The sets allowed_hosts and allowed_ports need to be created first. The next section describes nft set syntax in more detail. add set [family] table set { type type | typeof expression ; [flags flags ;] [timeout timeout ;] [gc-interval gc-interval ;] [elements = { element[, ...] } ;] [size size ;] [comment comment ;] [policy 'policy ;] [auto-merge ;] } {delete | destroy | list | flush | reset } set [family] table set list sets [family] delete set [family] table handle handle {add | delete | destroy } element [family] table set { element[, ...] } Sets are element containers of a user-defined data type, they are uniquely identified by a user-defined name and attached to tables. Their behaviour can be tuned with the flags that can be specified at set creation time. add Add a new set in the specified table. See the Set specification table below for more information about how to specify properties of a set. delete Delete the specified set. destroy Delete the specified set, it does not fail if it does not exist. list Display the elements in the specified set. flush Remove all elements from the specified set. reset Reset state in all contained elements, e.g. counter and quota statement values. Table 8. Set specifications ┌─────────────┬──────────────────────────┬──────────────────────────┐ │ Keyword │ Description │ Type │ ├─────────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ type │ data type of set │ string: ipv4_addr, │ │ │ elements │ ipv6_addr, ether_addr, │ │ │ │ inet_proto, │ │ │ │ inet_service, mark │ ├─────────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ typeof │ data type of set element │ expression to derive the │ │ │ │ data type from │ ├─────────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ flags │ set flags │ string: constant, │ │ │ │ dynamic, interval, │ │ │ │ timeout. Used to │ │ │ │ describe the sets │ │ │ │ properties. │ ├─────────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ timeout │ time an element stays in │ string, decimal followed │ │ │ the set, mandatory if │ by unit. Units are: d, │ │ │ set is added to from the │ h, m, s │ │ │ packet path (ruleset) │ │ ├─────────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ gc-interval │ garbage collection │ string, decimal followed │ │ │ interval, only available │ by unit. Units are: d, │ │ │ when timeout or flag │ h, m, s │ │ │ timeout are active │ │ ├─────────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ elements │ elements contained by │ set data type │ │ │ the set │ │ ├─────────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ size │ maximum number of │ unsigned integer (64 │ │ │ elements in the set, │ bit) │ │ │ mandatory if set is │ │ │ │ added to from the packet │ │ │ │ path (ruleset) │ │ ├─────────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ policy │ set policy │ string: performance │ │ │ │ [default], memory │ ├─────────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ auto-merge │ automatic merge of │ │ │ │ adjacent/overlapping set │ │ │ │ elements (only for │ │ │ │ interval sets) │ │ └─────────────┴──────────────────────────┴──────────────────────────┘ MAPS add map [family] table map { type type | typeof expression [flags flags ;] [elements = { element[, ...] } ;] [size size ;] [comment comment ;] [policy 'policy ;] } {delete | destroy | list | flush | reset } map [family] table map list maps [family] Maps store data based on some specific key used as input. They are uniquely identified by a user-defined name and attached to tables. add Add a new map in the specified table. delete Delete the specified map. destroy Delete the specified map, it does not fail if it does not exist. list Display the elements in the specified map. flush Remove all elements from the specified map. reset Reset state in all contained elements, e.g. counter and quota statement values. Table 9. Map specifications ┌──────────┬──────────────────────────┬──────────────────────────┐ │ Keyword │ Description │ Type │ ├──────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ type │ data type of map │ string: ipv4_addr, │ │ │ elements │ ipv6_addr, ether_addr, │ │ │ │ inet_proto, │ │ │ │ inet_service, mark, │ │ │ │ counter, quota. Counter │ │ │ │ and quota can’t be used │ │ │ │ as keys │ ├──────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ typeof │ data type of set element │ expression to derive the │ │ │ │ data type from │ ├──────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ flags │ map flags │ string, same as set │ │ │ │ flags │ ├──────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ elements │ elements contained by │ map data type │ │ │ the map │ │ ├──────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ size │ maximum number of │ unsigned integer (64 │ │ │ elements in the map │ bit) │ ├──────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ policy │ map policy │ string: performance │ │ │ │ [default], memory │ └──────────┴──────────────────────────┴──────────────────────────┘ Users can specifiy the properties/features that the set/map must support. This allows the kernel to pick an optimal internal representation. If a required flag is missing, the ruleset might still work, as nftables will auto-enable features if it can infer this from the ruleset. This may not work for all cases, however, so it is recommended to specify all required features in the set/map definition manually. Table 10. Set and Map flags ┌──────────┬────────────────────────────────┐ │ Flag │ Description │ ├──────────┼────────────────────────────────┤ │ │ │ │ constant │ Set contents will never change │ │ │ after creation │ ├──────────┼────────────────────────────────┤ │ │ │ │ dynamic │ Set must support updates from │ │ │ the packet path with the add, │ │ │ update or delete keywords. │ ├──────────┼────────────────────────────────┤ │ │ │ │ interval │ Set must be able to store │ │ │ intervals (ranges) │ ├──────────┼────────────────────────────────┤ │ │ │ │ timeout │ Set must support element │ │ │ timeouts (auto-removal of │ │ │ elements once they expire). │ └──────────┴────────────────────────────────┘ ELEMENTS {add | create | delete | destroy | get | reset } element [family] table set { ELEMENT[, ...] } ELEMENT := key_expression OPTIONS [: value_expression] OPTIONS := [timeout TIMESPEC] [expires TIMESPEC] [comment string] TIMESPEC := [numd][numh][numm][num[s]] Element-related commands allow one to change contents of named sets and maps. key_expression is typically a value matching the set type. value_expression is not allowed in sets but mandatory when adding to maps, where it matches the data part in its type definition. When deleting from maps, it may be specified but is optional as key_expression uniquely identifies the element. create command is similar to add with the exception that none of the listed elements may already exist. get command is useful to check if an element is contained in a set which may be non-trivial in very large and/or interval sets. In the latter case, the containing interval is returned instead of just the element itself. reset command resets state attached to the given element(s), e.g. counter and quota statement values. Table 11. Element options ┌─────────┬──────────────────────────────────┐ │ Option │ Description │ ├─────────┼──────────────────────────────────┤ │ │ │ │ timeout │ timeout value for sets/maps with │ │ │ flag timeout │ ├─────────┼──────────────────────────────────┤ │ │ │ │ expires │ the time until given element │ │ │ expires, useful for ruleset │ │ │ replication only │ ├─────────┼──────────────────────────────────┤ │ │ │ │ comment │ per element comment field │ └─────────┴──────────────────────────────────┘ FLOWTABLES {add | create} flowtable [family] table flowtable { hook hook priority priority ; devices = { device[, ...] } ; } list flowtables [family] {delete | destroy | list} flowtable [family] table flowtable delete flowtable [family] table handle handle Flowtables allow you to accelerate packet forwarding in software. Flowtables entries are represented through a tuple that is composed of the input interface, source and destination address, source and destination port; and layer 3/4 protocols. Each entry also caches the destination interface and the gateway address - to update the destination link-layer address - to forward packets. The ttl and hoplimit fields are also decremented. Hence, flowtables provides an alternative path that allow packets to bypass the classic forwarding path. Flowtables reside in the ingress hook that is located before the prerouting hook. You can select which flows you want to offload through the flow expression from the forward chain. Flowtables are identified by their address family and their name. The address family must be one of ip, ip6, or inet. The inet address family is a dummy family which is used to create hybrid IPv4/IPv6 tables. When no address family is specified, ip is used by default. The priority can be a signed integer or filter which stands for 0. Addition and subtraction can be used to set relative priority, e.g. filter + 5 equals to 5. add Add a new flowtable for the given family with the given name. delete Delete the specified flowtable. destroy Delete the specified flowtable, it does not fail if it does not exist. list List all flowtables. LISTING list { secmarks | synproxys | flow tables | meters | hooks } [family] list { secmarks | synproxys | flow tables | meters | hooks } table [family] table list ct { timeout | expectation | helper | helpers } table [family] table Inspect configured objects. list hooks shows the full hook pipeline, including those registered by kernel modules, such as nf_conntrack. STATEFUL OBJECTS {add | delete | destroy | list | reset} counter [family] table object {add | delete | destroy | list | reset} quota [family] table object {add | delete | destroy | list} limit [family] table object delete counter [family] table handle handle delete quota [family] table handle handle delete limit [family] table handle handle destroy counter [family] table handle handle destroy quota [family] table handle handle destroy limit [family] table handle handle list counters [family] list quotas [family] list limits [family] reset counters [family] reset quotas [family] reset counters [family] table reset quotas [family] table Stateful objects are attached to tables and are identified by a unique name. They group stateful information from rules, to reference them in rules the keywords "type name" are used e.g. "counter name". add Add a new stateful object in the specified table. delete Delete the specified object. destroy Delete the specified object, it does not fail if it does not exist. list Display stateful information the object holds. reset List-and-reset stateful object. CT HELPER add ct helper [family] table name { type type protocol protocol ; [l3proto family ;] } delete ct helper [family] table name list ct helpers Ct helper is used to define connection tracking helpers that can then be used in combination with the ct helper set statement. type and protocol are mandatory, l3proto is derived from the table family by default, i.e. in the inet table the kernel will try to load both the ipv4 and ipv6 helper backends, if they are supported by the kernel. Table 12. conntrack helper specifications ┌──────────┬─────────────────────────┬──────────────────────────┐ │ Keyword │ Description │ Type │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ type │ name of helper type │ quoted string (e.g. │ │ │ │ "ftp") │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ protocol │ layer 4 protocol of the │ string (e.g. ip) │ │ │ helper │ │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ l3proto │ layer 3 protocol of the │ address family (e.g. ip) │ │ │ helper │ │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ comment │ per ct helper comment │ string │ │ │ field │ │ └──────────┴─────────────────────────┴──────────────────────────┘ defining and assigning ftp helper. Unlike iptables, helper assignment needs to be performed after the conntrack lookup has completed, for example with the default 0 hook priority. table inet myhelpers { ct helper ftp-standard { type "ftp" protocol tcp } chain prerouting { type filter hook prerouting priority filter; tcp dport 21 ct helper set "ftp-standard" } } CT TIMEOUT add ct timeout [family] table name { protocol protocol ; policy = { state: value [, ...] } ; [l3proto family ;] } delete ct timeout [family] table name list ct timeouts Ct timeout is used to update connection tracking timeout values.Timeout policies are assigned with the ct timeout set statement. protocol and policy are mandatory, l3proto is derived from the table family by default. Table 13. conntrack timeout specifications ┌──────────┬─────────────────────────┬──────────────────────────┐ │ Keyword │ Description │ Type │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ protocol │ layer 4 protocol of the │ string (e.g. ip) │ │ │ timeout object │ │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ state │ connection state name │ string (e.g. │ │ │ │ "established") │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ value │ timeout value for │ unsigned integer │ │ │ connection state │ │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ l3proto │ layer 3 protocol of the │ address family (e.g. ip) │ │ │ timeout object │ │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ comment │ per ct timeout comment │ string │ │ │ field │ │ └──────────┴─────────────────────────┴──────────────────────────┘ tcp connection state names that can have a specific timeout value are: close, close_wait, established, fin_wait, last_ack, retrans, syn_recv, syn_sent, time_wait and unack. You can use sysctl -a |grep net.netfilter.nf_conntrack_tcp_timeout_ to view and change the system-wide defaults. ct timeout allows for flow-specific settings, without changing the global timeouts. For example, tcp port 53 could have much lower settings than other traffic. udp state names that can have a specific timeout value are replied and unreplied. defining and assigning ct timeout policy. table ip filter { ct timeout customtimeout { protocol tcp; l3proto ip policy = { established: 2m, close: 20s } } chain output { type filter hook output priority filter; policy accept; ct timeout set "customtimeout" } } testing the updated timeout policy. % conntrack -E It should display: [UPDATE] tcp 6 120 ESTABLISHED src=172.16.19.128 dst=172.16.19.1 sport=22 dport=41360 [UNREPLIED] src=172.16.19.1 dst=172.16.19.128 sport=41360 dport=22 CT EXPECTATION add ct expectation [family] table name { protocol protocol ; dport dport ; timeout timeout ; size size ; [*l3proto family ;] } delete ct expectation [family] table name list ct expectations Ct expectation is used to create connection expectations. Expectations are assigned with the ct expectation set statement. protocol, dport, timeout and size are mandatory, l3proto is derived from the table family by default. Table 14. conntrack expectation specifications ┌──────────┬─────────────────────────┬──────────────────────────┐ │ Keyword │ Description │ Type │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ protocol │ layer 4 protocol of the │ string (e.g. ip) │ │ │ expectation object │ │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ dport │ destination port of │ unsigned integer │ │ │ expected connection │ │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ timeout │ timeout value for │ unsigned integer │ │ │ expectation │ │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ size │ size value for │ unsigned integer │ │ │ expectation │ │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ l3proto │ layer 3 protocol of the │ address family (e.g. ip) │ │ │ expectation object │ │ ├──────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ comment │ per ct expectation │ string │ │ │ comment field │ │ └──────────┴─────────────────────────┴──────────────────────────┘ defining and assigning ct expectation policy. table ip filter { ct expectation expect { protocol udp dport 9876 timeout 2m size 8 l3proto ip } chain input { type filter hook input priority filter; policy accept; ct expectation set "expect" } } COUNTER add counter [family] table name [{ [ packets packets bytes bytes ; ] [ comment comment ; }] delete counter [family] table name list counters Table 15. Counter specifications ┌─────────┬──────────────────────────┬──────────────────────┐ │ Keyword │ Description │ Type │ ├─────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ packets │ initial count of packets │ unsigned integer (64 │ │ │ │ bit) │ ├─────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ bytes │ initial count of bytes │ unsigned integer (64 │ │ │ │ bit) │ ├─────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ comment │ per counter comment │ string │ │ │ field │ │ └─────────┴──────────────────────────┴──────────────────────┘ Using named counters. nft add counter filter http nft add rule filter input tcp dport 80 counter name \"http\" Using named counters with maps. nft add counter filter http nft add counter filter https nft add rule filter input counter name tcp dport map { 80 : \"http\", 443 : \"https\" } QUOTA add quota [family] table name { [over|until] bytes BYTE_UNIT [ used bytes BYTE_UNIT ] ; [ comment comment ; ] } BYTE_UNIT := bytes | kbytes | mbytes delete quota [family] table name list quotas Table 16. Quota specifications ┌─────────┬──────────────────────────┬─────────────────────────┐ │ Keyword │ Description │ Type │ ├─────────┼──────────────────────────┼─────────────────────────┤ │ │ │ │ │ quota │ quota limit, used as the │ Two arguments, unsigned │ │ │ quota name │ integer (64 bit) and │ │ │ │ string: bytes, kbytes, │ │ │ │ mbytes. "over" and │ │ │ │ "until" go before these │ │ │ │ arguments │ ├─────────┼──────────────────────────┼─────────────────────────┤ │ │ │ │ │ used │ initial value of used │ Two arguments, unsigned │ │ │ quota │ integer (64 bit) and │ │ │ │ string: bytes, kbytes, │ │ │ │ mbytes │ ├─────────┼──────────────────────────┼─────────────────────────┤ │ │ │ │ │ comment │ per quota comment field │ string │ └─────────┴──────────────────────────┴─────────────────────────┘ Using named quotas. nft add quota filter user123 { over 20 mbytes } nft add rule filter input ip saddr 192.168.10.123 quota name \"user123\" Using named quotas with maps. nft add quota filter user123 { over 20 mbytes } nft add quota filter user124 { over 20 mbytes } nft add rule filter input quota name ip saddr map { 192.168.10.123 : \"user123\", 192.168.10.124 : \"user124\" } EXPRESSIONS Expressions represent values, either constants like network addresses, port numbers, etc., or data gathered from the packet during ruleset evaluation. Expressions can be combined using binary, logical, relational and other types of expressions to form complex or relational (match) expressions. They are also used as arguments to certain types of operations, like NAT, packet marking etc. Each expression has a data type, which determines the size, parsing and representation of symbolic values and type compatibility with other expressions. DESCRIBE COMMAND describe expression | data type The describe command shows information about the type of an expression and its data type. A data type may also be given, in which nft will display more information about the type. The describe command. $ nft describe tcp flags payload expression, datatype tcp_flag (TCP flag) (basetype bitmask, integer), 8 bits predefined symbolic constants: fin 0x01 syn 0x02 rst 0x04 psh 0x08 ack 0x10 urg 0x20 ecn 0x40 cwr 0x80 DATA TYPES Data types determine the size, parsing and representation of symbolic values and type compatibility of expressions. A number of global data types exist, in addition some expression types define further data types specific to the expression type. Most data types have a fixed size, some however may have a dynamic size, f.i. the string type. Some types also have predefined symbolic constants. Those can be listed using the nft describe command: $ nft describe ct_state datatype ct_state (conntrack state) (basetype bitmask, integer), 32 bits pre-defined symbolic constants (in hexadecimal): invalid 0x00000001 new ... Types may be derived from lower order types, f.i. the IPv4 address type is derived from the integer type, meaning an IPv4 address can also be specified as an integer value. In certain contexts (set and map definitions), it is necessary to explicitly specify a data type. Each type has a name which is used for this. INTEGER TYPE ┌─────────┬─────────┬──────────┬───────────┐ │ Name │ Keyword │ Size │ Base type │ ├─────────┼─────────┼──────────┼───────────┤ │ │ │ │ │ │ Integer │ integer │ variable │ - │ └─────────┴─────────┴──────────┴───────────┘ The integer type is used for numeric values. It may be specified as a decimal, hexadecimal or octal number. The integer type does not have a fixed size, its size is determined by the expression for which it is used. BITMASK TYPE ┌─────────┬─────────┬──────────┬───────────┐ │ Name │ Keyword │ Size │ Base type │ ├─────────┼─────────┼──────────┼───────────┤ │ │ │ │ │ │ Bitmask │ bitmask │ variable │ integer │ └─────────┴─────────┴──────────┴───────────┘ The bitmask type (bitmask) is used for bitmasks. STRING TYPE ┌────────┬─────────┬──────────┬───────────┐ │ Name │ Keyword │ Size │ Base type │ ├────────┼─────────┼──────────┼───────────┤ │ │ │ │ │ │ String │ string │ variable │ - │ └────────┴─────────┴──────────┴───────────┘ The string type is used for character strings. A string begins with an alphabetic character (a-zA-Z) followed by zero or more alphanumeric characters or the characters /, -, _ and .. In addition, anything enclosed in double quotes (") is recognized as a string. String specification. # Interface name filter input iifname eth0 # Weird interface name filter input iifname "(eth0)" LINK LAYER ADDRESS TYPE ┌────────────────────┬─────────┬──────────┬───────────┐ │ Name │ Keyword │ Size │ Base type │ ├────────────────────┼─────────┼──────────┼───────────┤ │ │ │ │ │ │ Link layer address │ lladdr │ variable │ integer │ └────────────────────┴─────────┴──────────┴───────────┘ The link layer address type is used for link layer addresses. Link layer addresses are specified as a variable amount of groups of two hexadecimal digits separated using colons (:). Link layer address specification. # Ethernet destination MAC address filter input ether daddr 20:c9:d0:43:12:d9 IPV4 ADDRESS TYPE ┌──────────────┬───────────┬────────┬───────────┐ │ Name │ Keyword │ Size │ Base type │ ├──────────────┼───────────┼────────┼───────────┤ │ │ │ │ │ │ IPV4 address │ ipv4_addr │ 32 bit │ integer │ └──────────────┴───────────┴────────┴───────────┘ The IPv4 address type is used for IPv4 addresses. Addresses are specified in either dotted decimal, dotted hexadecimal, dotted octal, decimal, hexadecimal, octal notation or as a host name. A host name will be resolved using the standard system resolver. IPv4 address specification. # dotted decimal notation filter output ip daddr 127.0.0.1 # host name filter output ip daddr localhost IPV6 ADDRESS TYPE ┌──────────────┬───────────┬─────────┬───────────┐ │ Name │ Keyword │ Size │ Base type │ ├──────────────┼───────────┼─────────┼───────────┤ │ │ │ │ │ │ IPv6 address │ ipv6_addr │ 128 bit │ integer │ └──────────────┴───────────┴─────────┴───────────┘ The IPv6 address type is used for IPv6 addresses. Addresses are specified as a host name or as hexadecimal halfwords separated by colons. Addresses might be enclosed in square brackets ("[]") to differentiate them from port numbers. IPv6 address specification. # abbreviated loopback address filter output ip6 daddr ::1 IPv6 address specification with bracket notation. # without [] the port number (22) would be parsed as part of the # ipv6 address ip6 nat prerouting tcp dport 2222 dnat to [1ce::d0]:22 BOOLEAN TYPE ┌─────────┬─────────┬───────┬───────────┐ │ Name │ Keyword │ Size │ Base type │ ├─────────┼─────────┼───────┼───────────┤ │ │ │ │ │ │ Boolean │ boolean │ 1 bit │ integer │ └─────────┴─────────┴───────┴───────────┘ The boolean type is a syntactical helper type in userspace. Its use is in the right-hand side of a (typically implicit) relational expression to change the expression on the left-hand side into a boolean check (usually for existence). Table 17. The following keywords will automatically resolve into a boolean type with given value ┌─────────┬───────┐ │ Keyword │ Value │ ├─────────┼───────┤ │ │ │ │ exists │ 1 │ ├─────────┼───────┤ │ │ │ │ missing │ 0 │ └─────────┴───────┘ Table 18. expressions support a boolean comparison ┌────────────┬─────────────────────────────┐ │ Expression │ Behaviour │ ├────────────┼─────────────────────────────┤ │ │ │ │ fib │ Check route existence. │ ├────────────┼─────────────────────────────┤ │ │ │ │ exthdr │ Check IPv6 extension header │ │ │ existence. │ ├────────────┼─────────────────────────────┤ │ │ │ │ tcp option │ Check TCP option header │ │ │ existence. │ └────────────┴─────────────────────────────┘ Boolean specification. # match if route exists filter input fib daddr . iif oif exists # match only non-fragmented packets in IPv6 traffic filter input exthdr frag missing # match if TCP timestamp option is present filter input tcp option timestamp exists ICMP TYPE TYPE ┌───────────┬───────────┬───────┬───────────┐ │ Name │ Keyword │ Size │ Base type │ ├───────────┼───────────┼───────┼───────────┤ │ │ │ │ │ │ ICMP Type │ icmp_type │ 8 bit │ integer │ └───────────┴───────────┴───────┴───────────┘ The ICMP Type type is used to conveniently specify the ICMP header’s type field. Table 19. Keywords may be used when specifying the ICMP type ┌─────────────────────────┬───────┐ │ Keyword │ Value │ ├─────────────────────────┼───────┤ │ │ │ │ echo-reply │ 0 │ ├─────────────────────────┼───────┤ │ │ │ │ destination-unreachable │ 3 │ ├─────────────────────────┼───────┤ │ │ │ │ source-quench │ 4 │ ├─────────────────────────┼───────┤ │ │ │ │ redirect │ 5 │ ├─────────────────────────┼───────┤ │ │ │ │ echo-request │ 8 │ ├─────────────────────────┼───────┤ │ │ │ │ router-advertisement │ 9 │ ├─────────────────────────┼───────┤ │ │ │ │ router-solicitation │ 10 │ ├─────────────────────────┼───────┤ │ │ │ │ time-exceeded │ 11 │ ├─────────────────────────┼───────┤ │ │ │ │ parameter-problem │ 12 │ ├─────────────────────────┼───────┤ │ │ │ │ timestamp-request │ 13 │ ├─────────────────────────┼───────┤ │ │ │ │ timestamp-reply │ 14 │ ├─────────────────────────┼───────┤ │ │ │ │ info-request │ 15 │ ├─────────────────────────┼───────┤ │ │ │ │ info-reply │ 16 │ ├─────────────────────────┼───────┤ │ │ │ │ address-mask-request │ 17 │ ├─────────────────────────┼───────┤ │ │ │ │ address-mask-reply │ 18 │ └─────────────────────────┴───────┘ ICMP Type specification. # match ping packets filter output icmp type { echo-request, echo-reply } ICMP CODE TYPE ┌───────────┬───────────┬───────┬───────────┐ │ Name │ Keyword │ Size │ Base type │ ├───────────┼───────────┼───────┼───────────┤ │ │ │ │ │ │ ICMP Code │ icmp_code │ 8 bit │ integer │ └───────────┴───────────┴───────┴───────────┘ The ICMP Code type is used to conveniently specify the ICMP header’s code field. Table 20. Keywords may be used when specifying the ICMP code ┌──────────────────┬───────┐ │ Keyword │ Value │ ├──────────────────┼───────┤ │ │ │ │ net-unreachable │ 0 │ ├──────────────────┼───────┤ │ │ │ │ host-unreachable │ 1 │ ├──────────────────┼───────┤ │ │ │ │ prot-unreachable │ 2 │ ├──────────────────┼───────┤ │ │ │ │ port-unreachable │ 3 │ ├──────────────────┼───────┤ │ │ │ │ frag-needed │ 4 │ ├──────────────────┼───────┤ │ │ │ │ net-prohibited │ 9 │ ├──────────────────┼───────┤ │ │ │ │ host-prohibited │ 10 │ ├──────────────────┼───────┤ │ │ │ │ admin-prohibited │ 13 │ └──────────────────┴───────┘ ICMPV6 TYPE TYPE ┌─────────────┬────────────┬───────┬───────────┐ │ Name │ Keyword │ Size │ Base type │ ├─────────────┼────────────┼───────┼───────────┤ │ │ │ │ │ │ ICMPv6 Type │ icmpx_code │ 8 bit │ integer │ └─────────────┴────────────┴───────┴───────────┘ The ICMPv6 Type type is used to conveniently specify the ICMPv6 header’s type field. Table 21. keywords may be used when specifying the ICMPv6 type: ┌─────────────────────────┬───────┐ │ Keyword │ Value │ ├─────────────────────────┼───────┤ │ │ │ │ destination-unreachable │ 1 │ ├─────────────────────────┼───────┤ │ │ │ │ packet-too-big │ 2 │ ├─────────────────────────┼───────┤ │ │ │ │ time-exceeded │ 3 │ ├─────────────────────────┼───────┤ │ │ │ │ parameter-problem │ 4 │ ├─────────────────────────┼───────┤ │ │ │ │ echo-request │ 128 │ ├─────────────────────────┼───────┤ │ │ │ │ echo-reply │ 129 │ ├─────────────────────────┼───────┤ │ │ │ │ mld-listener-query │ 130 │ ├─────────────────────────┼───────┤ │ │ │ │ mld-listener-report │ 131 │ ├─────────────────────────┼───────┤ │ │ │ │ mld-listener-done │ 132 │ ├─────────────────────────┼───────┤ │ │ │ │ mld-listener-reduction │ 132 │ ├─────────────────────────┼───────┤ │ │ │ │ nd-router-solicit │ 133 │ ├─────────────────────────┼───────┤ │ │ │ │ nd-router-advert │ 134 │ ├─────────────────────────┼───────┤ │ │ │ │ nd-neighbor-solicit │ 135 │ ├─────────────────────────┼───────┤ │ │ │ │ nd-neighbor-advert │ 136 │ ├─────────────────────────┼───────┤ │ │ │ │ nd-redirect │ 137 │ ├─────────────────────────┼───────┤ │ │ │ │ router-renumbering │ 138 │ ├─────────────────────────┼───────┤ │ │ │ │ ind-neighbor-solicit │ 141 │ ├─────────────────────────┼───────┤ │ │ │ │ ind-neighbor-advert │ 142 │ ├─────────────────────────┼───────┤ │ │ │ │ mld2-listener-report │ 143 │ └─────────────────────────┴───────┘ ICMPv6 Type specification. # match ICMPv6 ping packets filter output icmpv6 type { echo-request, echo-reply } ICMPV6 CODE TYPE ┌─────────────┬─────────────┬───────┬───────────┐ │ Name │ Keyword │ Size │ Base type │ ├─────────────┼─────────────┼───────┼───────────┤ │ │ │ │ │ │ ICMPv6 Code │ icmpv6_code │ 8 bit │ integer │ └─────────────┴─────────────┴───────┴───────────┘ The ICMPv6 Code type is used to conveniently specify the ICMPv6 header’s code field. Table 22. keywords may be used when specifying the ICMPv6 code ┌──────────────────┬───────┐ │ Keyword │ Value │ ├──────────────────┼───────┤ │ │ │ │ no-route │ 0 │ ├──────────────────┼───────┤ │ │ │ │ admin-prohibited │ 1 │ ├──────────────────┼───────┤ │ │ │ │ addr-unreachable │ 3 │ ├──────────────────┼───────┤ │ │ │ │ port-unreachable │ 4 │ ├──────────────────┼───────┤ │ │ │ │ policy-fail │ 5 │ ├──────────────────┼───────┤ │ │ │ │ reject-route │ 6 │ └──────────────────┴───────┘ ICMPVX CODE TYPE ┌─────────────┬─────────────┬───────┬───────────┐ │ Name │ Keyword │ Size │ Base type │ ├─────────────┼─────────────┼───────┼───────────┤ │ │ │ │ │ │ ICMPvX Code │ icmpv6_type │ 8 bit │ integer │ └─────────────┴─────────────┴───────┴───────────┘ The ICMPvX Code type abstraction is a set of values which overlap between ICMP and ICMPv6 Code types to be used from the inet family. Table 23. keywords may be used when specifying the ICMPvX code ┌──────────────────┬───────┐ │ Keyword │ Value │ ├──────────────────┼───────┤ │ │ │ │ no-route │ 0 │ ├──────────────────┼───────┤ │ │ │ │ port-unreachable │ 1 │ ├──────────────────┼───────┤ │ │ │ │ host-unreachable │ 2 │ ├──────────────────┼───────┤ │ │ │ │ admin-prohibited │ 3 │ └──────────────────┴───────┘ CONNTRACK TYPES Table 24. overview of types used in ct expression and statement ┌─────────────────────┬───────────┬─────────┬───────────┐ │ Name │ Keyword │ Size │ Base type │ ├─────────────────────┼───────────┼─────────┼───────────┤ │ │ │ │ │ │ conntrack state │ ct_state │ 4 byte │ bitmask │ ├─────────────────────┼───────────┼─────────┼───────────┤ │ │ │ │ │ │ conntrack direction │ ct_dir │ 8 bit │ integer │ ├─────────────────────┼───────────┼─────────┼───────────┤ │ │ │ │ │ │ conntrack status │ ct_status │ 4 byte │ bitmask │ ├─────────────────────┼───────────┼─────────┼───────────┤ │ │ │ │ │ │ conntrack event │ ct_event │ 4 byte │ bitmask │ │ bits │ │ │ │ ├─────────────────────┼───────────┼─────────┼───────────┤ │ │ │ │ │ │ conntrack label │ ct_label │ 128 bit │ bitmask │ └─────────────────────┴───────────┴─────────┴───────────┘ For each of the types above, keywords are available for convenience: Table 25. conntrack state (ct_state) ┌─────────────┬───────┐ │ Keyword │ Value │ ├─────────────┼───────┤ │ │ │ │ invalid │ 1 │ ├─────────────┼───────┤ │ │ │ │ established │ 2 │ ├─────────────┼───────┤ │ │ │ │ related │ 4 │ ├─────────────┼───────┤ │ │ │ │ new │ 8 │ ├─────────────┼───────┤ │ │ │ │ untracked │ 64 │ └─────────────┴───────┘ Table 26. conntrack direction (ct_dir) ┌──────────┬───────┐ │ Keyword │ Value │ ├──────────┼───────┤ │ │ │ │ original │ 0 │ ├──────────┼───────┤ │ │ │ │ reply │ 1 │ └──────────┴───────┘ Table 27. conntrack status (ct_status) ┌────────────┬───────┐ │ Keyword │ Value │ ├────────────┼───────┤ │ │ │ │ expected │ 1 │ ├────────────┼───────┤ │ │ │ │ seen-reply │ 2 │ ├────────────┼───────┤ │ │ │ │ assured │ 4 │ ├────────────┼───────┤ │ │ │ │ confirmed │ 8 │ ├────────────┼───────┤ │ │ │ │ snat │ 16 │ ├────────────┼───────┤ │ │ │ │ dnat │ 32 │ ├────────────┼───────┤ │ │ │ │ dying │ 512 │ └────────────┴───────┘ Table 28. conntrack event bits (ct_event) ┌───────────┬───────┐ │ Keyword │ Value │ ├───────────┼───────┤ │ │ │ │ new │ 1 │ ├───────────┼───────┤ │ │ │ │ related │ 2 │ ├───────────┼───────┤ │ │ │ │ destroy │ 4 │ ├───────────┼───────┤ │ │ │ │ reply │ 8 │ ├───────────┼───────┤ │ │ │ │ assured │ 16 │ ├───────────┼───────┤ │ │ │ │ protoinfo │ 32 │ ├───────────┼───────┤ │ │ │ │ helper │ 64 │ ├───────────┼───────┤ │ │ │ │ mark │ 128 │ ├───────────┼───────┤ │ │ │ │ seqadj │ 256 │ ├───────────┼───────┤ │ │ │ │ secmark │ 512 │ ├───────────┼───────┤ │ │ │ │ label │ 1024 │ └───────────┴───────┘ Possible keywords for conntrack label type (ct_label) are read at runtime from /etc/connlabel.conf. DCCP PKTTYPE TYPE ┌──────────────────┬──────────────┬───────┬───────────┐ │ Name │ Keyword │ Size │ Base type │ ├──────────────────┼──────────────┼───────┼───────────┤ │ │ │ │ │ │ DCCP packet type │ dccp_pkttype │ 4 bit │ integer │ └──────────────────┴──────────────┴───────┴───────────┘ The DCCP packet type abstracts the different legal values of the respective four bit field in the DCCP header, as stated by RFC4340. Note that possible values 10-15 are considered reserved and therefore not allowed to be used. In iptables' dccp match, these values are aliased INVALID. With nftables, one may simply match on the numeric value range, i.e. 10-15. Table 29. keywords may be used when specifying the DCCP packet type ┌──────────┬───────┐ │ Keyword │ Value │ ├──────────┼───────┤ │ │ │ │ request │ 0 │ ├──────────┼───────┤ │ │ │ │ response │ 1 │ ├──────────┼───────┤ │ │ │ │ data │ 2 │ ├──────────┼───────┤ │ │ │ │ ack │ 3 │ ├──────────┼───────┤ │ │ │ │ dataack │ 4 │ ├──────────┼───────┤ │ │ │ │ closereq │ 5 │ ├──────────┼───────┤ │ │ │ │ close │ 6 │ ├──────────┼───────┤ │ │ │ │ reset │ 7 │ ├──────────┼───────┤ │ │ │ │ sync │ 8 │ ├──────────┼───────┤ │ │ │ │ syncack │ 9 │ └──────────┴───────┘ PRIMARY EXPRESSIONS The lowest order expression is a primary expression, representing either a constant or a single datum from a packet’s payload, meta data or a stateful module. META EXPRESSIONS meta {length | nfproto | l4proto | protocol | priority} [meta] {mark | iif | iifname | iiftype | oif | oifname | oiftype | skuid | skgid | nftrace | rtclassid | ibrname | obrname | pkttype | cpu | iifgroup | oifgroup | cgroup | random | ipsec | iifkind | oifkind | time | hour | day } A meta expression refers to meta data associated with a packet. There are two types of meta expressions: unqualified and qualified meta expressions. Qualified meta expressions require the meta keyword before the meta key, unqualified meta expressions can be specified by using the meta key directly or as qualified meta expressions. Meta l4proto is useful to match a particular transport protocol that is part of either an IPv4 or IPv6 packet. It will also skip any IPv6 extension headers present in an IPv6 packet. meta iif, oif, iifname and oifname are used to match the interface a packet arrived on or is about to be sent out on. iif and oif are used to match on the interface index, whereas iifname and oifname are used to match on the interface name. This is not the same — assuming the rule filter input meta iif "foo" Then this rule can only be added if the interface "foo" exists. Also, the rule will continue to match even if the interface "foo" is renamed to "bar". This is because internally the interface index is used. In case of dynamically created interfaces, such as tun/tap or dialup interfaces (ppp for example), it might be better to use iifname or oifname instead. In these cases, the name is used so the interface doesn’t have to exist to add such a rule, it will stop matching if the interface gets renamed and it will match again in case interface gets deleted and later a new interface with the same name is created. Like with iptables, wildcard matching on interface name prefixes is available for iifname and oifname matches by appending an asterisk (*) character. Note however that unlike iptables, nftables does not accept interface names consisting of the wildcard character only - users are supposed to just skip those always matching expressions. In order to match on literal asterisk character, one may escape it using backslash (\). Table 30. Meta expression types ┌───────────┬──────────────────────────┬─────────────────────┐ │ Keyword │ Description │ Type │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ length │ Length of the packet in │ integer (32-bit) │ │ │ bytes │ │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ nfproto │ real hook protocol │ integer (32 bit) │ │ │ family, useful only in │ │ │ │ inet table │ │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ l4proto │ layer 4 protocol, skips │ integer (8 bit) │ │ │ ipv6 extension headers │ │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ protocol │ EtherType protocol value │ ether_type │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ priority │ TC packet priority │ tc_handle │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ mark │ Packet mark │ mark │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ iif │ Input interface index │ iface_index │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ iifname │ Input interface name │ ifname │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ iiftype │ Input interface type │ iface_type │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ oif │ Output interface index │ iface_index │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ oifname │ Output interface name │ ifname │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ oiftype │ Output interface │ iface_type │ │ │ hardware type │ │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ sdif │ Slave device input │ iface_index │ │ │ interface index │ │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ sdifname │ Slave device interface │ ifname │ │ │ name │ │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ skuid │ UID associated with │ uid │ │ │ originating socket │ │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ skgid │ GID associated with │ gid │ │ │ originating socket │ │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ rtclassid │ Routing realm │ realm │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ ibrname │ Input bridge interface │ ifname │ │ │ name │ │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ obrname │ Output bridge interface │ ifname │ │ │ name │ │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ pkttype │ packet type │ pkt_type │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ cpu │ cpu number processing │ integer (32 bit) │ │ │ the packet │ │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ iifgroup │ incoming device group │ devgroup │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ oifgroup │ outgoing device group │ devgroup │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ cgroup │ control group id │ integer (32 bit) │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ random │ pseudo-random number │ integer (32 bit) │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ ipsec │ true if packet was ipsec │ boolean (1 bit) │ │ │ encrypted │ │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ iifkind │ Input interface kind │ │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ oifkind │ Output interface kind │ │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ time │ Absolute time of packet │ Integer (32 bit) or │ │ │ reception │ string │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ day │ Day of week │ Integer (8 bit) or │ │ │ │ string │ ├───────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ hour │ Hour of day │ String │ └───────────┴──────────────────────────┴─────────────────────┘ Table 31. Meta expression specific types ┌───────────────┬──────────────────────────────────┐ │ Type │ Description │ ├───────────────┼──────────────────────────────────┤ │ │ │ │ iface_index │ Interface index (32 bit number). │ │ │ Can be specified numerically or │ │ │ as name of an existing │ │ │ interface. │ ├───────────────┼──────────────────────────────────┤ │ │ │ │ ifname │ Interface name (16 byte string). │ │ │ Does not have to exist. │ ├───────────────┼──────────────────────────────────┤ │ │ │ │ iface_type │ Interface type (16 bit number). │ ├───────────────┼──────────────────────────────────┤ │ │ │ │ uid │ User ID (32 bit number). Can be │ │ │ specified numerically or as user │ │ │ name. │ ├───────────────┼──────────────────────────────────┤ │ │ │ │ gid │ Group ID (32 bit number). Can be │ │ │ specified numerically or as │ │ │ group name. │ ├───────────────┼──────────────────────────────────┤ │ │ │ │ realm │ Routing Realm (32 bit number). │ │ │ Can be specified numerically or │ │ │ as symbolic name defined in │ │ │ /etc/iproute2/rt_realms. │ ├───────────────┼──────────────────────────────────┤ │ │ │ │ devgroup_type │ Device group (32 bit number). │ │ │ Can be specified numerically or │ │ │ as symbolic name defined in │ │ │ /etc/iproute2/group. │ ├───────────────┼──────────────────────────────────┤ │ │ │ │ pkt_type │ Packet type: host (addressed to │ │ │ local host), broadcast (to all), │ │ │ multicast (to group), other │ │ │ (addressed to another host). │ ├───────────────┼──────────────────────────────────┤ │ │ │ │ ifkind │ Interface kind (16 byte string). │ │ │ See TYPES in ip-link(8) for a │ │ │ list. │ ├───────────────┼──────────────────────────────────┤ │ │ │ │ time │ Either an integer or a date in │ │ │ ISO format. For example: │ │ │ "2019-06-06 17:00". Hour and │ │ │ seconds are optional and can be │ │ │ omitted if desired. If omitted, │ │ │ midnight will be assumed. The │ │ │ following three would be │ │ │ equivalent: "2019-06-06", │ │ │ "2019-06-06 00:00" and │ │ │ "2019-06-06 00:00:00". When an │ │ │ integer is given, it is assumed │ │ │ to be a UNIX timestamp. │ ├───────────────┼──────────────────────────────────┤ │ │ │ │ day │ Either a day of week ("Monday", │ │ │ "Tuesday", etc.), or an integer │ │ │ between 0 and 6. Strings are │ │ │ matched case-insensitively, and │ │ │ a full match is not expected │ │ │ (e.g. "Mon" would match │ │ │ "Monday"). When an integer is │ │ │ given, 0 is Sunday and 6 is │ │ │ Saturday. │ ├───────────────┼──────────────────────────────────┤ │ │ │ │ hour │ A string representing an hour in │ │ │ 24-hour format. Seconds can │ │ │ optionally be specified. For │ │ │ example, 17:00 and 17:00:00 │ │ │ would be equivalent. │ └───────────────┴──────────────────────────────────┘ Using meta expressions. # qualified meta expression filter output meta oif eth0 filter forward meta iifkind { "tun", "veth" } # unqualified meta expression filter output oif eth0 # incoming packet was subject to ipsec processing raw prerouting meta ipsec exists accept SOCKET EXPRESSION socket {transparent | mark | wildcard} socket cgroupv2 level NUM Socket expression can be used to search for an existing open TCP/UDP socket and its attributes that can be associated with a packet. It looks for an established or non-zero bound listening socket (possibly with a non-local address). You can also use it to match on the socket cgroupv2 at a given ancestor level, e.g. if the socket belongs to cgroupv2 a/b, ancestor level 1 checks for a matching on cgroup a and ancestor level 2 checks for a matching on cgroup b. Table 32. Available socket attributes ┌─────────────┬──────────────────────────┬─────────────────┐ │ Name │ Description │ Type │ ├─────────────┼──────────────────────────┼─────────────────┤ │ │ │ │ │ transparent │ Value of the │ boolean (1 bit) │ │ │ IP_TRANSPARENT socket │ │ │ │ option in the found │ │ │ │ socket. It can be 0 or │ │ │ │ 1. │ │ ├─────────────┼──────────────────────────┼─────────────────┤ │ │ │ │ │ mark │ Value of the socket mark │ mark │ │ │ (SOL_SOCKET, SO_MARK). │ │ ├─────────────┼──────────────────────────┼─────────────────┤ │ │ │ │ │ wildcard │ Indicates whether the │ boolean (1 bit) │ │ │ socket is wildcard-bound │ │ │ │ (e.g. 0.0.0.0 or ::0). │ │ ├─────────────┼──────────────────────────┼─────────────────┤ │ │ │ │ │ cgroupv2 │ cgroup version 2 for │ cgroupv2 │ │ │ this socket (path from │ │ │ │ /sys/fs/cgroup) │ │ └─────────────┴──────────────────────────┴─────────────────┘ Using socket expression. # Mark packets that correspond to a transparent socket. "socket wildcard 0" # means that zero-bound listener sockets are NOT matched (which is usually # exactly what you want). table inet x { chain y { type filter hook prerouting priority mangle; policy accept; socket transparent 1 socket wildcard 0 mark set 0x00000001 accept } } # Trace packets that corresponds to a socket with a mark value of 15 table inet x { chain y { type filter hook prerouting priority mangle; policy accept; socket mark 0x0000000f nftrace set 1 } } # Set packet mark to socket mark table inet x { chain y { type filter hook prerouting priority mangle; policy accept; tcp dport 8080 mark set socket mark } } # Count packets for cgroupv2 "user.slice" at level 1 table inet x { chain y { type filter hook input priority filter; policy accept; socket cgroupv2 level 1 "user.slice" counter } } OSF EXPRESSION osf [ttl {loose | skip}] {name | version} The osf expression does passive operating system fingerprinting. This expression compares some data (Window Size, MSS, options and their order, DF, and others) from packets with the SYN bit set. Table 33. Available osf attributes ┌─────────┬──────────────────────────┬────────┐ │ Name │ Description │ Type │ ├─────────┼──────────────────────────┼────────┤ │ │ │ │ │ ttl │ Do TTL checks on the │ string │ │ │ packet to determine the │ │ │ │ operating system. │ │ ├─────────┼──────────────────────────┼────────┤ │ │ │ │ │ version │ Do OS version checks on │ │ │ │ the packet. │ │ ├─────────┼──────────────────────────┼────────┤ │ │ │ │ │ name │ Name of the OS signature │ string │ │ │ to match. All signatures │ │ │ │ can be found at pf.os │ │ │ │ file. Use "unknown" for │ │ │ │ OS signatures that the │ │ │ │ expression could not │ │ │ │ detect. │ │ └─────────┴──────────────────────────┴────────┘ Available ttl values. If no TTL attribute is passed, make a true IP header and fingerprint TTL true comparison. This generally works for LANs. * loose: Check if the IP header's TTL is less than the fingerprint one. Works for globally-routable addresses. * skip: Do not compare the TTL at all. Using osf expression. # Accept packets that match the "Linux" OS genre signature without comparing TTL. table inet x { chain y { type filter hook input priority filter; policy accept; osf ttl skip name "Linux" } } FIB EXPRESSIONS fib {saddr | daddr | mark | iif | oif} [. ...] {oif | oifname | type} A fib expression queries the fib (forwarding information base) to obtain information such as the output interface index a particular address would use. The input is a tuple of elements that is used as input to the fib lookup functions. Table 34. fib expression specific types ┌─────────┬────────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├─────────┼────────────────────────┼──────────────────┤ │ │ │ │ │ oif │ Output interface index │ integer (32 bit) │ ├─────────┼────────────────────────┼──────────────────┤ │ │ │ │ │ oifname │ Output interface name │ string │ ├─────────┼────────────────────────┼──────────────────┤ │ │ │ │ │ type │ Address type │ fib_addrtype │ └─────────┴────────────────────────┴──────────────────┘ Use nft describe fib_addrtype to get a list of all address types. Using fib expressions. # drop packets without a reverse path filter prerouting fib saddr . iif oif missing drop In this example, 'saddr . iif' looks up routing information based on the source address and the input interface. oif picks the output interface index from the routing information. If no route was found for the source address/input interface combination, the output interface index is zero. In case the input interface is specified as part of the input key, the output interface index is always the same as the input interface index or zero. If only 'saddr oif' is given, then oif can be any interface index or zero. # drop packets to address not configured on incoming interface filter prerouting fib daddr . iif type != { local, broadcast, multicast } drop # perform lookup in a specific 'blackhole' table (0xdead, needs ip appropriate ip rule) filter prerouting meta mark set 0xdead fib daddr . mark type vmap { blackhole : drop, prohibit : jump prohibited, unreachable : drop } ROUTING EXPRESSIONS rt [ip | ip6] {classid | nexthop | mtu | ipsec} A routing expression refers to routing data associated with a packet. Table 35. Routing expression types ┌─────────┬──────────────────────────┬─────────────────────┐ │ Keyword │ Description │ Type │ ├─────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ classid │ Routing realm │ realm │ ├─────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ nexthop │ Routing nexthop │ ipv4_addr/ipv6_addr │ ├─────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ mtu │ TCP maximum segment size │ integer (16 bit) │ │ │ of route │ │ ├─────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ ipsec │ route via ipsec tunnel │ boolean │ │ │ or transport │ │ └─────────┴──────────────────────────┴─────────────────────┘ Table 36. Routing expression specific types ┌───────┬─────────────────────────────────┐ │ Type │ Description │ ├───────┼─────────────────────────────────┤ │ │ │ │ realm │ Routing Realm (32 bit number). │ │ │ Can be specified numerically or │ │ │ as symbolic name defined in │ │ │ /etc/iproute2/rt_realms. │ └───────┴─────────────────────────────────┘ Using routing expressions. # IP family independent rt expression filter output rt classid 10 # IP family dependent rt expressions ip filter output rt nexthop 192.168.0.1 ip6 filter output rt nexthop fd00::1 inet filter output rt ip nexthop 192.168.0.1 inet filter output rt ip6 nexthop fd00::1 # outgoing packet will be encapsulated/encrypted by ipsec filter output rt ipsec exists IPSEC EXPRESSIONS ipsec {in | out} [ spnum NUM ] {reqid | spi} ipsec {in | out} [ spnum NUM ] {ip | ip6} {saddr | daddr} An ipsec expression refers to ipsec data associated with a packet. The in or out keyword needs to be used to specify if the expression should examine inbound or outbound policies. The in keyword can be used in the prerouting, input and forward hooks. The out keyword applies to forward, output and postrouting hooks. The optional keyword spnum can be used to match a specific state in a chain, it defaults to 0. Table 37. Ipsec expression types ┌─────────┬──────────────────────────┬─────────────────────┐ │ Keyword │ Description │ Type │ ├─────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ reqid │ Request ID │ integer (32 bit) │ ├─────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ spi │ Security Parameter Index │ integer (32 bit) │ ├─────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ saddr │ Source address of the │ ipv4_addr/ipv6_addr │ │ │ tunnel │ │ ├─────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ daddr │ Destination address of │ ipv4_addr/ipv6_addr │ │ │ the tunnel │ │ └─────────┴──────────────────────────┴─────────────────────┘ Note: When using xfrm_interface, this expression is not useable in output hook as the plain packet does not traverse it with IPsec info attached - use a chain in postrouting hook instead. NUMGEN EXPRESSION numgen {inc | random} mod NUM [ offset NUM ] Create a number generator. The inc or random keywords control its operation mode: In inc mode, the last returned value is simply incremented. In random mode, a new random number is returned. The value after mod keyword specifies an upper boundary (read: modulus) which is not reached by returned numbers. The optional offset allows one to increment the returned value by a fixed offset. A typical use-case for numgen is load-balancing: Using numgen expression. # round-robin between 192.168.10.100 and 192.168.20.200: add rule nat prerouting dnat to numgen inc mod 2 map \ { 0 : 192.168.10.100, 1 : 192.168.20.200 } # probability-based with odd bias using intervals: add rule nat prerouting dnat to numgen random mod 10 map \ { 0-2 : 192.168.10.100, 3-9 : 192.168.20.200 } HASH EXPRESSIONS jhash {ip saddr | ip6 daddr | tcp dport | udp sport | ether saddr} [. ...] mod NUM [ seed NUM ] [ offset NUM ] symhash mod NUM [ offset NUM ] Use a hashing function to generate a number. The functions available are jhash, known as Jenkins Hash, and symhash, for Symmetric Hash. The jhash requires an expression to determine the parameters of the packet header to apply the hashing, concatenations are possible as well. The value after mod keyword specifies an upper boundary (read: modulus) which is not reached by returned numbers. The optional seed is used to specify an init value used as seed in the hashing function. The optional offset allows one to increment the returned value by a fixed offset. A typical use-case for jhash and symhash is load-balancing: Using hash expressions. # load balance based on source ip between 2 ip addresses: add rule nat prerouting dnat to jhash ip saddr mod 2 map \ { 0 : 192.168.10.100, 1 : 192.168.20.200 } # symmetric load balancing between 2 ip addresses: add rule nat prerouting dnat to symhash mod 2 map \ { 0 : 192.168.10.100, 1 : 192.168.20.200 } PAYLOAD EXPRESSIONS Payload expressions refer to data from the packet’s payload. ETHERNET HEADER EXPRESSION ether {daddr | saddr | type} Table 38. Ethernet header expression types ┌─────────┬─────────────────────────┬────────────┐ │ Keyword │ Description │ Type │ ├─────────┼─────────────────────────┼────────────┤ │ │ │ │ │ daddr │ Destination MAC address │ ether_addr │ ├─────────┼─────────────────────────┼────────────┤ │ │ │ │ │ saddr │ Source MAC address │ ether_addr │ ├─────────┼─────────────────────────┼────────────┤ │ │ │ │ │ type │ EtherType │ ether_type │ └─────────┴─────────────────────────┴────────────┘ VLAN HEADER EXPRESSION vlan {id | dei | pcp | type} The vlan expression is used to match on the vlan header fields. This expression will not work in the ip, ip6 and inet families, unless the vlan interface is configured with the reorder_hdr off setting. The default is reorder_hdr on which will automatically remove the vlan tag from the packet. See ip-link(8) for more information. For these families its easier to match the vlan interface name instead, using the meta iif or meta iifname expression. Table 39. VLAN header expression ┌─────────┬─────────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├─────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ id │ VLAN ID (VID) │ integer (12 bit) │ ├─────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ dei │ Drop Eligible Indicator │ integer (1 bit) │ ├─────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ pcp │ Priority code point │ integer (3 bit) │ ├─────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ type │ EtherType │ ether_type │ └─────────┴─────────────────────────┴──────────────────┘ ARP HEADER EXPRESSION arp {htype | ptype | hlen | plen | operation | saddr { ip | ether } | daddr { ip | ether } Table 40. ARP header expression ┌─────────────┬─────────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ htype │ ARP hardware type │ integer (16 bit) │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ ptype │ EtherType │ ether_type │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ hlen │ Hardware address len │ integer (8 bit) │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ plen │ Protocol address len │ integer (8 bit) │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ operation │ Operation │ arp_op │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ saddr ether │ Ethernet sender address │ ether_addr │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ daddr ether │ Ethernet target address │ ether_addr │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ saddr ip │ IPv4 sender address │ ipv4_addr │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ daddr ip │ IPv4 target address │ ipv4_addr │ └─────────────┴─────────────────────────┴──────────────────┘ IPV4 HEADER EXPRESSION ip {version | hdrlength | dscp | ecn | length | id | frag-off | ttl | protocol | checksum | saddr | daddr } Table 41. IPv4 header expression ┌───────────┬─────────────────────────┬───────────────────────┐ │ Keyword │ Description │ Type │ ├───────────┼─────────────────────────┼───────────────────────┤ │ │ │ │ │ version │ IP header version (4) │ integer (4 bit) │ ├───────────┼─────────────────────────┼───────────────────────┤ │ │ │ │ │ hdrlength │ IP header length │ integer (4 bit) FIXME │ │ │ including options │ scaling │ ├───────────┼─────────────────────────┼───────────────────────┤ │ │ │ │ │ dscp │ Differentiated Services │ dscp │ │ │ Code Point │ │ ├───────────┼─────────────────────────┼───────────────────────┤ │ │ │ │ │ ecn │ Explicit Congestion │ ecn │ │ │ Notification │ │ ├───────────┼─────────────────────────┼───────────────────────┤ │ │ │ │ │ length │ Total packet length │ integer (16 bit) │ ├───────────┼─────────────────────────┼───────────────────────┤ │ │ │ │ │ id │ IP ID │ integer (16 bit) │ ├───────────┼─────────────────────────┼───────────────────────┤ │ │ │ │ │ frag-off │ Fragment offset │ integer (16 bit) │ ├───────────┼─────────────────────────┼───────────────────────┤ │ │ │ │ │ ttl │ Time to live │ integer (8 bit) │ ├───────────┼─────────────────────────┼───────────────────────┤ │ │ │ │ │ protocol │ Upper layer protocol │ inet_proto │ ├───────────┼─────────────────────────┼───────────────────────┤ │ │ │ │ │ checksum │ IP header checksum │ integer (16 bit) │ ├───────────┼─────────────────────────┼───────────────────────┤ │ │ │ │ │ saddr │ Source address │ ipv4_addr │ ├───────────┼─────────────────────────┼───────────────────────┤ │ │ │ │ │ daddr │ Destination address │ ipv4_addr │ └───────────┴─────────────────────────┴───────────────────────┘ Careful with matching on ip length: If GRO/GSO is enabled, then the Linux kernel might aggregate several packets into one big packet that is larger than MTU. Moreover, if GRO/GSO maximum size is larger than 65535 (see man ip-link(8), specifically gro_ipv6_max_size and gso_ipv6_max_size), then ip length might be 0 for such jumbo packets. meta length allows you to match on the packet length including the IP header size. If you want to perform heuristics on the ip length field, then disable GRO/GSO. ICMP HEADER EXPRESSION icmp {type | code | checksum | id | sequence | gateway | mtu} This expression refers to ICMP header fields. When using it in inet, bridge or netdev families, it will cause an implicit dependency on IPv4 to be created. To match on unusual cases like ICMP over IPv6, one has to add an explicit meta protocol ip6 match to the rule. Table 42. ICMP header expression ┌──────────┬─────────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├──────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ type │ ICMP type field │ icmp_type │ ├──────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ code │ ICMP code field │ integer (8 bit) │ ├──────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ checksum │ ICMP checksum field │ integer (16 bit) │ ├──────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ id │ ID of echo │ integer (16 bit) │ │ │ request/response │ │ ├──────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ sequence │ sequence number of echo │ integer (16 bit) │ │ │ request/response │ │ ├──────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ gateway │ gateway of redirects │ integer (32 bit) │ ├──────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ mtu │ MTU of path MTU │ integer (16 bit) │ │ │ discovery │ │ └──────────┴─────────────────────────┴──────────────────┘ IGMP HEADER EXPRESSION igmp {type | mrt | checksum | group} This expression refers to IGMP header fields. When using it in inet, bridge or netdev families, it will cause an implicit dependency on IPv4 to be created. To match on unusual cases like IGMP over IPv6, one has to add an explicit meta protocol ip6 match to the rule. Table 43. IGMP header expression ┌──────────┬───────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├──────────┼───────────────────────┼──────────────────┤ │ │ │ │ │ type │ IGMP type field │ igmp_type │ ├──────────┼───────────────────────┼──────────────────┤ │ │ │ │ │ mrt │ IGMP maximum response │ integer (8 bit) │ │ │ time field │ │ ├──────────┼───────────────────────┼──────────────────┤ │ │ │ │ │ checksum │ IGMP checksum field │ integer (16 bit) │ ├──────────┼───────────────────────┼──────────────────┤ │ │ │ │ │ group │ Group address │ integer (32 bit) │ └──────────┴───────────────────────┴──────────────────┘ IPV6 HEADER EXPRESSION ip6 {version | dscp | ecn | flowlabel | length | nexthdr | hoplimit | saddr | daddr} This expression refers to the ipv6 header fields. Caution when using ip6 nexthdr, the value only refers to the next header, i.e. ip6 nexthdr tcp will only match if the ipv6 packet does not contain any extension headers. Packets that are fragmented or e.g. contain a routing extension headers will not be matched. Please use meta l4proto if you wish to match the real transport header and ignore any additional extension headers instead. Table 44. IPv6 header expression ┌───────────┬─────────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├───────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ version │ IP header version (6) │ integer (4 bit) │ ├───────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ dscp │ Differentiated Services │ dscp │ │ │ Code Point │ │ ├───────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ ecn │ Explicit Congestion │ ecn │ │ │ Notification │ │ ├───────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ flowlabel │ Flow label │ integer (20 bit) │ ├───────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ length │ Payload length │ integer (16 bit) │ ├───────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ nexthdr │ Nexthdr protocol │ inet_proto │ ├───────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ hoplimit │ Hop limit │ integer (8 bit) │ ├───────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ saddr │ Source address │ ipv6_addr │ ├───────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ daddr │ Destination address │ ipv6_addr │ └───────────┴─────────────────────────┴──────────────────┘ Careful with matching on ip6 length: If GRO/GSO is enabled, then the Linux kernel might aggregate several packets into one big packet that is larger than MTU. Moreover, if GRO/GSO maximum size is larger than 65535 (see man ip-link(8), specifically gro_ipv6_max_size and gso_ipv6_max_size), then ip6 length might be 0 for such jumbo packets. meta length allows you to match on the packet length including the IP header size. If you want to perform heuristics on the ip6 length field, then disable GRO/GSO. Using ip6 header expressions. # matching if first extension header indicates a fragment ip6 nexthdr ipv6-frag ICMPV6 HEADER EXPRESSION icmpv6 {type | code | checksum | parameter-problem | packet-too-big | id | sequence | max-delay | taddr | daddr} This expression refers to ICMPv6 header fields. When using it in inet, bridge or netdev families, it will cause an implicit dependency on IPv6 to be created. To match on unusual cases like ICMPv6 over IPv4, one has to add an explicit meta protocol ip match to the rule. Table 45. ICMPv6 header expression ┌───────────────────┬──────────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├───────────────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ type │ ICMPv6 type field │ icmpv6_type │ ├───────────────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ code │ ICMPv6 code field │ integer (8 bit) │ ├───────────────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ checksum │ ICMPv6 checksum field │ integer (16 bit) │ ├───────────────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ parameter-problem │ pointer to problem │ integer (32 bit) │ ├───────────────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ packet-too-big │ oversized MTU │ integer (32 bit) │ ├───────────────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ id │ ID of echo │ integer (16 bit) │ │ │ request/response │ │ ├───────────────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ sequence │ sequence number of echo │ integer (16 bit) │ │ │ request/response │ │ ├───────────────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ max-delay │ maximum response delay │ integer (16 bit) │ │ │ of MLD queries │ │ ├───────────────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ taddr │ target address of │ ipv6_addr │ │ │ neighbor solicit/advert, │ │ │ │ redirect or MLD │ │ ├───────────────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ daddr │ destination address of │ ipv6_addr │ │ │ redirect │ │ └───────────────────┴──────────────────────────┴──────────────────┘ TCP HEADER EXPRESSION tcp {sport | dport | sequence | ackseq | doff | reserved | flags | window | checksum | urgptr} Table 46. TCP header expression ┌──────────┬────────────────────────┬───────────────────────┐ │ Keyword │ Description │ Type │ ├──────────┼────────────────────────┼───────────────────────┤ │ │ │ │ │ sport │ Source port │ inet_service │ ├──────────┼────────────────────────┼───────────────────────┤ │ │ │ │ │ dport │ Destination port │ inet_service │ ├──────────┼────────────────────────┼───────────────────────┤ │ │ │ │ │ sequence │ Sequence number │ integer (32 bit) │ ├──────────┼────────────────────────┼───────────────────────┤ │ │ │ │ │ ackseq │ Acknowledgement number │ integer (32 bit) │ ├──────────┼────────────────────────┼───────────────────────┤ │ │ │ │ │ doff │ Data offset │ integer (4 bit) FIXME │ │ │ │ scaling │ ├──────────┼────────────────────────┼───────────────────────┤ │ │ │ │ │ reserved │ Reserved area │ integer (4 bit) │ ├──────────┼────────────────────────┼───────────────────────┤ │ │ │ │ │ flags │ TCP flags │ tcp_flag │ ├──────────┼────────────────────────┼───────────────────────┤ │ │ │ │ │ window │ Window │ integer (16 bit) │ ├──────────┼────────────────────────┼───────────────────────┤ │ │ │ │ │ checksum │ Checksum │ integer (16 bit) │ ├──────────┼────────────────────────┼───────────────────────┤ │ │ │ │ │ urgptr │ Urgent pointer │ integer (16 bit) │ └──────────┴────────────────────────┴───────────────────────┘ UDP HEADER EXPRESSION udp {sport | dport | length | checksum} Table 47. UDP header expression ┌──────────┬─────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├──────────┼─────────────────────┼──────────────────┤ │ │ │ │ │ sport │ Source port │ inet_service │ ├──────────┼─────────────────────┼──────────────────┤ │ │ │ │ │ dport │ Destination port │ inet_service │ ├──────────┼─────────────────────┼──────────────────┤ │ │ │ │ │ length │ Total packet length │ integer (16 bit) │ ├──────────┼─────────────────────┼──────────────────┤ │ │ │ │ │ checksum │ Checksum │ integer (16 bit) │ └──────────┴─────────────────────┴──────────────────┘ UDP-LITE HEADER EXPRESSION udplite {sport | dport | checksum} Table 48. UDP-Lite header expression ┌──────────┬──────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├──────────┼──────────────────┼──────────────────┤ │ │ │ │ │ sport │ Source port │ inet_service │ ├──────────┼──────────────────┼──────────────────┤ │ │ │ │ │ dport │ Destination port │ inet_service │ ├──────────┼──────────────────┼──────────────────┤ │ │ │ │ │ checksum │ Checksum │ integer (16 bit) │ └──────────┴──────────────────┴──────────────────┘ SCTP HEADER EXPRESSION sctp {sport | dport | vtag | checksum} sctp chunk CHUNK [ FIELD ] CHUNK := data | init | init-ack | sack | heartbeat | heartbeat-ack | abort | shutdown | shutdown-ack | error | cookie-echo | cookie-ack | ecne | cwr | shutdown-complete | asconf-ack | forward-tsn | asconf FIELD := COMMON_FIELD | DATA_FIELD | INIT_FIELD | INIT_ACK_FIELD | SACK_FIELD | SHUTDOWN_FIELD | ECNE_FIELD | CWR_FIELD | ASCONF_ACK_FIELD | FORWARD_TSN_FIELD | ASCONF_FIELD COMMON_FIELD := type | flags | length DATA_FIELD := tsn | stream | ssn | ppid INIT_FIELD := init-tag | a-rwnd | num-outbound-streams | num-inbound-streams | initial-tsn INIT_ACK_FIELD := INIT_FIELD SACK_FIELD := cum-tsn-ack | a-rwnd | num-gap-ack-blocks | num-dup-tsns SHUTDOWN_FIELD := cum-tsn-ack ECNE_FIELD := lowest-tsn CWR_FIELD := lowest-tsn ASCONF_ACK_FIELD := seqno FORWARD_TSN_FIELD := new-cum-tsn ASCONF_FIELD := seqno Table 49. SCTP header expression ┌──────────┬────────────────────────┬────────────────────────┐ │ Keyword │ Description │ Type │ ├──────────┼────────────────────────┼────────────────────────┤ │ │ │ │ │ sport │ Source port │ inet_service │ ├──────────┼────────────────────────┼────────────────────────┤ │ │ │ │ │ dport │ Destination port │ inet_service │ ├──────────┼────────────────────────┼────────────────────────┤ │ │ │ │ │ vtag │ Verification Tag │ integer (32 bit) │ ├──────────┼────────────────────────┼────────────────────────┤ │ │ │ │ │ checksum │ Checksum │ integer (32 bit) │ ├──────────┼────────────────────────┼────────────────────────┤ │ │ │ │ │ chunk │ Search chunk in packet │ without FIELD, boolean │ │ │ │ indicating existence │ └──────────┴────────────────────────┴────────────────────────┘ Table 50. SCTP chunk fields ┌──────────────────────┬───────────────┬────────────────────┬─────────────────────┐ │ Name │ Width in bits │ Chunk │ Notes │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ type │ 8 │ all │ not useful, defined │ │ │ │ │ by chunk type │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ flags │ 8 │ all │ semantics defined │ │ │ │ │ on per-chunk basis │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ length │ 16 │ all │ length of this │ │ │ │ │ chunk in bytes │ │ │ │ │ excluding padding │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ tsn │ 32 │ data │ transmission │ │ │ │ │ sequence number │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ stream │ 16 │ data │ stream identifier │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ ssn │ 16 │ data │ stream sequence │ │ │ │ │ number │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ ppid │ 32 │ data │ payload protocol │ │ │ │ │ identifier │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ init-tag │ 32 │ init, init-ack │ initiate tag │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ a-rwnd │ 32 │ init, init-ack, │ advertised receiver │ │ │ │ sack │ window credit │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ num-outbound-streams │ 16 │ init, init-ack │ number of outbound │ │ │ │ │ streams │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ num-inbound-streams │ 16 │ init, init-ack │ number of inbound │ │ │ │ │ streams │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ initial-tsn │ 32 │ init, init-ack │ initial transmit │ │ │ │ │ sequence number │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ cum-tsn-ack │ 32 │ sack, shutdown │ cumulative │ │ │ │ │ transmission │ │ │ │ │ sequence number │ │ │ │ │ acknowledged │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ num-gap-ack-blocks │ 16 │ sack │ number of Gap Ack │ │ │ │ │ Blocks included │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ num-dup-tsns │ 16 │ sack │ number of duplicate │ │ │ │ │ transmission │ │ │ │ │ sequence numbers │ │ │ │ │ received │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ lowest-tsn │ 32 │ ecne, cwr │ lowest transmission │ │ │ │ │ sequence number │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ seqno │ 32 │ asconf-ack, asconf │ sequence number │ ├──────────────────────┼───────────────┼────────────────────┼─────────────────────┤ │ │ │ │ │ │ new-cum-tsn │ 32 │ forward-tsn │ new cumulative │ │ │ │ │ transmission │ │ │ │ │ sequence number │ └──────────────────────┴───────────────┴────────────────────┴─────────────────────┘ DCCP HEADER EXPRESSION dccp {sport | dport | type} Table 51. DCCP header expression ┌─────────┬──────────────────┬──────────────┐ │ Keyword │ Description │ Type │ ├─────────┼──────────────────┼──────────────┤ │ │ │ │ │ sport │ Source port │ inet_service │ ├─────────┼──────────────────┼──────────────┤ │ │ │ │ │ dport │ Destination port │ inet_service │ ├─────────┼──────────────────┼──────────────┤ │ │ │ │ │ type │ Packet type │ dccp_pkttype │ └─────────┴──────────────────┴──────────────┘ AUTHENTICATION HEADER EXPRESSION ah {nexthdr | hdrlength | reserved | spi | sequence} Table 52. AH header expression ┌───────────┬──────────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├───────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ nexthdr │ Next header protocol │ inet_proto │ ├───────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ hdrlength │ AH Header length │ integer (8 bit) │ ├───────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ reserved │ Reserved area │ integer (16 bit) │ ├───────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ spi │ Security Parameter Index │ integer (32 bit) │ ├───────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ sequence │ Sequence number │ integer (32 bit) │ └───────────┴──────────────────────────┴──────────────────┘ ENCRYPTED SECURITY PAYLOAD HEADER EXPRESSION esp {spi | sequence} Table 53. ESP header expression ┌──────────┬──────────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├──────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ spi │ Security Parameter Index │ integer (32 bit) │ ├──────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ sequence │ Sequence number │ integer (32 bit) │ └──────────┴──────────────────────────┴──────────────────┘ IPCOMP HEADER EXPRESSION comp {nexthdr | flags | cpi} Table 54. IPComp header expression ┌─────────┬───────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├─────────┼───────────────────────┼──────────────────┤ │ │ │ │ │ nexthdr │ Next header protocol │ inet_proto │ ├─────────┼───────────────────────┼──────────────────┤ │ │ │ │ │ flags │ Flags │ bitmask │ ├─────────┼───────────────────────┼──────────────────┤ │ │ │ │ │ cpi │ compression Parameter │ integer (16 bit) │ │ │ Index │ │ └─────────┴───────────────────────┴──────────────────┘ GRE HEADER EXPRESSION gre {flags | version | protocol} gre ip {version | hdrlength | dscp | ecn | length | id | frag-off | ttl | protocol | checksum | saddr | daddr } gre ip6 {version | dscp | ecn | flowlabel | length | nexthdr | hoplimit | saddr | daddr} The gre expression is used to match on the gre header fields. This expression also allows to match on the IPv4 or IPv6 packet within the gre header. Table 55. GRE header expression ┌──────────┬──────────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├──────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ flags │ checksum, routing, key, │ integer (5 bit) │ │ │ sequence and strict │ │ │ │ source route flags │ │ ├──────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ version │ gre version field, 0 for │ integer (3 bit) │ │ │ GRE and 1 for PPTP │ │ ├──────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ protocol │ EtherType of │ integer (16 bit) │ │ │ encapsulated packet │ │ └──────────┴──────────────────────────┴──────────────────┘ Matching inner IPv4 destination address encapsulated in gre. netdev filter ingress gre ip daddr 9.9.9.9 counter GENEVE HEADER EXPRESSION geneve {vni | flags} geneve ether {daddr | saddr | type} geneve vlan {id | dei | pcp | type} geneve ip {version | hdrlength | dscp | ecn | length | id | frag-off | ttl | protocol | checksum | saddr | daddr } geneve ip6 {version | dscp | ecn | flowlabel | length | nexthdr | hoplimit | saddr | daddr} geneve tcp {sport | dport | sequence | ackseq | doff | reserved | flags | window | checksum | urgptr} geneve udp {sport | dport | length | checksum} The geneve expression is used to match on the geneve header fields. The geneve header encapsulates a ethernet frame within a udp packet. This expression requires that you restrict the matching to udp packets (usually at port 6081 according to IANA-assigned ports). Table 56. GENEVE header expression ┌──────────┬──────────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├──────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ protocol │ EtherType of │ integer (16 bit) │ │ │ encapsulated packet │ │ ├──────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ vni │ Virtual Network ID (VNI) │ integer (24 bit) │ └──────────┴──────────────────────────┴──────────────────┘ Matching inner TCP destination port encapsulated in geneve. netdev filter ingress udp dport 4789 geneve tcp dport 80 counter GRETAP HEADER EXPRESSION gretap {vni | flags} gretap ether {daddr | saddr | type} gretap vlan {id | dei | pcp | type} gretap ip {version | hdrlength | dscp | ecn | length | id | frag-off | ttl | protocol | checksum | saddr | daddr } gretap ip6 {version | dscp | ecn | flowlabel | length | nexthdr | hoplimit | saddr | daddr} gretap tcp {sport | dport | sequence | ackseq | doff | reserved | flags | window | checksum | urgptr} gretap udp {sport | dport | length | checksum} The gretap expression is used to match on the encapsulated ethernet frame within the gre header. Use the gre expression to match on the gre header fields. Matching inner TCP destination port encapsulated in gretap. netdev filter ingress gretap tcp dport 80 counter VXLAN HEADER EXPRESSION vxlan {vni | flags} vxlan ether {daddr | saddr | type} vxlan vlan {id | dei | pcp | type} vxlan ip {version | hdrlength | dscp | ecn | length | id | frag-off | ttl | protocol | checksum | saddr | daddr } vxlan ip6 {version | dscp | ecn | flowlabel | length | nexthdr | hoplimit | saddr | daddr} vxlan tcp {sport | dport | sequence | ackseq | doff | reserved | flags | window | checksum | urgptr} vxlan udp {sport | dport | length | checksum} The vxlan expression is used to match on the vxlan header fields. The vxlan header encapsulates a ethernet frame within a udp packet. This expression requires that you restrict the matching to udp packets (usually at port 4789 according to IANA-assigned ports). Table 57. VXLAN header expression ┌─────────┬──────────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├─────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ flags │ vxlan flags │ integer (8 bit) │ ├─────────┼──────────────────────────┼──────────────────┤ │ │ │ │ │ vni │ Virtual Network ID (VNI) │ integer (24 bit) │ └─────────┴──────────────────────────┴──────────────────┘ Matching inner TCP destination port encapsulated in vxlan. netdev filter ingress udp dport 4789 vxlan tcp dport 80 counter ARP HEADER EXPRESSION arp {htype | ptype | hlen | plen | operation | saddr { ip | ether } | daddr { ip | ether } Table 58. ARP header expression ┌─────────────┬─────────────────────────┬──────────────────┐ │ Keyword │ Description │ Type │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ htype │ ARP hardware type │ integer (16 bit) │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ ptype │ EtherType │ ether_type │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ hlen │ Hardware address len │ integer (8 bit) │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ plen │ Protocol address len │ integer (8 bit) │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ operation │ Operation │ arp_op │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ saddr ether │ Ethernet sender address │ ether_addr │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ daddr ether │ Ethernet target address │ ether_addr │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ saddr ip │ IPv4 sender address │ ipv4_addr │ ├─────────────┼─────────────────────────┼──────────────────┤ │ │ │ │ │ daddr ip │ IPv4 target address │ ipv4_addr │ └─────────────┴─────────────────────────┴──────────────────┘ RAW PAYLOAD EXPRESSION @base,offset,length The raw payload expression instructs to load length bits starting at offset bits. Bit 0 refers to the very first bit — in the C programming language, this corresponds to the topmost bit, i.e. 0x80 in case of an octet. They are useful to match headers that do not have a human-readable template expression yet. Note that nft will not add dependencies for Raw payload expressions. If you e.g. want to match protocol fields of a transport header with protocol number 5, you need to manually exclude packets that have a different transport header, for instance by using meta l4proto 5 before the raw expression. Table 59. Supported payload protocol bases ┌──────┬──────────────────────────────────┐ │ Base │ Description │ ├──────┼──────────────────────────────────┤ │ │ │ │ ll │ Link layer, for example the │ │ │ Ethernet header │ ├──────┼──────────────────────────────────┤ │ │ │ │ nh │ Network header, for example IPv4 │ │ │ or IPv6 │ ├──────┼──────────────────────────────────┤ │ │ │ │ th │ Transport Header, for example │ │ │ TCP │ ├──────┼──────────────────────────────────┤ │ │ │ │ ih │ Inner Header / Payload, i.e. │ │ │ after the L4 transport level │ │ │ header │ └──────┴──────────────────────────────────┘ Matching destination port of both UDP and TCP. inet filter input meta l4proto {tcp, udp} @th,16,16 { 53, 80 } The above can also be written as inet filter input meta l4proto {tcp, udp} th dport { 53, 80 } it is more convenient, but like the raw expression notation no dependencies are created or checked. It is the users responsibility to restrict matching to those header types that have a notion of ports. Otherwise, rules using raw expressions will errnously match unrelated packets, e.g. mis-interpreting ESP packets SPI field as a port. Rewrite arp packet target hardware address if target protocol address matches a given address. input meta iifname enp2s0 arp ptype 0x0800 arp htype 1 arp hlen 6 arp plen 4 @nh,192,32 0xc0a88f10 @nh,144,48 set 0x112233445566 accept EXTENSION HEADER EXPRESSIONS Extension header expressions refer to data from variable-sized protocol headers, such as IPv6 extension headers, TCP options and IPv4 options. nftables currently supports matching (finding) a given ipv6 extension header, TCP option or IPv4 option. hbh {nexthdr | hdrlength} frag {nexthdr | frag-off | more-fragments | id} rt {nexthdr | hdrlength | type | seg-left} dst {nexthdr | hdrlength} mh {nexthdr | hdrlength | checksum | type} srh {flags | tag | sid | seg-left} tcp option {eol | nop | maxseg | window | sack-perm | sack | sack0 | sack1 | sack2 | sack3 | timestamp} tcp_option_field ip option { lsrr | ra | rr | ssrr } ip_option_field The following syntaxes are valid only in a relational expression with boolean type on right-hand side for checking header existence only: exthdr {hbh | frag | rt | dst | mh} tcp option {eol | nop | maxseg | window | sack-perm | sack | sack0 | sack1 | sack2 | sack3 | timestamp} ip option { lsrr | ra | rr | ssrr } dccp option dccp_option_type Table 60. IPv6 extension headers ┌─────────┬────────────────────────┐ │ Keyword │ Description │ ├─────────┼────────────────────────┤ │ │ │ │ hbh │ Hop by Hop │ ├─────────┼────────────────────────┤ │ │ │ │ rt │ Routing Header │ ├─────────┼────────────────────────┤ │ │ │ │ frag │ Fragmentation header │ ├─────────┼────────────────────────┤ │ │ │ │ dst │ dst options │ ├─────────┼────────────────────────┤ │ │ │ │ mh │ Mobility Header │ ├─────────┼────────────────────────┤ │ │ │ │ srh │ Segment Routing Header │ └─────────┴────────────────────────┘ Table 61. TCP Options ┌───────────┬──────────────────────────┬──────────────────────┐ │ Keyword │ Description │ TCP option fields │ ├───────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ eol │ End if option list │ - │ ├───────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ nop │ 1 Byte TCP Nop padding │ - │ │ │ option │ │ ├───────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ maxseg │ TCP Maximum Segment Size │ length, size │ ├───────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ window │ TCP Window Scaling │ length, count │ ├───────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ sack-perm │ TCP SACK permitted │ length │ ├───────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ sack │ TCP Selective │ length, left, right │ │ │ Acknowledgement (alias │ │ │ │ of block 0) │ │ ├───────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ sack0 │ TCP Selective │ length, left, right │ │ │ Acknowledgement (block │ │ │ │ 0) │ │ ├───────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ sack1 │ TCP Selective │ length, left, right │ │ │ Acknowledgement (block │ │ │ │ 1) │ │ ├───────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ sack2 │ TCP Selective │ length, left, right │ │ │ Acknowledgement (block │ │ │ │ 2) │ │ ├───────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ sack3 │ TCP Selective │ length, left, right │ │ │ Acknowledgement (block │ │ │ │ 3) │ │ ├───────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ timestamp │ TCP Timestamps │ length, tsval, tsecr │ └───────────┴──────────────────────────┴──────────────────────┘ TCP option matching also supports raw expression syntax to access arbitrary options: tcp option tcp option @number,offset,length Table 62. IP Options ┌─────────┬─────────────────────┬─────────────────────────┐ │ Keyword │ Description │ IP option fields │ ├─────────┼─────────────────────┼─────────────────────────┤ │ │ │ │ │ lsrr │ Loose Source Route │ type, length, ptr, addr │ ├─────────┼─────────────────────┼─────────────────────────┤ │ │ │ │ │ ra │ Router Alert │ type, length, value │ ├─────────┼─────────────────────┼─────────────────────────┤ │ │ │ │ │ rr │ Record Route │ type, length, ptr, addr │ ├─────────┼─────────────────────┼─────────────────────────┤ │ │ │ │ │ ssrr │ Strict Source Route │ type, length, ptr, addr │ └─────────┴─────────────────────┴─────────────────────────┘ finding TCP options. filter input tcp option sack-perm exists counter matching TCP options. filter input tcp option maxseg size lt 536 matching IPv6 exthdr. ip6 filter input frag more-fragments 1 counter finding IP option. filter input ip option lsrr exists counter finding DCCP option. filter input dccp option 40 exists counter CONNTRACK EXPRESSIONS Conntrack expressions refer to meta data of the connection tracking entry associated with a packet. There are three types of conntrack expressions. Some conntrack expressions require the flow direction before the conntrack key, others must be used directly because they are direction agnostic. The packets, bytes and avgpkt keywords can be used with or without a direction. If the direction is omitted, the sum of the original and the reply direction is returned. The same is true for the zone, if a direction is given, the zone is only matched if the zone id is tied to the given direction. ct {state | direction | status | mark | expiration | helper | label | count | id} ct [original | reply] {l3proto | protocol | bytes | packets | avgpkt | zone} ct {original | reply} {proto-src | proto-dst} ct {original | reply} {ip | ip6} {saddr | daddr} The conntrack-specific types in this table are described in the sub-section CONNTRACK TYPES above. Table 63. Conntrack expressions ┌────────────┬──────────────────────────┬─────────────────────┐ │ Keyword │ Description │ Type │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ state │ State of the connection │ ct_state │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ direction │ Direction of the packet │ ct_dir │ │ │ relative to the │ │ │ │ connection │ │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ status │ Status of the connection │ ct_status │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ mark │ Connection mark │ mark │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ expiration │ Connection expiration │ time │ │ │ time │ │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ helper │ Helper associated with │ string │ │ │ the connection │ │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ label │ Connection tracking │ ct_label │ │ │ label bit or symbolic │ │ │ │ name defined in │ │ │ │ connlabel.conf in the │ │ │ │ nftables include path │ │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ l3proto │ Layer 3 protocol of the │ nf_proto │ │ │ connection │ │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ saddr │ Source address of the │ ipv4_addr/ipv6_addr │ │ │ connection for the given │ │ │ │ direction │ │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ daddr │ Destination address of │ ipv4_addr/ipv6_addr │ │ │ the connection for the │ │ │ │ given direction │ │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ protocol │ Layer 4 protocol of the │ inet_proto │ │ │ connection for the given │ │ │ │ direction │ │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ proto-src │ Layer 4 protocol source │ integer (16 bit) │ │ │ for the given direction │ │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ proto-dst │ Layer 4 protocol │ integer (16 bit) │ │ │ destination for the │ │ │ │ given direction │ │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ packets │ packet count seen in the │ integer (64 bit) │ │ │ given direction or sum │ │ │ │ of original and reply │ │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ bytes │ byte count seen, see │ integer (64 bit) │ │ │ description for packets │ │ │ │ keyword │ │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ avgpkt │ average bytes per │ integer (64 bit) │ │ │ packet, see description │ │ │ │ for packets keyword │ │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ zone │ conntrack zone │ integer (16 bit) │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ count │ number of current │ integer (32 bit) │ │ │ connections │ │ ├────────────┼──────────────────────────┼─────────────────────┤ │ │ │ │ │ id │ Connection id │ ct_id │ └────────────┴──────────────────────────┴─────────────────────┘ restrict the number of parallel connections to a server. nft add set filter ssh_flood '{ type ipv4_addr; flags dynamic; }' nft add rule filter input tcp dport 22 add @ssh_flood '{ ip saddr ct count over 2 }' reject STATEMENTS Statements represent actions to be performed. They can alter control flow (return, jump to a different chain, accept or drop the packet) or can perform actions, such as logging, rejecting a packet, etc. Statements exist in two kinds. Terminal statements unconditionally terminate evaluation of the current rule, non-terminal statements either only conditionally or never terminate evaluation of the current rule, in other words, they are passive from the ruleset evaluation perspective. There can be an arbitrary amount of non-terminal statements in a rule, but only a single terminal statement as the final statement. VERDICT STATEMENT The verdict statement alters control flow in the ruleset and issues policy decisions for packets. {accept | drop | queue | continue | return} {jump | goto} chain accept and drop are absolute verdicts — they terminate ruleset evaluation immediately. accept Terminate ruleset evaluation and accept the packet. The packet can still be dropped later by another hook, for instance accept in the forward hook still allows one to drop the packet later in the postrouting hook, or another forward base chain that has a higher priority number and is evaluated afterwards in the processing pipeline. drop Terminate ruleset evaluation and drop the packet. The drop occurs instantly, no further chains or hooks are evaluated. It is not possible to accept the packet in a later chain again, as those are not evaluated anymore for the packet. queue Terminate ruleset evaluation and queue the packet to userspace. Userspace must provide a drop or accept verdict. In case of accept, processing resumes with the next base chain hook, not the rule following the queue verdict. continue Continue ruleset evaluation with the next rule. This is the default behaviour in case a rule issues no verdict. return Return from the current chain and continue evaluation at the next rule in the last chain. If issued in a base chain, it is equivalent to the base chain policy. jump chain Continue evaluation at the first rule in chain. The current position in the ruleset is pushed to a call stack and evaluation will continue there when the new chain is entirely evaluated or a return verdict is issued. In case an absolute verdict is issued by a rule in the chain, ruleset evaluation terminates immediately and the specific action is taken. goto chain Similar to jump, but the current position is not pushed to the call stack, meaning that after the new chain evaluation will continue at the last chain instead of the one containing the goto statement. Using verdict statements. # process packets from eth0 and the internal network in from_lan # chain, drop all packets from eth0 with different source addresses. filter input iif eth0 ip saddr 192.168.0.0/24 jump from_lan filter input iif eth0 drop PAYLOAD STATEMENT payload_expression set value The payload statement alters packet content. It can be used for example to set ip DSCP (diffserv) header field or ipv6 flow labels. route some packets instead of bridging. # redirect tcp:http from 192.160.0.0/16 to local machine for routing instead of bridging # assumes 00:11:22:33:44:55 is local MAC address. bridge input meta iif eth0 ip saddr 192.168.0.0/16 tcp dport 80 meta pkttype set unicast ether daddr set 00:11:22:33:44:55 Set IPv4 DSCP header field. ip forward ip dscp set 42 EXTENSION HEADER STATEMENT extension_header_expression set value The extension header statement alters packet content in variable-sized headers. This can currently be used to alter the TCP Maximum segment size of packets, similar to the TCPMSS target in iptables. change tcp mss. tcp flags syn tcp option maxseg size set 1360 # set a size based on route information: tcp flags syn tcp option maxseg size set rt mtu You can also remove tcp options via reset keyword. remove tcp option. tcp flags syn reset tcp option sack-perm LOG STATEMENT log [prefix quoted_string] [level syslog-level] [flags log-flags] log group nflog_group [prefix quoted_string] [queue-threshold value] [snaplen size] log level audit The log statement enables logging of matching packets. When this statement is used from a rule, the Linux kernel will print some information on all matching packets, such as header fields, via the kernel log (where it can be read with dmesg(1) or read in the syslog). In the second form of invocation (if nflog_group is specified), the Linux kernel will pass the packet to nfnetlink_log which will send the log through a netlink socket to the specified group. One userspace process may subscribe to the group to receive the logs, see man(8) ulogd for the Netfilter userspace log daemon and libnetfilter_log documentation for details in case you would like to develop a custom program to digest your logs. In the third form of invocation (if level audit is specified), the Linux kernel writes a message into the audit buffer suitably formatted for reading with auditd. Therefore no further formatting options (such as prefix or flags) are allowed in this mode. This is a non-terminating statement, so the rule evaluation continues after the packet is logged. Table 64. log statement options ┌─────────────────┬──────────────────────────┬──────────────────────────┐ │ Keyword │ Description │ Type │ ├─────────────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ prefix │ Log message prefix │ quoted string │ ├─────────────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ level │ Syslog level of logging │ string: emerg, alert, │ │ │ │ crit, err, warn │ │ │ │ [default], notice, info, │ │ │ │ debug, audit │ ├─────────────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ group │ NFLOG group to send │ unsigned integer (16 │ │ │ messages to │ bit) │ ├─────────────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ snaplen │ Length of packet payload │ unsigned integer (32 │ │ │ to include in netlink │ bit) │ │ │ message │ │ ├─────────────────┼──────────────────────────┼──────────────────────────┤ │ │ │ │ │ queue-threshold │ Number of packets to │ unsigned integer (32 │ │ │ queue inside the kernel │ bit) │ │ │ before sending them to │ │ │ │ userspace │ │ └─────────────────┴──────────────────────────┴──────────────────────────┘ Table 65. log-flags ┌──────────────┬─────────────────────────────────┐ │ Flag │ Description │ ├──────────────┼─────────────────────────────────┤ │ │ │ │ tcp sequence │ Log TCP sequence numbers. │ ├──────────────┼─────────────────────────────────┤ │ │ │ │ tcp options │ Log options from the TCP packet │ │ │ header. │ ├──────────────┼─────────────────────────────────┤ │ │ │ │ ip options │ Log options from the IP/IPv6 │ │ │ packet header. │ ├──────────────┼─────────────────────────────────┤ │ │ │ │ skuid │ Log the userid of the process │ │ │ which generated the packet. │ ├──────────────┼─────────────────────────────────┤ │ │ │ │ ether │ Decode MAC addresses and │ │ │ protocol. │ ├──────────────┼─────────────────────────────────┤ │ │ │ │ all │ Enable all log flags listed │ │ │ above. │ └──────────────┴─────────────────────────────────┘ Using log statement. # log the UID which generated the packet and ip options ip filter output log flags skuid flags ip options # log the tcp sequence numbers and tcp options from the TCP packet ip filter output log flags tcp sequence,options # enable all supported log flags ip6 filter output log flags all REJECT STATEMENT reject [ with REJECT_WITH ] REJECT_WITH := icmp icmp_code | icmpv6 icmpv6_code | icmpx icmpx_code | tcp reset A reject statement is used to send back an error packet in response to the matched packet otherwise it is equivalent to drop so it is a terminating statement, ending rule traversal. This statement is only valid in base chains using the input, forward or output hooks, and user-defined chains which are only called from those chains. Table 66. different ICMP reject variants are meant for use in different table families ┌─────────┬────────┬─────────────┐ │ Variant │ Family │ Type │ ├─────────┼────────┼─────────────┤ │ │ │ │ │ icmp │ ip │ icmp_code │ ├─────────┼────────┼─────────────┤ │ │ │ │ │ icmpv6 │ ip6 │ icmpv6_code │ ├─────────┼────────┼─────────────┤ │ │ │ │ │ icmpx │ inet │ icmpx_code │ └─────────┴────────┴─────────────┘ For a description of the different types and a list of supported keywords refer to DATA TYPES section above. The common default reject value is port-unreachable. Note that in bridge family, reject statement is only allowed in base chains which hook into input or prerouting. COUNTER STATEMENT A counter statement sets the hit count of packets along with the number of bytes. counter packets number bytes number counter { packets number | bytes number } CONNTRACK STATEMENT The conntrack statement can be used to set the conntrack mark and conntrack labels. ct {mark | event | label | zone} set value The ct statement sets meta data associated with a connection. The zone id has to be assigned before a conntrack lookup takes place, i.e. this has to be done in prerouting and possibly output (if locally generated packets need to be placed in a distinct zone), with a hook priority of raw (-300). Unlike iptables, where the helper assignment happens in the raw table, the helper needs to be assigned after a conntrack entry has been found, i.e. it will not work when used with hook priorities equal or before -200. Table 67. Conntrack statement types ┌─────────┬──────────────────────────┬──────────────────────┐ │ Keyword │ Description │ Value │ ├─────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ event │ conntrack event bits │ bitmask, integer (32 │ │ │ │ bit) │ ├─────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ helper │ name of ct helper object │ quoted string │ │ │ to assign to the │ │ │ │ connection │ │ ├─────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ mark │ Connection tracking mark │ mark │ ├─────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ label │ Connection tracking │ label │ │ │ label │ │ ├─────────┼──────────────────────────┼──────────────────────┤ │ │ │ │ │ zone │ conntrack zone │ integer (16 bit) │ └─────────┴──────────────────────────┴──────────────────────┘ save packet nfmark in conntrack. ct mark set meta mark set zone mapped via interface. table inet raw { chain prerouting { type filter hook prerouting priority raw; ct zone set iif map { "eth1" : 1, "veth1" : 2 } } chain output { type filter hook output priority raw; ct zone set oif map { "eth1" : 1, "veth1" : 2 } } } restrict events reported by ctnetlink. ct event set new,related,destroy NOTRACK STATEMENT The notrack statement allows one to disable connection tracking for certain packets. notrack Note that for this statement to be effective, it has to be applied to packets before a conntrack lookup happens. Therefore, it needs to sit in a chain with either prerouting or output hook and a hook priority of -300 (raw) or less. See SYNPROXY STATEMENT for an example usage. META STATEMENT A meta statement sets the value of a meta expression. The existing meta fields are: priority, mark, pkttype, nftrace. meta {mark | priority | pkttype | nftrace | broute} set value A meta statement sets meta data associated with a packet. Table 68. Meta statement types ┌──────────┬────────────────────────┬───────────┐ │ Keyword │ Description │ Value │ ├──────────┼────────────────────────┼───────────┤ │ │ │ │ │ priority │ TC packet priority │ tc_handle │ ├──────────┼────────────────────────┼───────────┤ │ │ │ │ │ mark │ Packet mark │ mark │ ├──────────┼────────────────────────┼───────────┤ │ │ │ │ │ pkttype │ packet type │ pkt_type │ ├──────────┼────────────────────────┼───────────┤ │ │ │ │ │ nftrace │ ruleset packet tracing │ 0, 1 │ │ │ on/off. Use monitor │ │ │ │ trace command to watch │ │ │ │ traces │ │ ├──────────┼────────────────────────┼───────────┤ │ │ │ │ │ broute │ broute on/off. packets │ 0, 1 │ │ │ are routed instead of │ │ │ │ being bridged │ │ └──────────┴────────────────────────┴───────────┘ LIMIT STATEMENT limit rate [over] packet_number / TIME_UNIT [burst packet_number packets] limit rate [over] byte_number BYTE_UNIT / TIME_UNIT [burst byte_number BYTE_UNIT] TIME_UNIT := second | minute | hour | day BYTE_UNIT := bytes | kbytes | mbytes A limit statement matches at a limited rate using a token bucket filter. A rule using this statement will match until this limit is reached. It can be used in combination with the log statement to give limited logging. The optional over keyword makes it match over the specified rate. The burst value influences the bucket size, i.e. jitter tolerance. With packet-based limit, the bucket holds exactly burst packets, by default five. If you specify packet burst, it must be a non-zero value. With byte-based limit, the bucket’s minimum size is the given rate’s byte value and the burst value adds to that, by default zero bytes. Table 69. limit statement values ┌───────────────┬───────────────────┬──────────────────────┐ │ Value │ Description │ Type │ ├───────────────┼───────────────────┼──────────────────────┤ │ │ │ │ │ packet_number │ Number of packets │ unsigned integer (32 │ │ │ │ bit) │ ├───────────────┼───────────────────┼──────────────────────┤ │ │ │ │ │ byte_number │ Number of bytes │ unsigned integer (32 │ │ │ │ bit) │ └───────────────┴───────────────────┴──────────────────────┘ NAT STATEMENTS snat [[ip | ip6] [ prefix ] to] ADDR_SPEC [:PORT_SPEC] [FLAGS] dnat [[ip | ip6] [ prefix ] to] ADDR_SPEC [:PORT_SPEC] [FLAGS] masquerade [to :PORT_SPEC] [FLAGS] redirect [to :PORT_SPEC] [FLAGS] ADDR_SPEC := address | address - address PORT_SPEC := port | port - port FLAGS := FLAG [, FLAGS] FLAG := persistent | random | fully-random The nat statements are only valid from nat chain types. The snat and masquerade statements specify that the source address of the packet should be modified. While snat is only valid in the postrouting and input chains, masquerade makes sense only in postrouting. The dnat and redirect statements are only valid in the prerouting and output chains, they specify that the destination address of the packet should be modified. You can use non-base chains which are called from base chains of nat chain type too. All future packets in this connection will also be mangled, and rules should cease being examined. The masquerade statement is a special form of snat which always uses the outgoing interface’s IP address to translate to. It is particularly useful on gateways with dynamic (public) IP addresses. The redirect statement is a special form of dnat which always translates the destination address to the local host’s one. It comes in handy if one only wants to alter the destination port of incoming traffic on different interfaces. When used in the inet family (available with kernel 5.2), the dnat and snat statements require the use of the ip and ip6 keyword in case an address is provided, see the examples below. Before kernel 4.18 nat statements require both prerouting and postrouting base chains to be present since otherwise packets on the return path won’t be seen by netfilter and therefore no reverse translation will take place. The optional prefix keyword allows to map to map n source addresses to n destination addresses. See Advanced NAT examples below. Table 70. NAT statement values ┌────────────┬──────────────────────────┬─────────────────────────┐ │ Expression │ Description │ Type │ ├────────────┼──────────────────────────┼─────────────────────────┤ │ │ │ │ │ address │ Specifies that the │ ipv4_addr, ipv6_addr, │ │ │ source/destination │ e.g. abcd::1234, or you │ │ │ address of the packet │ can use a mapping, e.g. │ │ │ should be modified. You │ meta mark map { 10 : │ │ │ may specify a mapping to │ 192.168.1.2, 20 : │ │ │ relate a list of tuples │ 192.168.1.3 } │ │ │ composed of arbitrary │ │ │ │ expression key with │ │ │ │ address value. │ │ ├────────────┼──────────────────────────┼─────────────────────────┤ │ │ │ │ │ port │ Specifies that the │ port number (16 bit) │ │ │ source/destination port │ │ │ │ of the packet should be │ │ │ │ modified. │ │ └────────────┴──────────────────────────┴─────────────────────────┘ Table 71. NAT statement flags ┌──────────────┬──────────────────────────────────┐ │ Flag │ Description │ ├──────────────┼──────────────────────────────────┤ │ │ │ │ persistent │ Gives a client the same │ │ │ source-/destination-address for │ │ │ each connection. │ ├──────────────┼──────────────────────────────────┤ │ │ │ │ random │ In kernel 5.0 and newer this is │ │ │ the same as fully-random. In │ │ │ earlier kernels the port mapping │ │ │ will be randomized using a │ │ │ seeded MD5 hash mix using source │ │ │ and destination address and │ │ │ destination port. │ ├──────────────┼──────────────────────────────────┤ │ │ │ │ fully-random │ If used then port mapping is │ │ │ generated based on a 32-bit │ │ │ pseudo-random algorithm. │ └──────────────┴──────────────────────────────────┘ Using NAT statements. # create a suitable table/chain setup for all further examples add table nat add chain nat prerouting { type nat hook prerouting priority dstnat; } add chain nat postrouting { type nat hook postrouting priority srcnat; } # translate source addresses of all packets leaving via eth0 to address 1.2.3.4 add rule nat postrouting oif eth0 snat to 1.2.3.4 # redirect all traffic entering via eth0 to destination address 192.168.1.120 add rule nat prerouting iif eth0 dnat to 192.168.1.120 # translate source addresses of all packets leaving via eth0 to whatever # locally generated packets would use as source to reach the same destination add rule nat postrouting oif eth0 masquerade # redirect incoming TCP traffic for port 22 to port 2222 add rule nat prerouting tcp dport 22 redirect to :2222 # inet family: # handle ip dnat: add rule inet nat prerouting dnat ip to 10.0.2.99 # handle ip6 dnat: add rule inet nat prerouting dnat ip6 to fe80::dead # this masquerades both ipv4 and ipv6: add rule inet nat postrouting meta oif ppp0 masquerade Advanced NAT examples. # map prefixes in one network to that of another, e.g. 10.141.11.4 is mangled to 192.168.2.4, # 10.141.11.5 is mangled to 192.168.2.5 and so on. add rule nat postrouting snat ip prefix to ip saddr map { 10.141.11.0/24 : 192.168.2.0/24 } # map a source address, source port combination to a pool of destination addresses and ports: add rule nat postrouting dnat to ip saddr . tcp dport map { 192.168.1.2 . 80 : 10.141.10.2-10.141.10.5 . 8888-8999 } # The above example generates the following NAT expression: # # [ nat dnat ip addr_min reg 1 addr_max reg 10 proto_min reg 9 proto_max reg 11 ] # # which expects to obtain the following tuple: # IP address (min), source port (min), IP address (max), source port (max) # to be obtained from the map. The given addresses and ports are inclusive. # This also works with named maps and in combination with both concatenations and ranges: table ip nat { map ipportmap { typeof ip saddr : interval ip daddr . tcp dport flags interval elements = { 192.168.1.2 : 10.141.10.1-10.141.10.3 . 8888-8999, 192.168.2.0/24 : 10.141.11.5-10.141.11.20 . 8888-8999 } } chain prerouting { type nat hook prerouting priority dstnat; policy accept; ip protocol tcp dnat ip to ip saddr map @ipportmap } } @ipportmap maps network prefixes to a range of hosts and ports. The new destination is taken from the range provided by the map element. Same for the destination port. Note the use of the "interval" keyword in the typeof description. This is required so nftables knows that it has to ask for twice the amount of storage for each key-value pair in the map. ": ipv4_addr . inet_service" would allow associating one address and one port with each key. But for this case, for each key, two addresses and two ports (The minimum and maximum values for both) have to be stored. TPROXY STATEMENT Tproxy redirects the packet to a local socket without changing the packet header in any way. If any of the arguments is missing the data of the incoming packet is used as parameter. Tproxy matching requires another rule that ensures the presence of transport protocol header is specified. tproxy to address:port tproxy to {address | :port} This syntax can be used in ip/ip6 tables where network layer protocol is obvious. Either IP address or port can be specified, but at least one of them is necessary. tproxy {ip | ip6} to address[:port] tproxy to :port This syntax can be used in inet tables. The ip/ip6 parameter defines the family the rule will match. The address parameter must be of this family. When only port is defined, the address family should not be specified. In this case the rule will match for both families. Table 72. tproxy attributes ┌─────────┬─────────────────────────────────┐ │ Name │ Description │ ├─────────┼─────────────────────────────────┤ │ │ │ │ address │ IP address the listening socket │ │ │ with IP_TRANSPARENT option is │ │ │ bound to. │ ├─────────┼─────────────────────────────────┤ │ │ │ │ port │ Port the listening socket with │ │ │ IP_TRANSPARENT option is bound │ │ │ to. │ └─────────┴─────────────────────────────────┘ Example ruleset for tproxy statement. table ip x { chain y { type filter hook prerouting priority mangle; policy accept; tcp dport ntp tproxy to 1.1.1.1 udp dport ssh tproxy to :2222 } } table ip6 x { chain y { type filter hook prerouting priority mangle; policy accept; tcp dport ntp tproxy to [dead::beef] udp dport ssh tproxy to :2222 } } table inet x { chain y { type filter hook prerouting priority mangle; policy accept; tcp dport 321 tproxy to :ssh tcp dport 99 tproxy ip to 1.1.1.1:999 udp dport 155 tproxy ip6 to [dead::beef]:smux } } SYNPROXY STATEMENT This statement will process TCP three-way-handshake parallel in netfilter context to protect either local or backend system. This statement requires connection tracking because sequence numbers need to be translated. synproxy [mss mss_value] [wscale wscale_value] [SYNPROXY_FLAGS] Table 73. synproxy statement attributes ┌────────┬─────────────────────────────────┐ │ Name │ Description │ ├────────┼─────────────────────────────────┤ │ │ │ │ mss │ Maximum segment size announced │ │ │ to clients. This must match the │ │ │ backend. │ ├────────┼─────────────────────────────────┤ │ │ │ │ wscale │ Window scale announced to │ │ │ clients. This must match the │ │ │ backend. │ └────────┴─────────────────────────────────┘ Table 74. synproxy statement flags ┌───────────┬──────────────────────────────────┐ │ Flag │ Description │ ├───────────┼──────────────────────────────────┤ │ │ │ │ sack-perm │ Pass client selective │ │ │ acknowledgement option to │ │ │ backend (will be disabled if not │ │ │ present). │ ├───────────┼──────────────────────────────────┤ │ │ │ │ timestamp │ Pass client timestamp option to │ │ │ backend (will be disabled if not │ │ │ present, also needed for │ │ │ selective acknowledgement and │ │ │ window scaling). │ └───────────┴──────────────────────────────────┘ Example ruleset for synproxy statement. Determine tcp options used by backend, from an external system tcpdump -pni eth0 -c 1 'tcp[tcpflags] == (tcp-syn|tcp-ack)' port 80 & telnet 192.0.2.42 80 18:57:24.693307 IP 192.0.2.42.80 > 192.0.2.43.48757: Flags [S.], seq 360414582, ack 788841994, win 14480, options [mss 1460,sackOK, TS val 1409056151 ecr 9690221, nop,wscale 9], length 0 Switch tcp_loose mode off, so conntrack will mark out-of-flow packets as state INVALID. echo 0 > /proc/sys/net/netfilter/nf_conntrack_tcp_loose Make SYN packets untracked. table ip x { chain y { type filter hook prerouting priority raw; policy accept; tcp flags syn notrack } } Catch UNTRACKED (SYN packets) and INVALID (3WHS ACK packets) states and send them to SYNPROXY. This rule will respond to SYN packets with SYN+ACK syncookies, create ESTABLISHED for valid client response (3WHS ACK packets) and drop incorrect cookies. Flags combinations not expected during 3WHS will not match and continue (e.g. SYN+FIN, SYN+ACK). Finally, drop invalid packets, this will be out-of-flow packets that were not matched by SYNPROXY. table ip x { chain z { type filter hook input priority filter; policy accept; ct state invalid, untracked synproxy mss 1460 wscale 9 timestamp sack-perm ct state invalid drop } } FLOW STATEMENT A flow statement allows us to select what flows you want to accelerate forwarding through layer 3 network stack bypass. You have to specify the flowtable name where you want to offload this flow. flow add @flowtable QUEUE STATEMENT This statement passes the packet to userspace using the nfnetlink_queue handler. The packet is put into the queue identified by its 16-bit queue number. Userspace can inspect and modify the packet if desired. Userspace must then drop or re-inject the packet into the kernel. See libnetfilter_queue documentation for details. queue [flags QUEUE_FLAGS] [to queue_number] queue [flags QUEUE_FLAGS] [to queue_number_from - queue_number_to] queue [flags QUEUE_FLAGS] [to QUEUE_EXPRESSION ] QUEUE_FLAGS := QUEUE_FLAG [, QUEUE_FLAGS] QUEUE_FLAG := bypass | fanout QUEUE_EXPRESSION := numgen | hash | symhash | MAP STATEMENT QUEUE_EXPRESSION can be used to compute a queue number at run-time with the hash or numgen expressions. It also allows one to use the map statement to assign fixed queue numbers based on external inputs such as the source ip address or interface names. Table 75. queue statement values ┌───────────────────┬─────────────────────────┬──────────────────────┐ │ Value │ Description │ Type │ ├───────────────────┼─────────────────────────┼──────────────────────┤ │ │ │ │ │ queue_number │ Sets queue number, │ unsigned integer (16 │ │ │ default is 0. │ bit) │ ├───────────────────┼─────────────────────────┼──────────────────────┤ │ │ │ │ │ queue_number_from │ Sets initial queue in │ unsigned integer (16 │ │ │ the range, if fanout is │ bit) │ │ │ used. │ │ ├───────────────────┼─────────────────────────┼──────────────────────┤ │ │ │ │ │ queue_number_to │ Sets closing queue in │ unsigned integer (16 │ │ │ the range, if fanout is │ bit) │ │ │ used. │ │ └───────────────────┴─────────────────────────┴──────────────────────┘ Table 76. queue statement flags ┌────────┬───────────────────────────────┐ │ Flag │ Description │ ├────────┼───────────────────────────────┤ │ │ │ │ bypass │ Let packets go through if │ │ │ userspace application cannot │ │ │ back off. Before using this │ │ │ flag, read libnetfilter_queue │ │ │ documentation for performance │ │ │ tuning recommendations. │ ├────────┼───────────────────────────────┤ │ │ │ │ fanout │ Distribute packets between │ │ │ several queues. │ └────────┴───────────────────────────────┘ DUP STATEMENT The dup statement is used to duplicate a packet and send the copy to a different destination. dup to device dup to address device device Table 77. Dup statement values ┌────────────┬─────────────────────────┬──────────────────────────┐ │ Expression │ Description │ Type │ ├────────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ address │ Specifies that the copy │ ipv4_addr, ipv6_addr, │ │ │ of the packet should be │ e.g. abcd::1234, or you │ │ │ sent to a new gateway. │ can use a mapping, e.g. │ │ │ │ ip saddr map { │ │ │ │ 192.168.1.2 : 10.1.1.1 } │ ├────────────┼─────────────────────────┼──────────────────────────┤ │ │ │ │ │ device │ Specifies that the copy │ string │ │ │ should be transmitted │ │ │ │ via device. │ │ └────────────┴─────────────────────────┴──────────────────────────┘ Using the dup statement. # send to machine with ip address 10.2.3.4 on eth0 ip filter forward dup to 10.2.3.4 device "eth0" # copy raw frame to another interface netdev ingress dup to "eth0" dup to "eth0" # combine with map dst addr to gateways dup to ip daddr map { 192.168.7.1 : "eth0", 192.168.7.2 : "eth1" } FWD STATEMENT The fwd statement is used to redirect a raw packet to another interface. It is only available in the netdev family ingress and egress hooks. It is similar to the dup statement except that no copy is made. You can also specify the address of the next hop and the device to forward the packet to. This updates the source and destination MAC address of the packet by transmitting it through the neighboring layer. This also decrements the ttl field of the IP packet. This provides a way to effectively bypass the classical forwarding path, thus skipping the fib (forwarding information base) lookup. fwd to device fwd [ip | ip6] to address device device Using the fwd statement. # redirect raw packet to device netdev ingress fwd to "eth0" # forward packet to next hop 192.168.200.1 via eth0 device netdev ingress ether saddr set fwd ip to 192.168.200.1 device "eth0" SET STATEMENT The set statement is used to dynamically add or update elements in a set from the packet path. The set setname must already exist in the given table and must have been created with one or both of the dynamic and the timeout flags. The dynamic flag is required if the set statement expression includes a stateful object. The timeout flag is implied if the set is created with a timeout, and is required if the set statement updates elements, rather than adding them. Furthermore, these sets should specify both a maximum set size (to prevent memory exhaustion), and their elements should have a timeout (so their number will not grow indefinitely) either from the set definition or from the statement that adds or updates them. The set statement can be used to e.g. create dynamic blacklists. Dynamic updates are also supported with maps. In this case, the add or update rule needs to provide both the key and the data element (value), separated via :. {add | update} @setname { expression [timeout timeout] [comment string] } Example for simple blacklist. # declare a set, bound to table "filter", in family "ip". # Timeout and size are mandatory because we will add elements from packet path. # Entries will timeout after one minute, after which they might be # re-added if limit condition persists. nft add set ip filter blackhole \ "{ type ipv4_addr; flags dynamic; timeout 1m; size 65536; }" # declare a set to store the limit per saddr. # This must be separate from blackhole since the timeout is different nft add set ip filter flood \ "{ type ipv4_addr; flags dynamic; timeout 10s; size 128000; }" # whitelist internal interface. nft add rule ip filter input meta iifname "internal" accept # drop packets coming from blacklisted ip addresses. nft add rule ip filter input ip saddr @blackhole counter drop # add source ip addresses to the blacklist if more than 10 tcp connection # requests occurred per second and ip address. nft add rule ip filter input tcp flags syn tcp dport ssh \ add @flood { ip saddr limit rate over 10/second } \ add @blackhole { ip saddr } \ drop # inspect state of the sets. nft list set ip filter flood nft list set ip filter blackhole # manually add two addresses to the blackhole. nft add element filter blackhole { 10.2.3.4, 10.23.1.42 } MAP STATEMENT The map statement is used to lookup data based on some specific input key. expression map { MAP_ELEMENTS } MAP_ELEMENTS := MAP_ELEMENT [, MAP_ELEMENTS] MAP_ELEMENT := key : value The key is a value returned by expression. Using the map statement. # select DNAT target based on TCP dport: # connections to port 80 are redirected to 192.168.1.100, # connections to port 8888 are redirected to 192.168.1.101 nft add rule ip nat prerouting dnat tcp dport map { 80 : 192.168.1.100, 8888 : 192.168.1.101 } # source address based SNAT: # packets from net 192.168.1.0/24 will appear as originating from 10.0.0.1, # packets from net 192.168.2.0/24 will appear as originating from 10.0.0.2 nft add rule ip nat postrouting snat to ip saddr map { 192.168.1.0/24 : 10.0.0.1, 192.168.2.0/24 : 10.0.0.2 } VMAP STATEMENT The verdict map (vmap) statement works analogous to the map statement, but contains verdicts as values. expression vmap { VMAP_ELEMENTS } VMAP_ELEMENTS := VMAP_ELEMENT [, VMAP_ELEMENTS] VMAP_ELEMENT := key : verdict Using the vmap statement. # jump to different chains depending on layer 4 protocol type: nft add rule ip filter input ip protocol vmap { tcp : jump tcp-chain, udp : jump udp-chain , icmp : jump icmp-chain } XT STATEMENT This represents an xt statement from xtables compat interface. It is a fallback if translation is not available or not complete. xt TYPE NAME TYPE := match | target | watcher Seeing this means the ruleset (or parts of it) were created by iptables-nft and one should use that to manage it. BEWARE: nftables won’t restore these statements. ADDITIONAL COMMANDS These are some additional commands included in nft. MONITOR The monitor command allows you to listen to Netlink events produced by the nf_tables subsystem. These are either related to creation and deletion of objects or to packets for which meta nftrace was enabled. When they occur, nft will print to stdout the monitored events in either JSON or native nft format. monitor [new | destroy] MONITOR_OBJECT monitor trace MONITOR_OBJECT := tables | chains | sets | rules | elements | ruleset To filter events related to a concrete object, use one of the keywords in MONITOR_OBJECT. To filter events related to a concrete action, use keyword new or destroy. The second form of invocation takes no further options and exclusively prints events generated for packets with nftrace enabled. Hit ^C to finish the monitor operation. Listen to all events, report in native nft format. % nft monitor Listen to deleted rules, report in JSON format. % nft -j monitor destroy rules Listen to both new and destroyed chains, in native nft format. % nft monitor chains Listen to ruleset events such as table, chain, rule, set, counters and quotas, in native nft format. % nft monitor ruleset Trace incoming packets from host 10.0.0.1. % nft add rule filter input ip saddr 10.0.0.1 meta nftrace set 1 % nft monitor trace ERROR REPORTING When an error is detected, nft shows the line(s) containing the error, the position of the erroneous parts in the input stream and marks up the erroneous parts using carets (^). If the error results from the combination of two expressions or statements, the part imposing the constraints which are violated is marked using tildes (~). For errors returned by the kernel, nft cannot detect which parts of the input caused the error and the entire command is marked. Error caused by single incorrect expression. <cmdline>:1:19-22: Error: Interface does not exist filter output oif eth0 ^^^^ Error caused by invalid combination of two expressions. <cmdline>:1:28-36: Error: Right hand side of relational expression (==) must be constant filter output tcp dport == tcp dport ~~ ^^^^^^^^^ Error returned by the kernel. <cmdline>:0:0-23: Error: Could not process rule: Operation not permitted filter output oif wlan0 ^^^^^^^^^^^^^^^^^^^^^^^ EXIT STATUS On success, nft exits with a status of 0. Unspecified errors cause it to exit with a status of 1, memory allocation errors with a status of 2, unable to open Netlink socket with 3. SEE ALSO libnftables(3), libnftables-json(5), iptables(8), ip6tables(8), arptables(8), ebtables(8), ip(8), tc(8) There is an official wiki at: https://wiki.nftables.org AUTHORS nftables was written by Patrick McHardy and Pablo Neira Ayuso, among many other contributors from the Netfilter community. COPYRIGHT Copyright © 2008-2014 Patrick McHardy <[email protected]> Copyright © 2013-2018 Pablo Neira Ayuso <[email protected]> nftables is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This documentation is licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 license, CC BY-SA 4.0 http://creativecommons.org/licenses/by-sa/4.0/. 10/11/2023 NFT(8)

March 13, 2025

gitコマンドメモ

はじめに よく使うが、man gitをメモしたいので記事作成。 man gitより引用 GIT(1) Git Manual GIT(1) NAME git - the stupid content tracker SYNOPSIS git [-v | --version] [-h | --help] [-C <path>] [-c <name>=<value>] [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path] [-p|--paginate|-P|--no-pager] [--no-replace-objects] [--bare] [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>] [--config-env=<name>=<envvar>] <command> [<args>] DESCRIPTION Git is a fast, scalable, distributed revision control system with an unusually rich command set that provides both high-level operations and full access to internals. See gittutorial(7) to get started, then see giteveryday(7) for a useful minimum set of commands. The Git User’s Manual[1] has a more in-depth introduction. After you mastered the basic concepts, you can come back to this page to learn what commands Git offers. You can learn more about individual Git commands with "git help command". gitcli(7) manual page gives you an overview of the command-line command syntax. A formatted and hyperlinked copy of the latest Git documentation can be viewed at https://git.github.io/htmldocs/git.html or https://git-scm.com/docs. OPTIONS -v, --version Prints the Git suite version that the git program came from. This option is internally converted to git version ... and accepts the same options as the git-version(1) command. If --help is also given, it takes precedence over --version. -h, --help Prints the synopsis and a list of the most commonly used commands. If the option --all or -a is given then all available commands are printed. If a Git command is named this option will bring up the manual page for that command. Other options are available to control how the manual page is displayed. See git-help(1) for more information, because git --help ... is converted internally into git help .... -C <path> Run as if git was started in <path> instead of the current working directory. When multiple -C options are given, each subsequent non-absolute -C <path> is interpreted relative to the preceding -C <path>. If <path> is present but empty, e.g. -C "", then the current working directory is left unchanged. This option affects options that expect path name like --git-dir and --work-tree in that their interpretations of the path names would be made relative to the working directory caused by the -C option. For example the following invocations are equivalent: git --git-dir=a.git --work-tree=b -C c status git --git-dir=c/a.git --work-tree=c/b status -c <name>=<value> Pass a configuration parameter to the command. The value given will override values from configuration files. The <name> is expected in the same format as listed by git config (subkeys separated by dots). Note that omitting the = in git -c foo.bar ... is allowed and sets foo.bar to the boolean true value (just like [foo]bar would in a config file). Including the equals but with an empty value (like git -c foo.bar= ...) sets foo.bar to the empty string which git config --type=bool will convert to false. --config-env=<name>=<envvar> Like -c <name>=<value>, give configuration variable <name> a value, where <envvar> is the name of an environment variable from which to retrieve the value. Unlike -c there is no shortcut for directly setting the value to an empty string, instead the environment variable itself must be set to the empty string. It is an error if the <envvar> does not exist in the environment. <envvar> may not contain an equals sign to avoid ambiguity with <name> containing one. This is useful for cases where you want to pass transitory configuration options to git, but are doing so on operating systems where other processes might be able to read your command line (e.g. /proc/self/cmdline), but not your environment (e.g. /proc/self/environ). That behavior is the default on Linux, but may not be on your system. Note that this might add security for variables such as http.extraHeader where the sensitive information is part of the value, but not e.g. url.<base>.insteadOf where the sensitive information can be part of the key. --exec-path[=<path>] Path to wherever your core Git programs are installed. This can also be controlled by setting the GIT_EXEC_PATH environment variable. If no path is given, git will print the current setting and then exit. --html-path Print the path, without trailing slash, where Git’s HTML documentation is installed and exit. --man-path Print the manpath (see man(1)) for the man pages for this version of Git and exit. --info-path Print the path where the Info files documenting this version of Git are installed and exit. -p, --paginate Pipe all output into less (or if set, $PAGER) if standard output is a terminal. This overrides the pager.<cmd> configuration options (see the "Configuration Mechanism" section below). -P, --no-pager Do not pipe Git output into a pager. --git-dir=<path> Set the path to the repository (".git" directory). This can also be controlled by setting the GIT_DIR environment variable. It can be an absolute path or relative path to current working directory. Specifying the location of the ".git" directory using this option (or GIT_DIR environment variable) turns off the repository discovery that tries to find a directory with ".git" subdirectory (which is how the repository and the top-level of the working tree are discovered), and tells Git that you are at the top level of the working tree. If you are not at the top-level directory of the working tree, you should tell Git where the top-level of the working tree is, with the --work-tree=<path> option (or GIT_WORK_TREE environment variable) If you just want to run git as if it was started in <path> then use git -C <path>. --work-tree=<path> Set the path to the working tree. It can be an absolute path or a path relative to the current working directory. This can also be controlled by setting the GIT_WORK_TREE environment variable and the core.worktree configuration variable (see core.worktree in git-config(1) for a more detailed discussion). --namespace=<path> Set the Git namespace. See gitnamespaces(7) for more details. Equivalent to setting the GIT_NAMESPACE environment variable. --bare Treat the repository as a bare repository. If GIT_DIR environment is not set, it is set to the current working directory. --no-replace-objects Do not use replacement refs to replace Git objects. See git-replace(1) for more information. --literal-pathspecs Treat pathspecs literally (i.e. no globbing, no pathspec magic). This is equivalent to setting the GIT_LITERAL_PATHSPECS environment variable to 1. --glob-pathspecs Add "glob" magic to all pathspec. This is equivalent to setting the GIT_GLOB_PATHSPECS environment variable to 1. Disabling globbing on individual pathspecs can be done using pathspec magic ":(literal)" --noglob-pathspecs Add "literal" magic to all pathspec. This is equivalent to setting the GIT_NOGLOB_PATHSPECS environment variable to 1. Enabling globbing on individual pathspecs can be done using pathspec magic ":(glob)" --icase-pathspecs Add "icase" magic to all pathspec. This is equivalent to setting the GIT_ICASE_PATHSPECS environment variable to 1. --no-optional-locks Do not perform optional operations that require locks. This is equivalent to setting the GIT_OPTIONAL_LOCKS to 0. --list-cmds=group[,group...] List commands by group. This is an internal/experimental option and may change or be removed in the future. Supported groups are: builtins, parseopt (builtin commands that use parse-options), main (all commands in libexec directory), others (all other commands in $PATH that have git- prefix), list-<category> (see categories in command-list.txt), nohelpers (exclude helper commands), alias and config (retrieve command list from config variable completion.commands) --attr-source=<tree-ish> Read gitattributes from <tree-ish> instead of the worktree. See gitattributes(5). This is equivalent to setting the GIT_ATTR_SOURCE environment variable. GIT COMMANDS We divide Git into high level ("porcelain") commands and low level ("plumbing") commands. HIGH-LEVEL COMMANDS (PORCELAIN) We separate the porcelain commands into the main commands and some ancillary user utilities. Main porcelain commands git-add(1) Add file contents to the index. git-am(1) Apply a series of patches from a mailbox. git-archive(1) Create an archive of files from a named tree. git-bisect(1) Use binary search to find the commit that introduced a bug. git-branch(1) List, create, or delete branches. git-bundle(1) Move objects and refs by archive. git-checkout(1) Switch branches or restore working tree files. git-cherry-pick(1) Apply the changes introduced by some existing commits. git-citool(1) Graphical alternative to git-commit. git-clean(1) Remove untracked files from the working tree. git-clone(1) Clone a repository into a new directory. git-commit(1) Record changes to the repository. git-describe(1) Give an object a human readable name based on an available ref. git-diff(1) Show changes between commits, commit and working tree, etc. git-fetch(1) Download objects and refs from another repository. git-format-patch(1) Prepare patches for e-mail submission. git-gc(1) Cleanup unnecessary files and optimize the local repository. git-grep(1) Print lines matching a pattern. git-gui(1) A portable graphical interface to Git. git-init(1) Create an empty Git repository or reinitialize an existing one. git-log(1) Show commit logs. git-maintenance(1) Run tasks to optimize Git repository data. git-merge(1) Join two or more development histories together. git-mv(1) Move or rename a file, a directory, or a symlink. git-notes(1) Add or inspect object notes. git-pull(1) Fetch from and integrate with another repository or a local branch. git-push(1) Update remote refs along with associated objects. git-range-diff(1) Compare two commit ranges (e.g. two versions of a branch). git-rebase(1) Reapply commits on top of another base tip. git-reset(1) Reset current HEAD to the specified state. git-restore(1) Restore working tree files. git-revert(1) Revert some existing commits. git-rm(1) Remove files from the working tree and from the index. git-shortlog(1) Summarize git log output. git-show(1) Show various types of objects. git-sparse-checkout(1) Reduce your working tree to a subset of tracked files. git-stash(1) Stash the changes in a dirty working directory away. git-status(1) Show the working tree status. git-submodule(1) Initialize, update or inspect submodules. git-switch(1) Switch branches. git-tag(1) Create, list, delete or verify a tag object signed with GPG. git-worktree(1) Manage multiple working trees. gitk(1) The Git repository browser. scalar(1) A tool for managing large Git repositories. Ancillary Commands Manipulators: git-config(1) Get and set repository or global options. git-fast-export(1) Git data exporter. git-fast-import(1) Backend for fast Git data importers. git-filter-branch(1) Rewrite branches. git-mergetool(1) Run merge conflict resolution tools to resolve merge conflicts. git-pack-refs(1) Pack heads and tags for efficient repository access. git-prune(1) Prune all unreachable objects from the object database. git-reflog(1) Manage reflog information. git-remote(1) Manage set of tracked repositories. git-repack(1) Pack unpacked objects in a repository. git-replace(1) Create, list, delete refs to replace objects. Interrogators: git-annotate(1) Annotate file lines with commit information. git-blame(1) Show what revision and author last modified each line of a file. git-bugreport(1) Collect information for user to file a bug report. git-count-objects(1) Count unpacked number of objects and their disk consumption. git-diagnose(1) Generate a zip archive of diagnostic information. git-difftool(1) Show changes using common diff tools. git-fsck(1) Verifies the connectivity and validity of the objects in the database. git-help(1) Display help information about Git. git-instaweb(1) Instantly browse your working repository in gitweb. git-merge-tree(1) Perform merge without touching index or working tree. git-rerere(1) Reuse recorded resolution of conflicted merges. git-show-branch(1) Show branches and their commits. git-verify-commit(1) Check the GPG signature of commits. git-verify-tag(1) Check the GPG signature of tags. git-version(1) Display version information about Git. git-whatchanged(1) Show logs with differences each commit introduces. gitweb(1) Git web interface (web frontend to Git repositories). Interacting with Others These commands are to interact with foreign SCM and with other people via patch over e-mail. git-archimport(1) Import a GNU Arch repository into Git. git-cvsexportcommit(1) Export a single commit to a CVS checkout. git-cvsimport(1) Salvage your data out of another SCM people love to hate. git-cvsserver(1) A CVS server emulator for Git. git-imap-send(1) Send a collection of patches from stdin to an IMAP folder. git-p4(1) Import from and submit to Perforce repositories. git-quiltimport(1) Applies a quilt patchset onto the current branch. git-request-pull(1) Generates a summary of pending changes. git-send-email(1) Send a collection of patches as emails. git-svn(1) Bidirectional operation between a Subversion repository and Git. Reset, restore and revert There are three commands with similar names: git reset, git restore and git revert. • git-revert(1) is about making a new commit that reverts the changes made by other commits. • git-restore(1) is about restoring files in the working tree from either the index or another commit. This command does not update your branch. The command can also be used to restore files in the index from another commit. • git-reset(1) is about updating your branch, moving the tip in order to add or remove commits from the branch. This operation changes the commit history. git reset can also be used to restore the index, overlapping with git restore. LOW-LEVEL COMMANDS (PLUMBING) Although Git includes its own porcelain layer, its low-level commands are sufficient to support development of alternative porcelains. Developers of such porcelains might start by reading about git-update-index(1) and git- read-tree(1). The interface (input, output, set of options and the semantics) to these low-level commands are meant to be a lot more stable than Porcelain level commands, because these commands are primarily for scripted use. The interface to Porcelain commands on the other hand are subject to change in order to improve the end user experience. The following description divides the low-level commands into commands that manipulate objects (in the repository, index, and working tree), commands that interrogate and compare objects, and commands that move objects and references between repositories. Manipulation commands git-apply(1) Apply a patch to files and/or to the index. git-checkout-index(1) Copy files from the index to the working tree. git-commit-graph(1) Write and verify Git commit-graph files. git-commit-tree(1) Create a new commit object. git-hash-object(1) Compute object ID and optionally create an object from a file. git-index-pack(1) Build pack index file for an existing packed archive. git-merge-file(1) Run a three-way file merge. git-merge-index(1) Run a merge for files needing merging. git-mktag(1) Creates a tag object with extra validation. git-mktree(1) Build a tree-object from ls-tree formatted text. git-multi-pack-index(1) Write and verify multi-pack-indexes. git-pack-objects(1) Create a packed archive of objects. git-prune-packed(1) Remove extra objects that are already in pack files. git-read-tree(1) Reads tree information into the index. git-symbolic-ref(1) Read, modify and delete symbolic refs. git-unpack-objects(1) Unpack objects from a packed archive. git-update-index(1) Register file contents in the working tree to the index. git-update-ref(1) Update the object name stored in a ref safely. git-write-tree(1) Create a tree object from the current index. Interrogation commands git-cat-file(1) Provide contents or details of repository objects. git-cherry(1) Find commits yet to be applied to upstream. git-diff-files(1) Compares files in the working tree and the index. git-diff-index(1) Compare a tree to the working tree or index. git-diff-tree(1) Compares the content and mode of blobs found via two tree objects. git-for-each-ref(1) Output information on each ref. git-for-each-repo(1) Run a Git command on a list of repositories. git-get-tar-commit-id(1) Extract commit ID from an archive created using git-archive. git-ls-files(1) Show information about files in the index and the working tree. git-ls-remote(1) List references in a remote repository. git-ls-tree(1) List the contents of a tree object. git-merge-base(1) Find as good common ancestors as possible for a merge. git-name-rev(1) Find symbolic names for given revs. git-pack-redundant(1) Find redundant pack files. git-rev-list(1) Lists commit objects in reverse chronological order. git-rev-parse(1) Pick out and massage parameters. git-show-index(1) Show packed archive index. git-show-ref(1) List references in a local repository. git-unpack-file(1) Creates a temporary file with a blob’s contents. git-var(1) Show a Git logical variable. git-verify-pack(1) Validate packed Git archive files. In general, the interrogate commands do not touch the files in the working tree. Syncing repositories git-daemon(1) A really simple server for Git repositories. git-fetch-pack(1) Receive missing objects from another repository. git-http-backend(1) Server side implementation of Git over HTTP. git-send-pack(1) Push objects over Git protocol to another repository. git-update-server-info(1) Update auxiliary info file to help dumb servers. The following are helper commands used by the above; end users typically do not use them directly. git-http-fetch(1) Download from a remote Git repository via HTTP. git-http-push(1) Push objects over HTTP/DAV to another repository. git-receive-pack(1) Receive what is pushed into the repository. git-shell(1) Restricted login shell for Git-only SSH access. git-upload-archive(1) Send archive back to git-archive. git-upload-pack(1) Send objects packed back to git-fetch-pack. Internal helper commands These are internal helper commands used by other commands; end users typically do not use them directly. git-check-attr(1) Display gitattributes information. git-check-ignore(1) Debug gitignore / exclude files. git-check-mailmap(1) Show canonical names and email addresses of contacts. git-check-ref-format(1) Ensures that a reference name is well formed. git-column(1) Display data in columns. git-credential(1) Retrieve and store user credentials. git-credential-cache(1) Helper to temporarily store passwords in memory. git-credential-store(1) Helper to store credentials on disk. git-fmt-merge-msg(1) Produce a merge commit message. git-hook(1) Run git hooks. git-interpret-trailers(1) Add or parse structured information in commit messages. git-mailinfo(1) Extracts patch and authorship from a single e-mail message. git-mailsplit(1) Simple UNIX mbox splitter program. git-merge-one-file(1) The standard helper program to use with git-merge-index. git-patch-id(1) Compute unique ID for a patch. git-sh-i18n(1) Git’s i18n setup code for shell scripts. git-sh-setup(1) Common Git shell script setup code. git-stripspace(1) Remove unnecessary whitespace. GUIDES The following documentation pages are guides about Git concepts. gitcore-tutorial(7) A Git core tutorial for developers. gitcredentials(7) Providing usernames and passwords to Git. gitcvs-migration(7) Git for CVS users. gitdiffcore(7) Tweaking diff output. giteveryday(7) A useful minimum set of commands for Everyday Git. gitfaq(7) Frequently asked questions about using Git. gitglossary(7) A Git Glossary. gitnamespaces(7) Git namespaces. gitremote-helpers(7) Helper programs to interact with remote repositories. gitsubmodules(7) Mounting one repository inside another. gittutorial(7) A tutorial introduction to Git. gittutorial-2(7) A tutorial introduction to Git: part two. gitworkflows(7) An overview of recommended workflows with Git. REPOSITORY, COMMAND AND FILE INTERFACES This documentation discusses repository and command interfaces which users are expected to interact with directly. See --user-formats in git-help(1) for more details on the criteria. gitattributes(5) Defining attributes per path. gitcli(7) Git command-line interface and conventions. githooks(5) Hooks used by Git. gitignore(5) Specifies intentionally untracked files to ignore. gitmailmap(5) Map author/committer names and/or E-Mail addresses. gitmodules(5) Defining submodule properties. gitrepository-layout(5) Git Repository Layout. gitrevisions(7) Specifying revisions and ranges for Git. FILE FORMATS, PROTOCOLS AND OTHER DEVELOPER INTERFACES This documentation discusses file formats, over-the-wire protocols and other git developer interfaces. See --developer-interfaces in git-help(1). gitformat-bundle(5) The bundle file format. gitformat-chunk(5) Chunk-based file formats. gitformat-commit-graph(5) Git commit-graph format. gitformat-index(5) Git index format. gitformat-pack(5) Git pack format. gitformat-signature(5) Git cryptographic signature formats. gitprotocol-capabilities(5) Protocol v0 and v1 capabilities. gitprotocol-common(5) Things common to various protocols. gitprotocol-http(5) Git HTTP-based protocols. gitprotocol-pack(5) How packs are transferred over-the-wire. gitprotocol-v2(5) Git Wire Protocol, Version 2. CONFIGURATION MECHANISM Git uses a simple text format to store customizations that are per repository and are per user. Such a configuration file may look like this: # # A '#' or ';' character indicates a comment. # ; core variables [core] ; Don't trust file modes filemode = false ; user identity [user] name = "Junio C Hamano" email = "[email protected]" Various commands read from the configuration file and adjust their operation accordingly. See git-config(1) for a list and more details about the configuration mechanism. IDENTIFIER TERMINOLOGY <object> Indicates the object name for any type of object. <blob> Indicates a blob object name. <tree> Indicates a tree object name. <commit> Indicates a commit object name. <tree-ish> Indicates a tree, commit or tag object name. A command that takes a <tree-ish> argument ultimately wants to operate on a <tree> object but automatically dereferences <commit> and <tag> objects that point at a <tree>. <commit-ish> Indicates a commit or tag object name. A command that takes a <commit-ish> argument ultimately wants to operate on a <commit> object but automatically dereferences <tag> objects that point at a <commit>. <type> Indicates that an object type is required. Currently one of: blob, tree, commit, or tag. <file> Indicates a filename - almost always relative to the root of the tree structure GIT_INDEX_FILE describes. SYMBOLIC IDENTIFIERS Any Git command accepting any <object> can also use the following symbolic notation: HEAD indicates the head of the current branch. <tag> a valid tag name (i.e. a refs/tags/<tag> reference). <head> a valid head name (i.e. a refs/heads/<head> reference). For a more complete list of ways to spell object names, see "SPECIFYING REVISIONS" section in gitrevisions(7). FILE/DIRECTORY STRUCTURE Please see the gitrepository-layout(5) document. Read githooks(5) for more details about each hook. Higher level SCMs may provide and manage additional information in the $GIT_DIR. TERMINOLOGY Please see gitglossary(7). ENVIRONMENT VARIABLES Various Git commands pay attention to environment variables and change their behavior. The environment variables marked as "Boolean" take their values the same way as Boolean valued configuration variables, e.g. "true", "yes", "on" and positive numbers are taken as "yes". Here are the variables: The Git Repository These environment variables apply to all core Git commands. Nb: it is worth noting that they may be used/overridden by SCMS sitting above Git so take care if using a foreign front-end. GIT_INDEX_FILE This environment variable specifies an alternate index file. If not specified, the default of $GIT_DIR/index is used. GIT_INDEX_VERSION This environment variable specifies what index version is used when writing the index file out. It won’t affect existing index files. By default index file version 2 or 3 is used. See git-update-index(1) for more information. GIT_OBJECT_DIRECTORY If the object storage directory is specified via this environment variable then the sha1 directories are created underneath - otherwise the default $GIT_DIR/objects directory is used. GIT_ALTERNATE_OBJECT_DIRECTORIES Due to the immutable nature of Git objects, old objects can be archived into shared, read-only directories. This variable specifies a ":" separated (on Windows ";" separated) list of Git object directories which can be used to search for Git objects. New objects will not be written to these directories. Entries that begin with " (double-quote) will be interpreted as C-style quoted paths, removing leading and trailing double-quotes and respecting backslash escapes. E.g., the value "path-with-\"-and-:-in-it":vanilla-path has two paths: path-with-"-and-:-in-it and vanilla-path. GIT_DIR If the GIT_DIR environment variable is set then it specifies a path to use instead of the default .git for the base of the repository. The --git-dir command-line option also sets this value. GIT_WORK_TREE Set the path to the root of the working tree. This can also be controlled by the --work-tree command-line option and the core.worktree configuration variable. GIT_NAMESPACE Set the Git namespace; see gitnamespaces(7) for details. The --namespace command-line option also sets this value. GIT_CEILING_DIRECTORIES This should be a colon-separated list of absolute paths. If set, it is a list of directories that Git should not chdir up into while looking for a repository directory (useful for excluding slow-loading network directories). It will not exclude the current working directory or a GIT_DIR set on the command line or in the environment. Normally, Git has to read the entries in this list and resolve any symlink that might be present in order to compare them with the current directory. However, if even this access is slow, you can add an empty entry to the list to tell Git that the subsequent entries are not symlinks and needn’t be resolved; e.g., GIT_CEILING_DIRECTORIES=/maybe/symlink::/very/slow/non/symlink. GIT_DISCOVERY_ACROSS_FILESYSTEM When run in a directory that does not have ".git" repository directory, Git tries to find such a directory in the parent directories to find the top of the working tree, but by default it does not cross filesystem boundaries. This Boolean environment variable can be set to true to tell Git not to stop at filesystem boundaries. Like GIT_CEILING_DIRECTORIES, this will not affect an explicit repository directory set via GIT_DIR or on the command line. GIT_COMMON_DIR If this variable is set to a path, non-worktree files that are normally in $GIT_DIR will be taken from this path instead. Worktree-specific files such as HEAD or index are taken from $GIT_DIR. See gitrepository- layout(5) and git-worktree(1) for details. This variable has lower precedence than other path variables such as GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY... GIT_DEFAULT_HASH If this variable is set, the default hash algorithm for new repositories will be set to this value. This value is ignored when cloning and the setting of the remote repository is always used. The default is "sha1". See --object-format in git-init(1). Git Commits GIT_AUTHOR_NAME The human-readable name used in the author identity when creating commit or tag objects, or when writing reflogs. Overrides the user.name and author.name configuration settings. GIT_AUTHOR_EMAIL The email address used in the author identity when creating commit or tag objects, or when writing reflogs. Overrides the user.email and author.email configuration settings. GIT_AUTHOR_DATE The date used for the author identity when creating commit or tag objects, or when writing reflogs. See git- commit(1) for valid formats. GIT_COMMITTER_NAME The human-readable name used in the committer identity when creating commit or tag objects, or when writing reflogs. Overrides the user.name and committer.name configuration settings. GIT_COMMITTER_EMAIL The email address used in the author identity when creating commit or tag objects, or when writing reflogs. Overrides the user.email and committer.email configuration settings. GIT_COMMITTER_DATE The date used for the committer identity when creating commit or tag objects, or when writing reflogs. See git- commit(1) for valid formats. EMAIL The email address used in the author and committer identities if no other relevant environment variable or configuration setting has been set. Git Diffs GIT_DIFF_OPTS Only valid setting is "--unified=??" or "-u??" to set the number of context lines shown when a unified diff is created. This takes precedence over any "-U" or "--unified" option value passed on the Git diff command line. GIT_EXTERNAL_DIFF When the environment variable GIT_EXTERNAL_DIFF is set, the program named by it is called to generate diffs, and Git does not use its builtin diff machinery. For a path that is added, removed, or modified, GIT_EXTERNAL_DIFF is called with 7 parameters: path old-file old-hex old-mode new-file new-hex new-mode where: <old|new>-file are files GIT_EXTERNAL_DIFF can use to read the contents of <old|new>, <old|new>-hex are the 40-hexdigit SHA-1 hashes, <old|new>-mode are the octal representation of the file modes. The file parameters can point at the user’s working file (e.g. new-file in "git-diff-files"), /dev/null (e.g. old-file when a new file is added), or a temporary file (e.g. old-file in the index). GIT_EXTERNAL_DIFF should not worry about unlinking the temporary file — it is removed when GIT_EXTERNAL_DIFF exits. For a path that is unmerged, GIT_EXTERNAL_DIFF is called with 1 parameter, <path>. For each path GIT_EXTERNAL_DIFF is called, two environment variables, GIT_DIFF_PATH_COUNTER and GIT_DIFF_PATH_TOTAL are set. GIT_DIFF_PATH_COUNTER A 1-based counter incremented by one for every path. GIT_DIFF_PATH_TOTAL The total number of paths. other GIT_MERGE_VERBOSITY A number controlling the amount of output shown by the recursive merge strategy. Overrides merge.verbosity. See git-merge(1) GIT_PAGER This environment variable overrides $PAGER. If it is set to an empty string or to the value "cat", Git will not launch a pager. See also the core.pager option in git-config(1). GIT_PROGRESS_DELAY A number controlling how many seconds to delay before showing optional progress indicators. Defaults to 2. GIT_EDITOR This environment variable overrides $EDITOR and $VISUAL. It is used by several Git commands when, on interactive mode, an editor is to be launched. See also git-var(1) and the core.editor option in git-config(1). GIT_SEQUENCE_EDITOR This environment variable overrides the configured Git editor when editing the todo list of an interactive rebase. See also git-rebase(1) and the sequence.editor option in git-config(1). GIT_SSH, GIT_SSH_COMMAND If either of these environment variables is set then git fetch and git push will use the specified command instead of ssh when they need to connect to a remote system. The command-line parameters passed to the configured command are determined by the ssh variant. See ssh.variant option in git-config(1) for details. $GIT_SSH_COMMAND takes precedence over $GIT_SSH, and is interpreted by the shell, which allows additional arguments to be included. $GIT_SSH on the other hand must be just the path to a program (which can be a wrapper shell script, if additional arguments are needed). Usually it is easier to configure any desired options through your personal .ssh/config file. Please consult your ssh documentation for further details. GIT_SSH_VARIANT If this environment variable is set, it overrides Git’s autodetection whether GIT_SSH/GIT_SSH_COMMAND/core.sshCommand refer to OpenSSH, plink or tortoiseplink. This variable overrides the config setting ssh.variant that serves the same purpose. GIT_SSL_NO_VERIFY Setting and exporting this environment variable to any value tells Git not to verify the SSL certificate when fetching or pushing over HTTPS. GIT_ATTR_SOURCE Sets the treeish that gitattributes will be read from. GIT_ASKPASS If this environment variable is set, then Git commands which need to acquire passwords or passphrases (e.g. for HTTP or IMAP authentication) will call this program with a suitable prompt as command-line argument and read the password from its STDOUT. See also the core.askPass option in git-config(1). GIT_TERMINAL_PROMPT If this Boolean environment variable is set to false, git will not prompt on the terminal (e.g., when asking for HTTP authentication). GIT_CONFIG_GLOBAL, GIT_CONFIG_SYSTEM Take the configuration from the given files instead from global or system-level configuration files. If GIT_CONFIG_SYSTEM is set, the system config file defined at build time (usually /etc/gitconfig) will not be read. Likewise, if GIT_CONFIG_GLOBAL is set, neither $HOME/.gitconfig nor $XDG_CONFIG_HOME/git/config will be read. Can be set to /dev/null to skip reading configuration files of the respective level. GIT_CONFIG_NOSYSTEM Whether to skip reading settings from the system-wide $(prefix)/etc/gitconfig file. This Boolean environment variable can be used along with $HOME and $XDG_CONFIG_HOME to create a predictable environment for a picky script, or you can set it to true to temporarily avoid using a buggy /etc/gitconfig file while waiting for someone with sufficient permissions to fix it. GIT_FLUSH If this environment variable is set to "1", then commands such as git blame (in incremental mode), git rev-list, git log, git check-attr and git check-ignore will force a flush of the output stream after each record have been flushed. If this variable is set to "0", the output of these commands will be done using completely buffered I/O. If this environment variable is not set, Git will choose buffered or record-oriented flushing based on whether stdout appears to be redirected to a file or not. GIT_TRACE Enables general trace messages, e.g. alias expansion, built-in command execution and external command execution. If this variable is set to "1", "2" or "true" (comparison is case insensitive), trace messages will be printed to stderr. If the variable is set to an integer value greater than 2 and lower than 10 (strictly) then Git will interpret this value as an open file descriptor and will try to write the trace messages into this file descriptor. Alternatively, if the variable is set to an absolute path (starting with a / character), Git will interpret this as a file path and will try to append the trace messages to it. Unsetting the variable, or setting it to empty, "0" or "false" (case insensitive) disables trace messages. GIT_TRACE_FSMONITOR Enables trace messages for the filesystem monitor extension. See GIT_TRACE for available trace output options. GIT_TRACE_PACK_ACCESS Enables trace messages for all accesses to any packs. For each access, the pack file name and an offset in the pack is recorded. This may be helpful for troubleshooting some pack-related performance problems. See GIT_TRACE for available trace output options. GIT_TRACE_PACKET Enables trace messages for all packets coming in or out of a given program. This can help with debugging object negotiation or other protocol issues. Tracing is turned off at a packet starting with "PACK" (but see GIT_TRACE_PACKFILE below). See GIT_TRACE for available trace output options. GIT_TRACE_PACKFILE Enables tracing of packfiles sent or received by a given program. Unlike other trace output, this trace is verbatim: no headers, and no quoting of binary data. You almost certainly want to direct into a file (e.g., GIT_TRACE_PACKFILE=/tmp/my.pack) rather than displaying it on the terminal or mixing it with other trace output. Note that this is currently only implemented for the client side of clones and fetches. GIT_TRACE_PERFORMANCE Enables performance related trace messages, e.g. total execution time of each Git command. See GIT_TRACE for available trace output options. GIT_TRACE_REFS Enables trace messages for operations on the ref database. See GIT_TRACE for available trace output options. GIT_TRACE_SETUP Enables trace messages printing the .git, working tree and current working directory after Git has completed its setup phase. See GIT_TRACE for available trace output options. GIT_TRACE_SHALLOW Enables trace messages that can help debugging fetching / cloning of shallow repositories. See GIT_TRACE for available trace output options. GIT_TRACE_CURL Enables a curl full trace dump of all incoming and outgoing data, including descriptive information, of the git transport protocol. This is similar to doing curl --trace-ascii on the command line. See GIT_TRACE for available trace output options. GIT_TRACE_CURL_NO_DATA When a curl trace is enabled (see GIT_TRACE_CURL above), do not dump data (that is, only dump info lines and headers). GIT_TRACE2 Enables more detailed trace messages from the "trace2" library. Output from GIT_TRACE2 is a simple text-based format for human readability. If this variable is set to "1", "2" or "true" (comparison is case insensitive), trace messages will be printed to stderr. If the variable is set to an integer value greater than 2 and lower than 10 (strictly) then Git will interpret this value as an open file descriptor and will try to write the trace messages into this file descriptor. Alternatively, if the variable is set to an absolute path (starting with a / character), Git will interpret this as a file path and will try to append the trace messages to it. If the path already exists and is a directory, the trace messages will be written to files (one per process) in that directory, named according to the last component of the SID and an optional counter (to avoid filename collisions). In addition, if the variable is set to af_unix:[<socket_type>:]<absolute-pathname>, Git will try to open the path as a Unix Domain Socket. The socket type can be either stream or dgram. Unsetting the variable, or setting it to empty, "0" or "false" (case insensitive) disables trace messages. See Trace2 documentation[2] for full details. GIT_TRACE2_EVENT This setting writes a JSON-based format that is suited for machine interpretation. See GIT_TRACE2 for available trace output options and Trace2 documentation[2] for full details. GIT_TRACE2_PERF In addition to the text-based messages available in GIT_TRACE2, this setting writes a column-based format for understanding nesting regions. See GIT_TRACE2 for available trace output options and Trace2 documentation[2] for full details. GIT_TRACE_REDACT By default, when tracing is activated, Git redacts the values of cookies, the "Authorization:" header, the "Proxy-Authorization:" header and packfile URIs. Set this Boolean environment variable to false to prevent this redaction. GIT_LITERAL_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs literally, rather than as glob patterns. For example, running GIT_LITERAL_PATHSPECS=1 git log -- '*.c' will search for commits that touch the path *.c, not any paths that the glob *.c matches. You might want this if you are feeding literal paths to Git (e.g., paths previously given to you by git ls-tree, --raw diff output, etc). GIT_GLOB_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs as glob patterns (aka "glob" magic). GIT_NOGLOB_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs as literal (aka "literal" magic). GIT_ICASE_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs as case-insensitive. GIT_REFLOG_ACTION When a ref is updated, reflog entries are created to keep track of the reason why the ref was updated (which is typically the name of the high-level command that updated the ref), in addition to the old and new values of the ref. A scripted Porcelain command can use set_reflog_action helper function in git-sh-setup to set its name to this variable when it is invoked as the top level command by the end user, to be recorded in the body of the reflog. GIT_REF_PARANOIA If this Boolean environment variable is set to false, ignore broken or badly named refs when iterating over lists of refs. Normally Git will try to include any such refs, which may cause some operations to fail. This is usually preferable, as potentially destructive operations (e.g., git-prune(1)) are better off aborting rather than ignoring broken refs (and thus considering the history they point to as not worth saving). The default value is 1 (i.e., be paranoid about detecting and aborting all operations). You should not normally need to set this to 0, but it may be useful when trying to salvage data from a corrupted repository. GIT_COMMIT_GRAPH_PARANOIA When loading a commit object from the commit-graph, Git performs an existence check on the object in the object database. This is done to avoid issues with stale commit-graphs that contain references to already-deleted commits, but comes with a performance penalty. The default is "true", which enables the aforementioned behavior. Setting this to "false" disables the existence check. This can lead to a performance improvement at the cost of consistency. GIT_ALLOW_PROTOCOL If set to a colon-separated list of protocols, behave as if protocol.allow is set to never, and each of the listed protocols has protocol.<name>.allow set to always (overriding any existing configuration). See the description of protocol.allow in git-config(1) for more details. GIT_PROTOCOL_FROM_USER Set this Boolean environment variable to false to prevent protocols used by fetch/push/clone which are configured to the user state. This is useful to restrict recursive submodule initialization from an untrusted repository or for programs which feed potentially-untrusted URLS to git commands. See git-config(1) for more details. GIT_PROTOCOL For internal use only. Used in handshaking the wire protocol. Contains a colon : separated list of keys with optional values key[=value]. Presence of unknown keys and values must be ignored. Note that servers may need to be configured to allow this variable to pass over some transports. It will be propagated automatically when accessing local repositories (i.e., file:// or a filesystem path), as well as over the git:// protocol. For git-over-http, it should work automatically in most configurations, but see the discussion in git-http-backend(1). For git-over-ssh, the ssh server may need to be configured to allow clients to pass this variable (e.g., by using AcceptEnv GIT_PROTOCOL with OpenSSH). This configuration is optional. If the variable is not propagated, then clients will fall back to the original "v0" protocol (but may miss out on some performance improvements or features). This variable currently only affects clones and fetches; it is not yet used for pushes (but may be in the future). GIT_OPTIONAL_LOCKS If this Boolean environment variable is set to false, Git will complete any requested operation without performing any optional sub-operations that require taking a lock. For example, this will prevent git status from refreshing the index as a side effect. This is useful for processes running in the background which do not want to cause lock contention with other operations on the repository. Defaults to 1. GIT_REDIRECT_STDIN, GIT_REDIRECT_STDOUT, GIT_REDIRECT_STDERR Windows-only: allow redirecting the standard input/output/error handles to paths specified by the environment variables. This is particularly useful in multi-threaded applications where the canonical way to pass standard handles via CreateProcess() is not an option because it would require the handles to be marked inheritable (and consequently every spawned process would inherit them, possibly blocking regular Git operations). The primary intended use case is to use named pipes for communication (e.g. \\.\pipe\my-git-stdin-123). Two special values are supported: off will simply close the corresponding standard handle, and if GIT_REDIRECT_STDERR is 2>&1, standard error will be redirected to the same handle as standard output. GIT_PRINT_SHA1_ELLIPSIS (deprecated) If set to yes, print an ellipsis following an (abbreviated) SHA-1 value. This affects indications of detached HEADs (git-checkout(1)) and the raw diff output (git-diff(1)). Printing an ellipsis in the cases mentioned is no longer considered adequate and support for it is likely to be removed in the foreseeable future (along with the variable). DISCUSSION More detail on the following is available from the Git concepts chapter of the user-manual[3] and gitcore- tutorial(7). A Git project normally consists of a working directory with a ".git" subdirectory at the top level. The .git directory contains, among other things, a compressed object database representing the complete history of the project, an "index" file which links that history to the current contents of the working tree, and named pointers into that history such as tags and branch heads. The object database contains objects of three main types: blobs, which hold file data; trees, which point to blobs and other trees to build up directory hierarchies; and commits, which each reference a single tree and some number of parent commits. The commit, equivalent to what other systems call a "changeset" or "version", represents a step in the project’s history, and each parent represents an immediately preceding step. Commits with more than one parent represent merges of independent lines of development. All objects are named by the SHA-1 hash of their contents, normally written as a string of 40 hex digits. Such names are globally unique. The entire history leading up to a commit can be vouched for by signing just that commit. A fourth object type, the tag, is provided for this purpose. When first created, objects are stored in individual files, but for efficiency may later be compressed together into "pack files". Named pointers called refs mark interesting points in history. A ref may contain the SHA-1 name of an object or the name of another ref. Refs with names beginning ref/head/ contain the SHA-1 name of the most recent commit (or "head") of a branch under development. SHA-1 names of tags of interest are stored under ref/tags/. A special ref named HEAD contains the name of the currently checked-out branch. The index file is initialized with a list of all paths and, for each path, a blob object and a set of attributes. The blob object represents the contents of the file as of the head of the current branch. The attributes (last modified time, size, etc.) are taken from the corresponding file in the working tree. Subsequent changes to the working tree can be found by comparing these attributes. The index may be updated with new content, and new commits may be created from the content stored in the index. The index is also capable of storing multiple entries (called "stages") for a given pathname. These stages are used to hold the various unmerged version of a file when a merge is in progress. FURTHER DOCUMENTATION See the references in the "description" section to get started using Git. The following is probably more detail than necessary for a first-time user. The Git concepts chapter of the user-manual[3] and gitcore-tutorial(7) both provide introductions to the underlying Git architecture. See gitworkflows(7) for an overview of recommended workflows. See also the howto[4] documents for some useful examples. The internals are documented in the Git API documentation[5]. Users migrating from CVS may also want to read gitcvs-migration(7). AUTHORS Git was started by Linus Torvalds, and is currently maintained by Junio C Hamano. Numerous contributions have come from the Git mailing list <[email protected][6]>. http://www.openhub.net/p/git/contributors/summary gives you a more complete list of contributors. If you have a clone of git.git itself, the output of git-shortlog(1) and git-blame(1) can show you the authors for specific parts of the project. REPORTING BUGS Report bugs to the Git mailing list <[email protected][6]> where the development and maintenance is primarily done. You do not have to be subscribed to the list to send a message there. See the list archive at https://lore.kernel.org/git for previous bug reports and other discussions. Issues which are security relevant should be disclosed privately to the Git Security mailing list <[email protected][7]>. SEE ALSO gittutorial(7), gittutorial-2(7), giteveryday(7), gitcvs-migration(7), gitglossary(7), gitcore-tutorial(7), gitcli(7), The Git User’s Manual[1], gitworkflows(7) GIT Part of the git(1) suite NOTES 1. Git User’s Manual file:///usr/share/doc/git/html/user-manual.html 2. Trace2 documentation file:///usr/share/doc/git/html/technical/api-trace2.html 3. Git concepts chapter of the user-manual file:///usr/share/doc/git/html/user-manual.html#git-concepts 4. howto file:///usr/share/doc/git/html/howto-index.html 5. Git API documentation file:///usr/share/doc/git/html/technical/api-index.html 6. [email protected] mailto:[email protected] 7. [email protected] mailto:[email protected] Git 2.43.0 01/13/2025 GIT(1)

March 10, 2025

rubyメモ

はじめに ruby自体は、初めて学習した言語であり今でも一番よく使う言語。 あまり忘れるということもないが、改めて体系的にまとまっているであろうmanページをメモしたいので記事を作る。 man ruby より引用 RUBY(1) Ruby Programmer's Reference Guide RUBY(1) NAME ruby — Interpreted object-oriented scripting language SYNOPSIS ruby [--copyright] [--version] [-SUacdlnpswvy] [-0[octal]] [-C directory] [-E external[:internal]] [-F[pattern]] [-I directory] [-K[c]] [-T[level]] [-W[level]] [-e command] [-i[extension]] [-r library] [-x[directory]] [--{enable|disable}-FEATURE] [--dump=target] [--verbose] [--] [program_file] [argument ...] DESCRIPTION Ruby is an interpreted scripting language for quick and easy object-oriented programming. It has many features to process text files and to do system management tasks (like in Perl). It is simple, straight-forward, and extensi‐ ble. If you want a language for easy object-oriented programming, or you don't like the Perl ugliness, or you do like the concept of LISP, but don't like too many parentheses, Ruby might be your language of choice. FEATURES Ruby's features are as follows: Interpretive Ruby is an interpreted language, so you don't have to recompile programs written in Ruby to execute them. Variables have no type (dynamic typing) Variables in Ruby can contain data of any type. You don't have to worry about variable typing. Conse‐ quently, it has a weaker compile time check. No declaration needed You can use variables in your Ruby programs without any declarations. Variable names denote their scope - global, class, instance, or local. Simple syntax Ruby has a simple syntax influenced slightly from Eiffel. No user-level memory management Ruby has automatic memory management. Objects no longer referenced from anywhere are automatically col‐ lected by the garbage collector built into the interpreter. Everything is an object Ruby is a purely object-oriented language, and was so since its creation. Even such basic data as integers are seen as objects. Class, inheritance, and methods Being an object-oriented language, Ruby naturally has basic features like classes, inheritance, and meth‐ ods. Singleton methods Ruby has the ability to define methods for certain objects. For example, you can define a press-button ac‐ tion for certain widget by defining a singleton method for the button. Or, you can make up your own proto‐ type based object system using singleton methods, if you want to. Mix-in by modules Ruby intentionally does not have the multiple inheritance as it is a source of confusion. Instead, Ruby has the ability to share implementations across the inheritance tree. This is often called a ‘Mix-in’. Iterators Ruby has iterators for loop abstraction. Closures In Ruby, you can objectify the procedure. Text processing and regular expressions Ruby has a bunch of text processing features like in Perl. M17N, character set independent Ruby supports multilingualized programming. Easy to process texts written in many different natural lan‐ guages and encoded in many different character encodings, without dependence on Unicode. Bignums With built-in bignums, you can for example calculate factorial(400). Reflection and domain specific languages Class is also an instance of the Class class. Definition of classes and methods is an expression just as 1+1 is. So your programs can even write and modify programs. Thus you can write your application in your own programming language on top of Ruby. Exception handling As in Java(tm). Direct access to the OS Ruby can use most Unix system calls, often used in system programming. Dynamic loading On most Unix systems, you can load object files into the Ruby interpreter on-the-fly. Rich libraries In addition to the “builtin libraries” and “standard libraries” that are bundled with Ruby, a vast amount of third-party libraries (“gems”) are available via the package management system called ‘RubyGems’, namely the gem(1) command. Visit RubyGems.org (https://rubygems.org/) to find the gems you need, and explore GitHub (https://github.com/) to see how they are being developed and used. OPTIONS The Ruby interpreter accepts the following command-line options (switches). They are quite similar to those of perl(1). --copyright Prints the copyright notice, and quits immediately without running any script. --version Prints the version of the Ruby interpreter, and quits immediately without running any script. -0[octal] (The digit “zero”.) Specifies the input record separator ($/) as an octal number. If no digit is given, the null character is taken as the separator. Other switches may follow the digits. -00 turns Ruby into paragraph mode. -0777 makes Ruby read whole file at once as a single string since there is no legal character with that value. -C directory -X directory Causes Ruby to switch to the directory. -E external[:internal] --encoding external[:internal] Specifies the default value(s) for external encodings and internal encoding. Values should be sepa‐ rated with colon (:). You can omit the one for internal encodings, then the value (Encoding.default_internal) will be nil. --external-encoding=encoding --internal-encoding=encoding Specify the default external or internal character encoding -F pattern Specifies input field separator ($;). -I directory Used to tell Ruby where to load the library scripts. Directory path will be added to the load-path variable ($:). -K kcode Specifies KANJI (Japanese) encoding. The default value for script encodings (__ENCODING__) and external encodings (Encoding.default_external) will be the specified one. kcode can be one of e EUC-JP s Windows-31J (CP932) u UTF-8 n ASCII-8BIT (BINARY) -S Makes Ruby use the PATH environment variable to search for script, unless its name begins with a slash. This is used to emulate #! on machines that don't support it, in the following manner: #! /usr/local/bin/ruby # This line makes the next one a comment in Ruby \ exec /usr/local/bin/ruby -S $0 $* On some systems $0 does not always contain the full pathname, so you need the -S switch to tell Ruby to search for the script if necessary (to handle embedded spaces and such). A better construct than $* would be ${1+"$@"}, but it does not work if the script is being interpreted by csh(1). -T[level=1] Turns on taint checks at the specified level (default 1). -U Sets the default value for internal encodings (Encoding.default_internal) to UTF-8. -W[level=2] Turns on verbose mode at the specified level without printing the version message at the beginning. The level can be; 0 Verbose mode is "silence". It sets the $VERBOSE to nil. 1 Verbose mode is "medium". It sets the $VERBOSE to false. 2 (default) Verbose mode is "verbose". It sets the $VERBOSE to true. -W2 is the same as -w -a Turns on auto-split mode when used with -n or -p. In auto-split mode, Ruby executes $F = $_.split at beginning of each loop. -c Causes Ruby to check the syntax of the script and exit without executing. If there are no syntax er‐ rors, Ruby will print “Syntax OK” to the standard output. -d --debug Turns on debug mode. $DEBUG will be set to true. -e command Specifies script from command-line while telling Ruby not to search the rest of the arguments for a script file name. -h --help Prints a summary of the options. -i extension Specifies in-place-edit mode. The extension, if specified, is added to old file name to make a backup copy. For example: % echo matz > /tmp/junk % cat /tmp/junk matz % ruby -p -i.bak -e '$_.upcase!' /tmp/junk % cat /tmp/junk MATZ % cat /tmp/junk.bak matz -l (The lowercase letter “ell”.) Enables automatic line-ending processing, which means to firstly set $\ to the value of $/, and secondly chops every line read using chomp!. -n Causes Ruby to assume the following loop around your script, which makes it iterate over file name arguments somewhat like sed -n or awk. while gets ... end -p Acts mostly same as -n switch, but print the value of variable $_ at the each end of the loop. For example: % echo matz | ruby -p -e '$_.tr! "a-z", "A-Z"' MATZ -r library Causes Ruby to load the library using require. It is useful when using -n or -p. -s Enables some switch parsing for switches after script name but before any file name arguments (or before a --). Any switches found there are removed from ARGV and set the corresponding variable in the script. For example: #! /usr/local/bin/ruby -s # prints "true" if invoked with `-xyz' switch. print "true\n" if $xyz -v Enables verbose mode. Ruby will print its version at the beginning and set the variable $VERBOSE to true. Some methods print extra messages if this variable is true. If this switch is given, and no other switches are present, Ruby quits after printing its version. -w Enables verbose mode without printing version message at the beginning. It sets the $VERBOSE vari‐ able to true. -x[directory] Tells Ruby that the script is embedded in a message. Leading garbage will be discarded until the first line that starts with “#!” and contains the string, “ruby”. Any meaningful switches on that line will be applied. The end of the script must be specified with either EOF, ^D (control-D), ^Z (control-Z), or the reserved word __END__. If the directory name is specified, Ruby will switch to that directory before executing script. -y --yydebug DO NOT USE. Turns on compiler debug mode. Ruby will print a bunch of internal state messages during compila‐ tion. Only specify this switch you are going to debug the Ruby interpreter. --disable-FEATURE --enable-FEATURE Disables (or enables) the specified FEATURE. --disable-gems --enable-gems Disables (or enables) RubyGems libraries. By default, Ruby will load the latest version of each installed gem. The Gem constant is true if RubyGems is enabled, false if otherwise. --disable-rubyopt --enable-rubyopt Ignores (or considers) the RUBYOPT environment variable. By default, Ruby consid‐ ers the variable. --disable-all --enable-all Disables (or enables) all features. --dump=target Dump some information. Prints the specified target. target can be one of; version version description same as --version usage brief usage message same as -h help Show long help message same as --help syntax check of syntax same as -c --yydebug yydebug compiler debug mode, same as --yydebug Only specify this switch if you are going to debug the Ruby interpreter. parsetree parsetree_with_comment AST nodes tree Only specify this switch if you are going to debug the Ruby interpreter. insns disassembled instructions Only specify this switch if you are going to debug the Ruby interpreter. --verbose Enables verbose mode without printing version message at the beginning. It sets the $VERBOSE vari‐ able to true. If this switch is given, and no script arguments (script file or -e options) are present, Ruby quits immediately. ENVIRONMENT RUBYLIB A colon-separated list of directories that are added to Ruby's library load path ($:). Directories from this environment variable are searched before the standard load path is searched. e.g.: RUBYLIB="$HOME/lib/ruby:$HOME/lib/rubyext" RUBYOPT Additional Ruby options. e.g. RUBYOPT="-w -Ke" Note that RUBYOPT can contain only -d, -E, -I, -K, -r, -T, -U, -v, -w, -W, --debug, --disable-FEATURE and --enable-FEATURE. RUBYPATH A colon-separated list of directories that Ruby searches for Ruby programs when the -S flag is speci‐ fied. This variable precedes the PATH environment variable. RUBYSHELL The path to the system shell command. This environment variable is enabled for only mswin32, mingw32, and OS/2 platforms. If this variable is not defined, Ruby refers to COMSPEC. PATH Ruby refers to the PATH environment variable on calling Kernel#system. And Ruby depends on some RubyGems related environment variables unless RubyGems is disabled. See the help of gem(1) as below. % gem help GC ENVIRONMENT The Ruby garbage collector (GC) tracks objects in fixed-sized slots, but each object may have auxiliary memory al‐ locations handled by the malloc family of C standard library calls ( malloc(3), calloc(3), and realloc(3)). In this documentatation, the "heap" refers to the Ruby object heap of fixed-sized slots, while "malloc" refers to aux‐ iliary allocations commonly referred to as the "process heap". Thus there are at least two possible ways to trig‐ ger GC: 1 Reaching the object limit. 2 Reaching the malloc limit. In Ruby 2.1, the generational GC was introduced and the limits are divided into young and old generations, provid‐ ing two additional ways to trigger a GC: 3 Reaching the old object limit. 4 Reaching the old malloc limit. There are currently 4 possible areas where the GC may be tuned by the following 11 environment variables: RUBY_GC_HEAP_INIT_SLOTS Initial allocation slots. Introduced in Ruby 2.1, default: 10000. RUBY_GC_HEAP_FREE_SLOTS Prepare at least this amount of slots after GC. Allocate this number slots if there are not enough slots. Introduced in Ruby 2.1, default: 4096 RUBY_GC_HEAP_GROWTH_FACTOR Increase allocation rate of heap slots by this factor. Introduced in Ruby 2.1, default: 1.8, minimum: 1.0 (no growth) RUBY_GC_HEAP_GROWTH_MAX_SLOTS Allocation rate is limited to this number of slots, preventing excessive al‐ location due to RUBY_GC_HEAP_GROWTH_FACTOR. Introduced in Ruby 2.1, de‐ fault: 0 (no limit) RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR Perform a full GC when the number of old objects is more than R * N, where R is this factor and N is the number of old objects after the last full GC. Introduced in Ruby 2.1.1, default: 2.0 RUBY_GC_MALLOC_LIMIT The initial limit of young generation allocation from the malloc-family. GC will start when this limit is reached. Default: 16MB RUBY_GC_MALLOC_LIMIT_MAX The maximum limit of young generation allocation from malloc before GC starts. Prevents excessive malloc growth due to RUBY_GC_MAL‐ LOC_LIMIT_GROWTH_FACTOR. Introduced in Ruby 2.1, default: 32MB. RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR Increases the limit of young generation malloc calls, reducing GC frequency but increasing malloc growth until RUBY_GC_MALLOC_LIMIT_MAX is reached. In‐ troduced in Ruby 2.1, default: 1.4, minimum: 1.0 (no growth) RUBY_GC_OLDMALLOC_LIMIT The initial limit of old generation allocation from malloc, a full GC will start when this limit is reached. Introduced in Ruby 2.1, default: 16MB RUBY_GC_OLDMALLOC_LIMIT_MAX The maximum limit of old generation allocation from malloc before a full GC starts. Prevents excessive malloc growth due to RUBY_GC_OLDMAL‐ LOC_LIMIT_GROWTH_FACTOR. Introduced in Ruby 2.1, default: 128MB RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR Increases the limit of old generation malloc allocation, reducing full GC frequency but increasing malloc growth until RUBY_GC_OLDMALLOC_LIMIT_MAX is reached. Introduced in Ruby 2.1, default: 1.2, minimum: 1.0 (no growth) STACK SIZE ENVIRONMENT Stack size environment variables are implementation-dependent and subject to change with different versions of Ruby. The VM stack is used for pure-Ruby code and managed by the virtual machine. Machine stack is used by the operating system and its usage is dependent on C extensions as well as C compiler options. Using lower values for these may allow applications to keep more Fibers or Threads running; but increases the chance of SystemStackError exceptions and segmentation faults (SIGSEGV). These environment variables are available since Ruby 2.0.0. All values are specified in bytes. RUBY_THREAD_VM_STACK_SIZE VM stack size used at thread creation. default: 524288 (32-bit CPU) or 1048575 (64-bit) RUBY_THREAD_MACHINE_STACK_SIZE Machine stack size used at thread creation. default: 524288 or 1048575 RUBY_FIBER_VM_STACK_SIZE VM stack size used at fiber creation. default: 65536 or 131072 RUBY_FIBER_MACHINE_STACK_SIZE Machine stack size used at fiber creation. default: 262144 or 524288 SEE ALSO https://www.ruby-lang.org/ The official web site. https://www.ruby-toolbox.com/ Comprehensive catalog of Ruby libraries. REPORTING BUGS • Security vulnerabilities should be reported via an email to [email protected]. Reported problems will be published after being fixed. • Other bugs and feature requests can be reported via the Ruby Issue Tracking System (https://bugs.ruby- lang.org/). Do not report security vulnerabilities via this system because it publishes the vulnerabilities immediately. AUTHORS Ruby is designed and implemented by Yukihiro Matsumoto <[email protected]>. See ⟨https://bugs.ruby-lang.org/projects/ruby/wiki/Contributors⟩ for contributors to Ruby. UNIX April 14, 2018 RUBY(1)

March 10, 2025

readelfコマンドメモ

はじめに ELFファイルを読むときに使うが、よく忘れるのでメモ。 よく使うオプション ヘッダだけ表示 readelf --file-header <filepath> 全ての情報を表示 readelf --all <filepath> man readelfより引用 READELF(1) GNU Development Tools READELF(1) NAME readelf - display information about ELF files SYNOPSIS readelf [-a|--all] [-h|--file-header] [-l|--program-headers|--segments] [-S|--section-headers|--sections] [-g|--section-groups] [-t|--section-details] [-e|--headers] [-s|--syms|--symbols] [--dyn-syms|--lto-syms] [--sym-base=[0|8|10|16]] [--demangle=style|--no-demangle] [--quiet] [--recurse-limit|--no-recurse-limit] [-U method|--unicode=method] [-X|--extra-sym-info|--no-extra-sym-info] [-n|--notes] [-r|--relocs] [-u|--unwind] [-d|--dynamic] [-V|--version-info] [-A|--arch-specific] [-D|--use-dynamic] [-L|--lint|--enable-checks] [-x <number or name>|--hex-dump=<number or name>] [-p <number or name>|--string-dump=<number or name>] [-R <number or name>|--relocated-dump=<number or name>] [-z|--decompress] [-c|--archive-index] [-w[lLiaprmfFsoORtUuTgAck]| --debug-dump[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,=frames-interp,=str,=str-offsets,=loc,=Ranges,=pubtypes,=trace_info,=trace_abbrev,=trace_aranges,=gdb_index,=addr,=cu_index,=links]] [-wK|--debug-dump=follow-links] [-wN|--debug-dump=no-follow-links] [-wD|--debug-dump=use-debuginfod] [-wE|--debug-dump=do-not-use-debuginfod] [-P|--process-links] [--dwarf-depth=n] [--dwarf-start=n] [--ctf=section] [--ctf-parent=section] [--ctf-symbols=section] [--ctf-strings=section] [--sframe=section] [-I|--histogram] [-v|--version] [-W|--wide] [-T|--silent-truncation] [-H|--help] elffile... DESCRIPTION readelf displays information about one or more ELF format object files. The options control what particular information to display. elffile... are the object files to be examined. 32-bit and 64-bit ELF files are supported, as are archives containing ELF files. This program performs a similar function to objdump but it goes into more detail and it exists independently of the BFD library, so if there is a bug in BFD then readelf will not be affected. OPTIONS The long and short forms of options, shown here as alternatives, are equivalent. At least one option besides -v or -H must be given. -a --all Equivalent to specifying --file-header, --program-headers, --sections, --symbols, --relocs, --dynamic, --notes, --version-info, --arch-specific, --unwind, --section-groups and --histogram. Note - this option does not enable --use-dynamic itself, so if that option is not present on the command line then dynamic symbols and dynamic relocs will not be displayed. -h --file-header Displays the information contained in the ELF header at the start of the file. -l --program-headers --segments Displays the information contained in the file's segment headers, if it has any. --quiet Suppress "no symbols" diagnostic. -S --sections --section-headers Displays the information contained in the file's section headers, if it has any. -g --section-groups Displays the information contained in the file's section groups, if it has any. -t --section-details Displays the detailed section information. Implies -S. -s --symbols --syms Displays the entries in symbol table section of the file, if it has one. If a symbol has version information associated with it then this is displayed as well. The version string is displayed as a suffix to the symbol name, preceded by an @ character. For example foo@VER_1. If the version is the default version to be used when resolving unversioned references to the symbol then it is displayed as a suffix preceded by two @ characters. For example foo@@VER_2. --dyn-syms Displays the entries in dynamic symbol table section of the file, if it has one. The output format is the same as the format used by the --syms option. --lto-syms Displays the contents of any LTO symbol tables in the file. --sym-base=[0|8|10|16] Forces the size field of the symbol table to use the given base. Any unrecognized options will be treated as 0. --sym-base=0 represents the default and legacy behaviour. This will output sizes as decimal for numbers less than 100000. For sizes 100000 and greater hexadecimal notation will be used with a 0x prefix. --sym-base=8 will give the symbol sizes in octal. --sym-base=10 will always give the symbol sizes in decimal. --sym-base=16 will always give the symbol sizes in hexadecimal with a 0x prefix. -C --demangle[=style] Decode (demangle) low-level symbol names into user-level names. This makes C++ function names readable. Different compilers have different mangling styles. The optional demangling style argument can be used to choose an appropriate demangling style for your compiler. --no-demangle Do not demangle low-level symbol names. This is the default. --recurse-limit --no-recurse-limit --recursion-limit --no-recursion-limit Enables or disables a limit on the amount of recursion performed whilst demangling strings. Since the name mangling formats allow for an infinite level of recursion it is possible to create strings whose decoding will exhaust the amount of stack space available on the host machine, triggering a memory fault. The limit tries to prevent this from happening by restricting recursion to 2048 levels of nesting. The default is for this limit to be enabled, but disabling it may be necessary in order to demangle truly complicated names. Note however that if the recursion limit is disabled then stack exhaustion is possible and any bug reports about such an event will be rejected. -U [d|i|l|e|x|h] --unicode=[default|invalid|locale|escape|hex|highlight] Controls the display of non-ASCII characters in identifier names. The default (--unicode=locale or --unicode=default) is to treat them as multibyte characters and display them in the current locale. All other versions of this option treat the bytes as UTF-8 encoded values and attempt to interpret them. If they cannot be interpreted or if the --unicode=invalid option is used then they are displayed as a sequence of hex bytes, encloses in curly parethesis characters. Using the --unicode=escape option will display the characters as as unicode escape sequences (\uxxxx). Using the --unicode=hex will display the characters as hex byte sequences enclosed between angle brackets. Using the --unicode=highlight will display the characters as unicode escape sequences but it will also highlighted them in red, assuming that colouring is supported by the output device. The colouring is intended to draw attention to the presence of unicode sequences when they might not be expected. -X --extra-sym-info When displaying details of symbols, include extra information not normally presented. Currently this just adds the name of the section referenced by the symbol's index field, if there is one. In the future more information may be displayed when this option is enabled. Enabling this option effectively enables the --wide option as well, at least when displaying symbol information. --no-extra-sym-info Disables the effect of the --extra-sym-info option. This is the default. -e --headers Display all the headers in the file. Equivalent to -h -l -S. -n --notes Displays the contents of the NOTE segments and/or sections, if any. -r --relocs Displays the contents of the file's relocation section, if it has one. -u --unwind Displays the contents of the file's unwind section, if it has one. Only the unwind sections for IA64 ELF files, as well as ARM unwind tables (".ARM.exidx" / ".ARM.extab") are currently supported. If support is not yet implemented for your architecture you could try dumping the contents of the .eh_frames section using the --debug-dump=frames or --debug-dump=frames-interp options. -d --dynamic Displays the contents of the file's dynamic section, if it has one. -V --version-info Displays the contents of the version sections in the file, it they exist. -A --arch-specific Displays architecture-specific information in the file, if there is any. -D --use-dynamic When displaying symbols, this option makes readelf use the symbol hash tables in the file's dynamic section, rather than the symbol table sections. When displaying relocations, this option makes readelf display the dynamic relocations rather than the static relocations. -L --lint --enable-checks Displays warning messages about possible problems with the file(s) being examined. If used on its own then all of the contents of the file(s) will be examined. If used with one of the dumping options then the warning messages will only be produced for the things being displayed. -x <number or name> --hex-dump=<number or name> Displays the contents of the indicated section as a hexadecimal bytes. A number identifies a particular section by index in the section table; any other string identifies all sections with that name in the object file. -R <number or name> --relocated-dump=<number or name> Displays the contents of the indicated section as a hexadecimal bytes. A number identifies a particular section by index in the section table; any other string identifies all sections with that name in the object file. The contents of the section will be relocated before they are displayed. -p <number or name> --string-dump=<number or name> Displays the contents of the indicated section as printable strings. A number identifies a particular section by index in the section table; any other string identifies all sections with that name in the object file. -z --decompress Requests that the section(s) being dumped by x, R or p options are decompressed before being displayed. If the section(s) are not compressed then they are displayed as is. -c --archive-index Displays the file symbol index information contained in the header part of binary archives. Performs the same function as the t command to ar, but without using the BFD library. -w[lLiaprmfFsOoRtUuTgAckK] --debug-dump[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,=frames-interp,=str,=str-offsets,=loc,=Ranges,=pubtypes,=trace_info,=trace_abbrev,=trace_aranges,=gdb_index,=addr,=cu_index,=links,=follow-links] Displays the contents of the DWARF debug sections in the file, if any are present. Compressed debug sections are automatically decompressed (temporarily) before they are displayed. If one or more of the optional letters or words follows the switch then only those type(s) of data will be dumped. The letters and words refer to the following information: "a" "=abbrev" Displays the contents of the .debug_abbrev section. "A" "=addr" Displays the contents of the .debug_addr section. "c" "=cu_index" Displays the contents of the .debug_cu_index and/or .debug_tu_index sections. "f" "=frames" Display the raw contents of a .debug_frame section. "F" "=frames-interp" Display the interpreted contents of a .debug_frame section. "g" "=gdb_index" Displays the contents of the .gdb_index and/or .debug_names sections. "i" "=info" Displays the contents of the .debug_info section. Note: the output from this option can also be restricted by the use of the --dwarf-depth and --dwarf-start options. "k" "=links" Displays the contents of the .gnu_debuglink, .gnu_debugaltlink and .debug_sup sections, if any of them are present. Also displays any links to separate dwarf object files (dwo), if they are specified by the DW_AT_GNU_dwo_name or DW_AT_dwo_name attributes in the .debug_info section. "K" "=follow-links" Display the contents of any selected debug sections that are found in linked, separate debug info file(s). This can result in multiple versions of the same debug section being displayed if it exists in more than one file. In addition, when displaying DWARF attributes, if a form is found that references the separate debug info file, then the referenced contents will also be displayed. Note - in some distributions this option is enabled by default. It can be disabled via the N debug option. The default can be chosen when configuring the binutils via the --enable-follow-debug-links=yes or --enable-follow-debug-links=no options. If these are not used then the default is to enable the following of debug links. Note - if support for the debuginfod protocol was enabled when the binutils were built then this option will also include an attempt to contact any debuginfod servers mentioned in the DEBUGINFOD_URLS environment variable. This could take some time to resolve. This behaviour can be disabled via the =do-not-use-debuginfod debug option. "N" "=no-follow-links" Disables the following of links to separate debug info files. "D" "=use-debuginfod" Enables contacting debuginfod servers if there is a need to follow debug links. This is the default behaviour. "E" "=do-not-use-debuginfod" Disables contacting debuginfod servers when there is a need to follow debug links. "l" "=rawline" Displays the contents of the .debug_line section in a raw format. "L" "=decodedline" Displays the interpreted contents of the .debug_line section. "m" "=macro" Displays the contents of the .debug_macro and/or .debug_macinfo sections. "o" "=loc" Displays the contents of the .debug_loc and/or .debug_loclists sections. "O" "=str-offsets" Displays the contents of the .debug_str_offsets section. "p" "=pubnames" Displays the contents of the .debug_pubnames and/or .debug_gnu_pubnames sections. "r" "=aranges" Displays the contents of the .debug_aranges section. "R" "=Ranges" Displays the contents of the .debug_ranges and/or .debug_rnglists sections. "s" "=str" Displays the contents of the .debug_str, .debug_line_str and/or .debug_str_offsets sections. "t" "=pubtype" Displays the contents of the .debug_pubtypes and/or .debug_gnu_pubtypes sections. "T" "=trace_aranges" Displays the contents of the .trace_aranges section. "u" "=trace_abbrev" Displays the contents of the .trace_abbrev section. "U" "=trace_info" Displays the contents of the .trace_info section. Note: displaying the contents of .debug_static_funcs, .debug_static_vars and debug_weaknames sections is not currently supported. --dwarf-depth=n Limit the dump of the ".debug_info" section to n children. This is only useful with --debug-dump=info. The default is to print all DIEs; the special value 0 for n will also have this effect. With a non-zero value for n, DIEs at or deeper than n levels will not be printed. The range for n is zero-based. --dwarf-start=n Print only DIEs beginning with the DIE numbered n. This is only useful with --debug-dump=info. If specified, this option will suppress printing of any header information and all DIEs before the DIE numbered n. Only siblings and children of the specified DIE will be printed. This can be used in conjunction with --dwarf-depth. -P --process-links Display the contents of non-debug sections found in separate debuginfo files that are linked to the main file. This option automatically implies the -wK option, and only sections requested by other command line options will be displayed. --ctf[=section] Display the contents of the specified CTF section. CTF sections themselves contain many subsections, all of which are displayed in order. By default, display the name of the section named .ctf, which is the name emitted by ld. --ctf-parent=member If the CTF section contains ambiguously-defined types, it will consist of an archive of many CTF dictionaries, all inheriting from one dictionary containing unambiguous types. This member is by default named .ctf, like the section containing it, but it is possible to change this name using the "ctf_link_set_memb_name_changer" function at link time. When looking at CTF archives that have been created by a linker that uses the name changer to rename the parent archive member, --ctf-parent can be used to specify the name used for the parent. --ctf-symbols=section --ctf-strings=section Specify the name of another section from which the CTF file can inherit strings and symbols. By default, the ".symtab" and its linked string table are used. If either of --ctf-symbols or --ctf-strings is specified, the other must be specified as well. -I --histogram Display a histogram of bucket list lengths when displaying the contents of the symbol tables. -v --version Display the version number of readelf. -W --wide Don't break output lines to fit into 80 columns. By default readelf breaks section header and segment listing lines for 64-bit ELF files, so that they fit into 80 columns. This option causes readelf to print each section header resp. each segment one a single line, which is far more readable on terminals wider than 80 columns. -T --silent-truncation Normally when readelf is displaying a symbol name, and it has to truncate the name to fit into an 80 column display, it will add a suffix of "[...]" to the name. This command line option disables this behaviour, allowing 5 more characters of the name to be displayed and restoring the old behaviour of readelf (prior to release 2.35). -H --help Display the command-line options understood by readelf. @file Read command-line options from file. The options read are inserted in place of the original @file option. If file does not exist, or cannot be read, then the option will be treated literally, and not removed. Options in file are separated by whitespace. A whitespace character may be included in an option by surrounding the entire option in either single or double quotes. Any character (including a backslash) may be included by prefixing the character to be included with a backslash. The file may itself contain additional @file options; any such options will be processed recursively. SEE ALSO objdump(1), and the Info entries for binutils. COPYRIGHT Copyright (c) 1991-2024 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". binutils-2.42 2025-02-05 READELF(1)

March 8, 2025

gpgコマンドメモ

はじめに rvmでrubyをインストールしようとしたところ実行要求されたコマンドにgpg2コマンドが含まれていたので学習メモ。 そもそも、GnuPGがあり、それのバージョンとして2系があり、これがgpg2として新しいコマンドになっているみたい。 しかし、それも今は昔、今ではgpgコマンドが2系として提供されていることが多い。 手元のUbuntuでは、逆にgpg2コマンドがgpgコマンドへのエイリアスになっていた。 gpgコマンド自体は用意されている。 which gpg /usr/bin/gpg 今でも、gpg2コマンド自体は用意されている。 which gpg2 /usr/bin/gpg2 ただし、それはgpgコマンドへのエイリアスになっている。 which gpg2 lrwxrwxrwx 1 root root 3 Apr 7 2024 /usr/bin/gpg2 -> gpg gpgのバージョンは2系。 gpg --version gpg (GnuPG) 2.4.4 libgcrypt 1.10.3 Copyright (C) 2024 g10 Code GmbH License GNU GPL-3.0-or-later <https://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Home: /home/ubuntu/.gnupg Supported algorithms: Pubkey: RSA, ELG, DSA, ECDH, ECDSA, EDDSA Cipher: IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH, CAMELLIA128, CAMELLIA192, CAMELLIA256 Hash: SHA1, RIPEMD160, SHA256, SHA384, SHA512, SHA224 Compression: Uncompressed, ZIP, ZLIB, BZIP2 gpg2のバージョンももちろん2系(エイリアスなので、0番目のコマンドライン引数に依存してなければ結果は同じになるはず)。 ...

March 6, 2025

rvm学習メモ

はじめに rvmコマンドについてよく忘れるのでメモする。 気づいたこと rvm は、デフォルトでOpenSSLとリンクしない。 rvm reinstall ruby-3.1.0 --with-openssl で、opensslと一緒にビルドできる(manにない…)。 ruby -ropenssl -e 'puts OpenSSL::OPENSSL_VERSION' で、rubyがopensslを利用可能な状態かわかる。 RVM コマンド チートシート 1. RVM とは RVM (Ruby Version Manager) は、Ruby のバージョン管理ツール。 複数の Ruby バージョンをインストール・切り替えでき、プロジェクトごとに異なるバージョンを使用可能。 2. RVM のインストール コマンド 説明 \curl -sSL https://get.rvm.io | bash -s stable RVM のインストール source ~/.rvm/scripts/rvm RVM の環境を適用 3. Ruby のインストール・管理 コマンド 説明 rvm list known インストール可能な Ruby のバージョン一覧を表示 rvm install 3.2.0 指定した Ruby バージョンをインストール rvm uninstall 3.1.0 指定した Ruby バージョンをアンインストール rvm list インストール済みの Ruby バージョン一覧を表示 rvm use 3.2.0 指定した Ruby バージョンを使用 rvm --default use 3.2.0 デフォルトの Ruby バージョンを設定 rvm current 現在使用中の Ruby バージョンを表示 4. Gemset の管理 コマンド 説明 rvm gemset list 現在の Ruby バージョンの Gemset を一覧表示 rvm gemset create mygemset Gemset を作成 rvm gemset use mygemset 指定した Gemset を使用 rvm --default gemset use mygemset デフォルトの Gemset を設定 rvm gemset delete mygemset 指定した Gemset を削除 5. プロジェクトごとの Ruby バージョン設定 コマンド 説明 echo "3.2.0" > .ruby-version プロジェクトディレクトリで Ruby バージョンを指定 echo "mygemset" > .ruby-gemset プロジェクトディレクトリで Gemset を指定 rvm use . .ruby-version と .ruby-gemset を適用 6. RVM の更新・削除 コマンド 説明 rvm get stable RVM を最新の安定版に更新 rvm reload RVM の設定をリロード rvm implode RVM を完全に削除 7. まとめ RVM は Ruby のバージョンを柔軟に管理できる Gemset を活用するとプロジェクトごとに独立した環境を構築できる .ruby-version や .ruby-gemset を設定すると、プロジェクトごとに自動でバージョンが切り替わる RVM を適切に活用し、開発環境を整理しよう! ...

March 6, 2025

nvim学習メモ

はじめに よく忘れるのでメモ。 私の環境はastronvimなので、これについても書く。 レジスタを見る コマンド 内容 :registers(:reg) レジスタの一覧を見る :echo @a 特定のレジスタの値を見る registers の読み方 "<register名>: レジスタ名 ダブルクォートのあとにレジスタ名がある。 Type Name Content c "" aaa l "0 bbb^J … … … Typeの意味 Type 意味 c 文字(Character) l 行(Line) b ブロック(Block) レジスタの値に含まれる、^Jは何? 改行。行単位でレジスタに入っている場合、基本的に含まれる。 nvimでは、\nが^Jで表現されるらしい。 また、astronvimにおいては、"を押すとregisters一覧が見られる。 このときには、改行文字は消されて表示される。 レジスタの名前ごとの役割 レジスタは名前と役割が対応している。下記に示す。 レジスタ一覧 レジスタ 役割 説明 " (無名レジスタ) デフォルト yank (y), delete (d), change (c) の操作で自動的に使用される 0 最新のヤンク 直近の yank (y) でコピーされたテキスト 1~9 削除履歴 delete (d), change (c) で削除されたテキストが保存される (1 が最新) a~z 名前付き マクロ用。"ay や "ap のように指定して使用可能。追記 ("A など大文字) も可能 * クリップボード (X11) X11 の PRIMARY クリップボード (選択テキスト) + クリップボード X11 の CLIPBOARD または Windows/macOS のシステムクリップボード - 小レジスタ 短い削除テキストを保存 (行をまたがない削除・変更) . 最後に挿入したテキスト 直前の i/a/o で挿入したテキスト % 現在のファイル名 カレントバッファのファイル名を取得 : コマンド履歴 直近の Ex コマンド (: で実行したコマンド) # 代替ファイル名 CTRL-^ で切り替えられる直前のバッファのファイル名 = 式レジスタ "=3+4 のように入力して計算結果を取得 _ ブラックホール /dev/null のようなもの。ここに保存するとテキストが完全に破棄される 実験で気づいたこと [や!などの存在しないレジスタ名をペーストすると、無名レジスタの値が利用される 一方、#レジスタの値がないときに#レジスタの値をペーストしようとするとエラーが出る ddやccで行削除した値は、ちゃんと1-9のレジスタにLILOで、入っていくのに、sやdiw、ciwなどだと無名レジスタや-レジスタに入るだけ、履歴は保存されない。 Type=cのレジスタは、値の途中に^Jが入ることがない。 Type=bのレジスタは、値の途中に^Jが入る場合はあるが、最後に入ることはない。 :putおよびインサートモードの<Ctrl>-rの場合、珍しくレジスタを指定する際に"をつける必要がない。 +にWindows/macOSとあるが、Ubuntuでも同様に動作した。 自分のUbuntu環境の場合、基本的に*は空であった。 d$で消した場合は、Type=cでレジスタに保存される(最後の改行は消されないし、レジスタに保存もされない)。 ビジュアルブロックモードで削除した場合、blockとして削除履歴に保存される。 式レジスタ(=)の使い方 "= を押して式レジスタに設定したい値を入力。エンターで決定。 ...

March 5, 2025

manコマンドメモ

はじめに man の使い方をメモ 例 man 3 strncpy これは、C標準ライブラリのLinux実装(つまり、glibc実装)。 https://man7.org/linux/man-pages/man3/strncpy.3.html man manより引用 MAN(1) Manual pager utils MAN(1) NAME man - an interface to the system reference manuals SYNOPSIS man [man options] [[section] page ...] ... man -k [apropos options] regexp ... man -K [man options] [section] term ... man -f [whatis options] page ... man -l [man options] file ... man -w|-W [man options] page ... DESCRIPTION man is the system's manual pager. Each page argument given to man is normally the name of a program, utility or function. The manual page associated with each of these arguments is then found and displayed. A section, if provided, will direct man to look only in that section of the manual. The default action is to search in all of the available sections following a pre-defined order (see DEFAULTS), and to show only the first page found, even if page exists in several sections. The table below shows the section numbers of the manual followed by the types of pages they contain. 1 Executable programs or shell commands 2 System calls (functions provided by the kernel) 3 Library calls (functions within program libraries) 4 Special files (usually found in /dev) 5 File formats and conventions, e.g. /etc/passwd 6 Games 7 Miscellaneous (including macro packages and conventions), e.g. man(7), groff(7), man-pages(7) 8 System administration commands (usually only for root) 9 Kernel routines [Non standard] A manual page consists of several sections. Conventional section names include NAME, SYNOPSIS, CONFIGURATION, DESCRIPTION, OPTIONS, EXIT STATUS, RETURN VALUE, ERRORS, ENVIRONMENT, FILES, VERSIONS, STANDARDS, NOTES, BUGS, EXAMPLE, AUTHORS, and SEE ALSO. The following conventions apply to the SYNOPSIS section and can be used as a guide in other sections. bold text type exactly as shown. italic text replace with appropriate argument. [-abc] any or all arguments within [ ] are optional. -a|-b options delimited by | cannot be used together. argument ... argument is repeatable. [expression] ... entire expression within [ ] is repeatable. Exact rendering may vary depending on the output device. For instance, man will usually not be able to render italics when running in a terminal, and will typically use underlined or coloured text instead. The command or function illustration is a pattern that should match all possible invocations. In some cases it is advisable to illus‐ trate several exclusive invocations as is shown in the SYNOPSIS section of this manual page. EXAMPLES man ls Display the manual page for the item (program) ls. man man.7 Display the manual page for macro package man from section 7. (This is an alternative spelling of "man 7 man".) man 'man(7)' Display the manual page for macro package man from section 7. (This is another alternative spelling of "man 7 man". It may be more convenient when copying and pasting cross-references to manual pages. Note that the parentheses must normally be quoted to protect them from the shell.) man -a intro Display, in succession, all of the available intro manual pages contained within the manual. It is possible to quit between suc‐ cessive displays or skip any of them. man -t bash | lpr -Pps Format the manual page for bash into the default troff or groff format and pipe it to the printer named ps. The default output for groff is usually PostScript. man --help should advise as to which processor is bound to the -t option. man -l -Tdvi ./foo.1x.gz > ./foo.1x.dvi This command will decompress and format the nroff source manual page ./foo.1x.gz into a device independent (dvi) file. The redi‐ rection is necessary as the -T flag causes output to be directed to stdout with no pager. The output could be viewed with a pro‐ gram such as xdvi or further processed into PostScript using a program such as dvips. man -k printf Search the short descriptions and manual page names for the keyword printf as regular expression. Print out any matches. Equiva‐ lent to apropos printf. man -f smail Lookup the manual pages referenced by smail and print out the short descriptions of any found. Equivalent to whatis smail. OVERVIEW Many options are available to man in order to give as much flexibility as possible to the user. Changes can be made to the search path, section order, output processor, and other behaviours and operations detailed below. If set, various environment variables are interrogated to determine the operation of man. It is possible to set the "catch-all" vari‐ able $MANOPT to any string in command line format, with the exception that any spaces used as part of an option's argument must be es‐ caped (preceded by a backslash). man will parse $MANOPT prior to parsing its own command line. Those options requiring an argument will be overridden by the same options found on the command line. To reset all of the options set in $MANOPT, -D can be specified as the initial command line option. This will allow man to "forget" about the options specified in $MANOPT, although they must still have been valid. Manual pages are normally stored in nroff(1) format under a directory such as /usr/share/man. In some installations, there may also be preformatted cat pages to improve performance. See manpath(5) for details of where these files are stored. This package supports manual pages in multiple languages, controlled by your locale. If your system did not set this up for you auto‐ matically, then you may need to set $LC_MESSAGES, $LANG, or another system-dependent environment variable to indicate your preferred locale, usually specified in the POSIX format: <language>[_<territory>[.<character-set>[,<version>]]] If the desired page is available in your locale, it will be displayed in lieu of the standard (usually American English) page. If you find that the translations supplied with this package are not available in your native language and you would like to supply them, please contact the maintainer who will be coordinating such activity. Individual manual pages are normally written and maintained by the maintainers of the program, function, or other topic that they docu‐ ment, and are not included with this package. If you find that a manual page is missing or inadequate, please report that to the main‐ tainers of the package in question. For information regarding other features and extensions available with this manual pager, please read the documents supplied with the package. DEFAULTS The order of sections to search may be overridden by the environment variable $MANSECT or by the SECTION directive in /etc/manpath.con‐ fig. By default it is as follows: 1 n l 8 3 0 2 3type 3posix 3pm 3perl 3am 5 4 9 6 7 The formatted manual page is displayed using a pager. This can be specified in a number of ways, or else will fall back to a default (see option -P for details). The filters are deciphered by a number of means. Firstly, the command line option -p or the environment variable $MANROFFSEQ is inter‐ rogated. If -p was not used and the environment variable was not set, the initial line of the nroff file is parsed for a preprocessor string. To contain a valid preprocessor string, the first line must resemble '\" <string> where string can be any combination of letters described by option -p below. If none of the above methods provide any filter information, a default set is used. A formatting pipeline is formed from the filters and the primary formatter (nroff or [tg]roff with -t) and executed. Alternatively, if an executable program mandb_nfmt (or mandb_tfmt with -t) exists in the man tree root, it is executed instead. It gets passed the man‐ ual source file, the preprocessor string, and optionally the device specified with -T or -E as arguments. OPTIONS Non-argument options that are duplicated either on the command line, in $MANOPT, or both, are not harmful. For options that require an argument, each duplication will override the previous argument value. General options -C file, --config-file=file Use this user configuration file rather than the default of ~/.manpath. -d, --debug Print debugging information. -D, --default This option is normally issued as the very first option and resets man's behaviour to its default. Its use is to reset those options that may have been set in $MANOPT. Any options that follow -D will have their usual effect. --warnings[=warnings] Enable warnings from groff. This may be used to perform sanity checks on the source text of manual pages. warnings is a comma- separated list of warning names; if it is not supplied, the default is "mac". To disable a groff warning, prefix it with "!": for example, --warnings=mac,!break enables warnings in the "mac" category and disables warnings in the "break" category. See the “Warnings” node in info groff for a list of available warning names. Main modes of operation -f, --whatis Approximately equivalent to whatis. Display a short description from the manual page, if available. See whatis(1) for details. -k, --apropos Approximately equivalent to apropos. Search the short manual page descriptions for keywords and display any matches. See apro‐ pos(1) for details. -K, --global-apropos Search for text in all manual pages. This is a brute-force search, and is likely to take some time; if you can, you should specify a section to reduce the number of pages that need to be searched. Search terms may be simple strings (the default), or regular expressions if the --regex option is used. Note that this searches the sources of the manual pages, not the rendered text, and so may include false positives due to things like comments in source files, or false negatives due to things like hyphens being written as "\-" in source files. Searching the rendered text would be much slower. -l, --local-file Activate "local" mode. Format and display local manual files instead of searching through the system's manual collection. Each manual page argument will be interpreted as an nroff source file in the correct format. No cat file is produced. If '-' is listed as one of the arguments, input will be taken from stdin. If this option is not used, then man will also fall back to interpreting manual page arguments as local file names if the argu‐ ment contains a "/" character, since that is a good indication that the argument refers to a path on the file system. -w, --where, --path, --location Don't actually display the manual page, but do print the location of the source nroff file that would be formatted. If the -a option is also used, then print the locations of all source files that match the search criteria. -W, --where-cat, --location-cat Don't actually display the manual page, but do print the location of the preformatted cat file that would be displayed. If the -a option is also used, then print the locations of all preformatted cat files that match the search criteria. If -w and -W are both used, then print both source file and cat file separated by a space. If all of -w, -W, and -a are used, then do this for each possible match. -c, --catman This option is not for general use and should only be used by the catman program. -R encoding, --recode=encoding Instead of formatting the manual page in the usual way, output its source converted to the specified encoding. If you already know the encoding of the source file, you can also use manconv(1) directly. However, this option allows you to convert several manual pages to a single encoding without having to explicitly state the encoding of each, provided that they were already in‐ stalled in a structure similar to a manual page hierarchy. Consider using man-recode(1) instead for converting multiple manual pages, since it has an interface designed for bulk conver‐ sion and so can be much faster. Finding manual pages -L locale, --locale=locale man will normally determine your current locale by a call to the C function setlocale(3) which interrogates various environment variables, possibly including $LC_MESSAGES and $LANG. To temporarily override the determined value, use this option to supply a locale string directly to man. Note that it will not take effect until the search for pages actually begins. Output such as the help message will always be displayed in the initially determined locale. -m system[,...], --systems=system[,...] If this system has access to other operating systems' manual pages, they can be accessed using this option. To search for a manual page from NewOS's manual page collection, use the option -m NewOS. The system specified can be a combination of comma delimited operating system names. To include a search of the native operat‐ ing system's manual pages, include the system name man in the argument string. This option will override the $SYSTEM environ‐ ment variable. -M path, --manpath=path Specify an alternate manpath to use. By default, man uses manpath derived code to determine the path to search. This option overrides the $MANPATH environment variable and causes option -m to be ignored. A path specified as a manpath must be the root of a manual page hierarchy structured into sections as described in the man-db manual (under "The manual page system"). To view manual pages outside such hierarchies, see the -l option. -S list, -s list, --sections=list The given list is a colon- or comma-separated list of sections, used to determine which manual sections to search and in what order. This option overrides the $MANSECT environment variable. (The -s spelling is for compatibility with System V.) -e sub-extension, --extension=sub-extension Some systems incorporate large packages of manual pages, such as those that accompany the Tcl package, into the main manual page hierarchy. To get around the problem of having two manual pages with the same name such as exit(3), the Tcl pages were usually all assigned to section l. As this is unfortunate, it is now possible to put the pages in the correct section, and to assign a specific "extension" to them, in this case, exit(3tcl). Under normal operation, man will display exit(3) in preference to exit(3tcl). To negotiate this situation and to avoid having to know which section the page you require resides in, it is now possible to give man a sub-extension string indicating which package the page must belong to. Using the above example, supply‐ ing the option -e tcl to man will restrict the search to pages having an extension of *tcl. -i, --ignore-case Ignore case when searching for manual pages. This is the default. -I, --match-case Search for manual pages case-sensitively. --regex Show all pages with any part of either their names or their descriptions matching each page argument as a regular expression, as with apropos(1). Since there is usually no reasonable way to pick a "best" page when searching for a regular expression, this option implies -a. --wildcard Show all pages with any part of either their names or their descriptions matching each page argument using shell-style wild‐ cards, as with apropos(1) --wildcard. The page argument must match the entire name or description, or match on word boundaries in the description. Since there is usually no reasonable way to pick a "best" page when searching for a wildcard, this option implies -a. --names-only If the --regex or --wildcard option is used, match only page names, not page descriptions, as with whatis(1). Otherwise, no ef‐ fect. -a, --all By default, man will exit after displaying the most suitable manual page it finds. Using this option forces man to display all the manual pages with names that match the search criteria. -u, --update This option causes man to update its database caches of installed manual pages. This is only needed in rare situations, and it is normally better to run mandb(8) instead. --no-subpages By default, man will try to interpret pairs of manual page names given on the command line as equivalent to a single manual page name containing a hyphen or an underscore. This supports the common pattern of programs that implement a number of subcommands, allowing them to provide manual pages for each that can be accessed using similar syntax as would be used to invoke the subcom‐ mands themselves. For example: $ man -aw git diff /usr/share/man/man1/git-diff.1.gz To disable this behaviour, use the --no-subpages option. $ man -aw --no-subpages git diff /usr/share/man/man1/git.1.gz /usr/share/man/man3/Git.3pm.gz /usr/share/man/man1/diff.1.gz Controlling formatted output -P pager, --pager=pager Specify which output pager to use. By default, man uses pager, falling back to cat if pager is not found or is not executable. This option overrides the $MANPAGER environment variable, which in turn overrides the $PAGER environment variable. It is not used in conjunction with -f or -k. The value may be a simple command name or a command with arguments, and may use shell quoting (backslashes, single quotes, or double quotes). It may not use pipes to connect multiple commands; if you need that, use a wrapper script, which may take the file to display either as an argument or on standard input. -r prompt, --prompt=prompt If a recent version of less is used as the pager, man will attempt to set its prompt and some sensible options. The default prompt looks like Manual page name(sec) line x where name denotes the manual page name, sec denotes the section it was found under and x the current line number. This is achieved by using the $LESS environment variable. Supplying -r with a string will override this default. The string may contain the text $MAN_PN which will be expanded to the name of the current manual page and its section name surrounded by "(" and ")". The string used to produce the default could be expressed as \ Manual\ page\ \$MAN_PN\ ?ltline\ %lt?L/%L.: byte\ %bB?s/%s..?\ (END):?pB\ %pB\\%.. (press h for help or q to quit) It is broken into three lines here for the sake of readability only. For its meaning see the less(1) manual page. The prompt string is first evaluated by the shell. All double quotes, back-quotes and backslashes in the prompt must be escaped by a pre‐ ceding backslash. The prompt string may end in an escaped $ which may be followed by further options for less. By default man sets the -ix8 options. The $MANLESS environment variable described below may be used to set a default prompt string if none is supplied on the command line. -7, --ascii When viewing a pure ascii(7) manual page on a 7 bit terminal or terminal emulator, some characters may not display correctly when using the latin1(7) device description with GNU nroff. This option allows pure ascii manual pages to be displayed in ascii with the latin1 device. It will not translate any latin1 text. The following table shows the translations performed: some parts of it may only be displayed properly when using GNU nroff's latin1(7) device. Description Octal latin1 ascii ───────────────────────────────────────────── continuation hyphen 255 ‐ - bullet (middle dot) 267 • o acute accent 264 ´ ' multiplication sign 327 × x If the latin1 column displays correctly, your terminal may be set up for latin1 characters and this option is not necessary. If the latin1 and ascii columns are identical, you are reading this page using this option or man did not format this page using the latin1 device description. If the latin1 column is missing or corrupt, you may need to view manual pages with this option. This option is ignored when using options -t, -H, -T, or -Z and may be useless for nroff other than GNU's. -E encoding, --encoding=encoding Generate output for a character encoding other than the default. For backward compatibility, encoding may be an nroff device such as ascii, latin1, or utf8 as well as a true character encoding such as UTF-8. --no-hyphenation, --nh Normally, nroff will automatically hyphenate text at line breaks even in words that do not contain hyphens, if it is necessary to do so to lay out words on a line without excessive spacing. This option disables automatic hyphenation, so words will only be hyphenated if they already contain hyphens. If you are writing a manual page and simply want to prevent nroff from hyphenating a word at an inappropriate point, do not use this option, but consult the nroff documentation instead; for instance, you can put "\%" inside a word to indicate that it may be hyphenated at that point, or put "\%" at the start of a word to prevent it from being hyphenated. --no-justification, --nj Normally, nroff will automatically justify text to both margins. This option disables full justification, leaving justified only to the left margin, sometimes called "ragged-right" text. If you are writing a manual page and simply want to prevent nroff from justifying certain paragraphs, do not use this option, but consult the nroff documentation instead; for instance, you can use the ".na", ".nf", ".fi", and ".ad" requests to temporar‐ ily disable adjusting and filling. -p string, --preprocessor=string Specify the sequence of preprocessors to run before nroff or troff/groff. Not all installations will have a full set of pre‐ processors. Some of the preprocessors and the letters used to designate them are: eqn (e), grap (g), pic (p), tbl (t), vgrind (v), refer (r). This option overrides the $MANROFFSEQ environment variable. zsoelim is always run as the very first preproces‐ sor. -t, --troff Use groff -mandoc to format the manual page to stdout. This option is not required in conjunction with -H, -T, or -Z. -T[device], --troff-device[=device] This option is used to change groff (or possibly troff's) output to be suitable for a device other than the default. It implies -t. Examples (provided with Groff-1.17) include dvi, latin1, ps, utf8, X75 and X100. -H[browser], --html[=browser] This option will cause groff to produce HTML output, and will display that output in a web browser. The choice of browser is determined by the optional browser argument if one is provided, by the $BROWSER environment variable, or by a compile-time de‐ fault if that is unset (usually lynx). This option implies -t, and will only work with GNU troff. -X[dpi], --gxditview[=dpi] This option displays the output of groff in a graphical window using the gxditview program. The dpi (dots per inch) may be 75, 75-12, 100, or 100-12, defaulting to 75; the -12 variants use a 12-point base font. This option implies -T with the X75, X75-12, X100, or X100-12 device respectively. -Z, --ditroff groff will run troff and then use an appropriate post-processor to produce output suitable for the chosen device. If groff -mandoc is groff, this option is passed to groff and will suppress the use of a post-processor. It implies -t. Getting help -?, --help Print a help message and exit. --usage Print a short usage message and exit. -V, --version Display version information. EXIT STATUS 0 Successful program execution. 1 Usage, syntax or configuration file error. 2 Operational error. 3 A child process returned a non-zero exit status. 16 At least one of the pages/files/keywords didn't exist or wasn't matched. ENVIRONMENT MANPATH If $MANPATH is set, its value is used as the path to search for manual pages. See the SEARCH PATH section of manpath(5) for the default behaviour and details of how this environment variable is handled. MANROFFOPT Every time man invokes the formatter (nroff, troff, or groff), it adds the contents of $MANROFFOPT to the formatter's command line. MANROFFSEQ If $MANROFFSEQ is set, its value is used to determine the set of preprocessors to pass each manual page through. The default preprocessor list is system dependent. MANSECT If $MANSECT is set, its value is a colon-delimited list of sections and it is used to determine which manual sections to search and in what order. The default is "1 n l 8 3 0 2 3type 3posix 3pm 3perl 3am 5 4 9 6 7", unless overridden by the SECTION direc‐ tive in /etc/manpath.config. MANPAGER, PAGER If $MANPAGER or $PAGER is set ($MANPAGER is used in preference), its value is used as the name of the program used to display the manual page. By default, pager is used, falling back to cat if pager is not found or is not executable. The value may be a simple command name or a command with arguments, and may use shell quoting (backslashes, single quotes, or double quotes). It may not use pipes to connect multiple commands; if you need that, use a wrapper script, which may take the file to display either as an argument or on standard input. MANLESS If $MANLESS is set, its value will be used as the default prompt string for the less pager, as if it had been passed using the -r option (so any occurrences of the text $MAN_PN will be expanded in the same way). For example, if you want to set the prompt string unconditionally to “my prompt string”, set $MANLESS to ‘-Psmy prompt string’. Using the -r option overrides this envi‐ ronment variable. BROWSER If $BROWSER is set, its value is a colon-delimited list of commands, each of which in turn is used to try to start a web browser for man --html. In each command, %s is replaced by a filename containing the HTML output from groff, %% is replaced by a single percent sign (%), and %c is replaced by a colon (:). SYSTEM If $SYSTEM is set, it will have the same effect as if it had been specified as the argument to the -m option. MANOPT If $MANOPT is set, it will be parsed prior to man's command line and is expected to be in a similar format. As all of the other man specific environment variables can be expressed as command line options, and are thus candidates for being included in $MANOPT it is expected that they will become obsolete. N.B. All spaces that should be interpreted as part of an option's argu‐ ment must be escaped. MANWIDTH If $MANWIDTH is set, its value is used as the line length for which manual pages should be formatted. If it is not set, manual pages will be formatted with a line length appropriate to the current terminal (using the value of $COLUMNS, and ioctl(2) if available, or falling back to 80 characters if neither is available). Cat pages will only be saved when the default formatting can be used, that is when the terminal line length is between 66 and 80 characters. MAN_KEEP_FORMATTING Normally, when output is not being directed to a terminal (such as to a file or a pipe), formatting characters are discarded to make it easier to read the result without special tools. However, if $MAN_KEEP_FORMATTING is set to any non-empty value, these formatting characters are retained. This may be useful for wrappers around man that can interpret formatting characters. MAN_KEEP_STDERR Normally, when output is being directed to a terminal (usually to a pager), any error output from the command used to produce formatted versions of manual pages is discarded to avoid interfering with the pager's display. Programs such as groff often produce relatively minor error messages about typographical problems such as poor alignment, which are unsightly and generally confusing when displayed along with the manual page. However, some users want to see them anyway, so, if $MAN_KEEP_STDERR is set to any non-empty value, error output will be displayed as usual. MAN_DISABLE_SECCOMP On Linux, man normally confines subprocesses that handle untrusted data using a seccomp(2) sandbox. This makes it safer to run complex parsing code over arbitrary manual pages. If this goes wrong for some reason unrelated to the content of the page being displayed, you can set $MAN_DISABLE_SECCOMP to any non-empty value to disable the sandbox. PIPELINE_DEBUG If the $PIPELINE_DEBUG environment variable is set to "1", then man will print debugging messages to standard error describing each subprocess it runs. LANG, LC_MESSAGES Depending on system and implementation, either or both of $LANG and $LC_MESSAGES will be interrogated for the current message locale. man will display its messages in that locale (if available). See setlocale(3) for precise details. FILES /etc/manpath.config man-db configuration file. /usr/share/man A global manual page hierarchy. STANDARDS POSIX.1-2001, POSIX.1-2008, POSIX.1-2017. SEE ALSO apropos(1), groff(1), less(1), manpath(1), nroff(1), troff(1), whatis(1), zsoelim(1), manpath(5), man(7), catman(8), mandb(8) Documentation for some packages may be available in other formats, such as info(1) or HTML. HISTORY 1990, 1991 – Originally written by John W. Eaton ([email protected]). Dec 23 1992: Rik Faith ([email protected]) applied bug fixes supplied by Willem Kasdorp ([email protected]). 30th April 1994 – 23rd February 2000: Wilf. ([email protected]) has been developing and maintaining this package with the help of a few dedicated people. 30th October 1996 – 30th March 2001: Fabrizio Polacco <[email protected]> maintained and enhanced this package for the Debian project, with the help of all the community. 31st March 2001 – present day: Colin Watson <[email protected]> is now developing and maintaining man-db. BUGS https://gitlab.com/man-db/man-db/-/issues https://savannah.nongnu.org/bugs/?group=man-db 2.12.0 2023-09-23 MAN(1)

March 3, 2025