├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── dkms-install.sh ├── dkms-remove.sh ├── dkms.conf ├── libip6t_FULLCONENAT.c ├── libipt_FULLCONENAT.c ├── libipt_FULLCONENAT.t └── xt_FULLCONENAT.c /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .tmp_versions 3 | *.ko 4 | *.cmd 5 | *.o 6 | *.so 7 | modules.order 8 | Module.symvers 9 | *.mod* 10 | .idea 11 | cmake* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | ccflags-y += -O3 2 | obj-m = xt_FULLCONENAT.o 3 | CFLAGS_xt_FULLCONENAT.o := ${CFLAGS} 4 | KVERSION = $(shell uname -r) 5 | XTABLES_LIBDIR ?= $(shell pkg-config xtables --variable=xtlibdir) 6 | 7 | %.so: %.o 8 | $(CC) -shared -lxtables -o $@ $^ 9 | %.o: %.c 10 | $(CC) ${CFLAGS} -fPIC -c -o $@ $< 11 | 12 | all: libipt_FULLCONENAT.so libip6t_FULLCONENAT.so 13 | $(MAKE) -C /lib/modules/$(KVERSION)/build M=$(PWD) modules 14 | strip --strip-debug xt_FULLCONENAT.ko 15 | clean: 16 | $(MAKE) -C /lib/modules/$(KVERSION)/build M=$(PWD) clean 17 | $(RM) libipt_FULLCONENAT.so libipt_FULLCONENAT.o libip6t_FULLCONENAT.so libip6t_FULLCONENAT.o 18 | install: all 19 | install -m 0644 libipt_FULLCONENAT.so libip6t_FULLCONENAT.so $(XTABLES_LIBDIR)/ 20 | .PHONY: all clean install -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | Implementation of RFC3489-compatible full cone SNAT. 3 | 4 | Assuming eth0 is external interface: 5 | ``` 6 | iptables -t nat -A POSTROUTING -o eth0 -j FULLCONENAT #same as MASQUERADE 7 | iptables -t nat -A PREROUTING -i eth0 -j FULLCONENAT #automatically restore NAT for inbound packets 8 | ``` 9 | Currently only UDP traffic is supported for full-cone NAT. For other protos FULLCONENAT is equivalent to MASQUERADE. 10 | 11 | Build 12 | ====== 13 | Prerequisites: 14 | * kernel source 15 | * iptables source ( git://git.netfilter.org/iptables.git ) 16 | 17 | Confirm the kernel configuration option `CONFIG_NF_CONNTRACK_EVENTS` is enabled. If this option is disabled on your system, enable it and rebuild your netfilter modules. 18 | 19 | Kernel Module 20 | ------------- 21 | ``` 22 | $ make 23 | # insmod xt_FULLCONENAT.ko 24 | ``` 25 | 26 | Iptables Extension 27 | ------------------ 28 | 29 | 1. Copy libipt_FULLCONENAT.c to `iptables-source/extensions`. 30 | 31 | 2. Under the iptables source directory, `./configure`(use `--prefix` to replace your current `iptables` by looking at `which iptables`), `make` and `make install` 32 | 33 | OpenWRT 34 | ------- 35 | Package for openwrt is available at https://github.com/LGA1150/openwrt-fullconenat 36 | 37 | Usage 38 | ===== 39 | 40 | Assuming eth0 is external interface: 41 | 42 | Basic Usage: 43 | 44 | ``` 45 | iptables -t nat -A POSTROUTING -o eth0 -j FULLCONENAT 46 | iptables -t nat -A PREROUTING -i eth0 -j FULLCONENAT 47 | ``` 48 | 49 | Random port range: 50 | 51 | ``` 52 | iptables -t nat -A POSTROUTING -o eth0 ! -p udp -j MASQUERADE 53 | iptables -t nat -A POSTROUTING -o eth0 -p udp -j FULLCONENAT --to-ports 40000-60000 --random-fully 54 | 55 | iptables -t nat -A PREROUTING -i eth0 -p udp -m multiport --dports 40000:60000 -j FULLCONENAT 56 | ``` 57 | 58 | Hairpin NAT (Assuming eth1 is LAN interface and IP range for LAN is 192.168.100.0/24): 59 | ``` 60 | iptables -t nat -A POSTROUTING -o eth0 -j FULLCONENAT 61 | iptables -t nat -A POSTROUTING -o eth1 -s 192.168.100.0/24 -j MASQUERADE 62 | iptables -t nat -A PREROUTING -i eth0 -j FULLCONENAT 63 | iptables -t nat -A PREROUTING -i eth1 -j FULLCONENAT 64 | ``` 65 | 66 | kernel Patch (Optional.) 67 | ======================== 68 | 1. Copy xt_FULLCONENAT.c to `kernel-source/net/netfilter/xt_FULLCONENAT.c` 69 | 2. Append following line to `kernel-source/net/netfilter/Makefile`: 70 | 71 | ``` 72 | obj-$(CONFIG_NETFILTER_XT_TARGET_FULLCONENAT) += xt_FULLCONENAT.o 73 | ``` 74 | 75 | 3. Insert following section into `kernel-source/net/ipv4/netfilter/Kconfig` right after `config IP_NF_TARGET_NETMAP` section: 76 | 77 | ``` 78 | config IP_NF_TARGET_FULLCONENAT 79 | tristate "FULLCONENAT target support" 80 | depends on NETFILTER_ADVANCED 81 | select NETFILTER_XT_TARGET_FULLCONENAT 82 | ---help--- 83 | This is a backwards-compat option for the user's convenience 84 | (e.g. when running oldconfig). It selects 85 | CONFIG_NETFILTER_XT_TARGET_FULLCONENAT. 86 | 87 | ``` 88 | 89 | 4. Insert following section into `kernel-source/net/netfilter/Kconfig` right after `config NETFILTER_XT_TARGET_NETMAP` section: 90 | 91 | ``` 92 | config NETFILTER_XT_TARGET_FULLCONENAT 93 | tristate '"FULLCONENAT" target support' 94 | depends on NF_NAT 95 | ---help--- 96 | Full Cone NAT 97 | 98 | To compile it as a module, choose M here. If unsure, say N. 99 | 100 | ``` 101 | 102 | 5. Run `make menuconfig` and select: 103 | Networking support -> Network options -> Network packet filtering framework (Netfilter) -> IP: Netfilter Configuration -> \ FULLCONENAT target support 104 | 105 | License 106 | ======= 107 | Copyright 2018 Chion Tang [betaidc](https://www.betaidc.com/contact.html) 108 | GPL-2.0 109 | See LICENSE 110 | -------------------------------------------------------------------------------- /dkms-install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | PKG_DIR="$(pwd)" 4 | PKG_NAME=fullconenat 5 | PKG_VERSION=1.0 6 | 7 | cp -r ${PKG_DIR} /usr/src/${PKG_NAME}-${PKG_VERSION} 8 | 9 | dkms install -m ${PKG_NAME} -v ${PKG_VERSION} 10 | -------------------------------------------------------------------------------- /dkms-remove.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | PKG_NAME=fullconenat 4 | PKG_VERSION=1.0 5 | 6 | dkms remove ${PKG_NAME}/${PKG_VERSION} --all 7 | rm -r /usr/src/${PKG_NAME}-${PKG_VERSION} 8 | -------------------------------------------------------------------------------- /dkms.conf: -------------------------------------------------------------------------------- 1 | PACKAGE_VERSION="1.0" 2 | 3 | # Items below here should not have to change with each driver version 4 | 5 | PACKAGE_NAME="fullconenat" 6 | BDIR="$dkms_tree/${PACKAGE_NAME}/${PACKAGE_VERSION}/build" 7 | MAKEARGS="-C $kernel_source_dir M=${BDIR} V=1" 8 | CLEAN="make ${MAKEARGS} clean" 9 | MAKE="make ${MAKEARGS} modules ; find ${BDIR} -name '*.ko' -exec mv -v {} ${BDIR} \;" 10 | 11 | AUTOINSTALL="yes" 12 | 13 | BUILT_MODULE_LOCATION[0]="" 14 | BUILT_MODULE_NAME[0]="xt_FULLCONENAT" 15 | DEST_MODULE_LOCATION[0]="/updates" 16 | -------------------------------------------------------------------------------- /libip6t_FULLCONENAT.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include /* INT_MAX in ip_tables.h */ 8 | #include 9 | #include 10 | 11 | #ifndef NF_NAT_RANGE_PROTO_RANDOM_FULLY 12 | #define NF_NAT_RANGE_PROTO_RANDOM_FULLY (1 << 4) 13 | #endif 14 | 15 | enum { 16 | O_TO_PORTS = 0, 17 | O_RANDOM, 18 | O_RANDOM_FULLY, 19 | O_TO_SRC, 20 | O_PERSISTENT, 21 | }; 22 | 23 | static void FULLCONENAT_help(void) 24 | { 25 | printf( 26 | "FULLCONENAT target options:\n" 27 | " --to-source [[-]] [--persistent]\n" 28 | " Address to map source to.\n" 29 | " --to-ports [-]\n" 30 | " Port (range) to map to.\n" 31 | " --random\n" 32 | " Randomize source port.\n" 33 | " --random-fully\n" 34 | " Fully randomize source port.\n"); 35 | } 36 | 37 | static const struct xt_option_entry FULLCONENAT_opts[] = { 38 | {.name = "to-ports", .id = O_TO_PORTS, .type = XTTYPE_STRING}, 39 | {.name = "random", .id = O_RANDOM, .type = XTTYPE_NONE}, 40 | {.name = "random-fully", .id = O_RANDOM_FULLY, .type = XTTYPE_NONE}, 41 | {.name = "to-source", .id = O_TO_SRC, .type = XTTYPE_STRING}, 42 | {.name = "persistent", .id = O_PERSISTENT, .type = XTTYPE_NONE}, 43 | XTOPT_TABLEEND, 44 | }; 45 | 46 | static void parse_to(const char *orig_arg, struct nf_nat_range *r) 47 | { 48 | char *arg, *dash, *error; 49 | const struct in6_addr *ip; 50 | 51 | arg = strdup(orig_arg); 52 | if (arg == NULL) 53 | xtables_error(RESOURCE_PROBLEM, "strdup"); 54 | 55 | r->flags |= NF_NAT_RANGE_MAP_IPS; 56 | dash = strchr(arg, '-'); 57 | 58 | if (dash) 59 | *dash = '\0'; 60 | 61 | ip = xtables_numeric_to_ip6addr(arg); 62 | if (!ip) 63 | xtables_error(PARAMETER_PROBLEM, "Bad IP address \"%s\"\n", 64 | arg); 65 | r->min_addr.in6 = *ip; 66 | if (dash) { 67 | ip = xtables_numeric_to_ip6addr(dash+1); 68 | if (!ip) 69 | xtables_error(PARAMETER_PROBLEM, "Bad IP address \"%s\"\n", 70 | dash+1); 71 | r->max_addr.in6 = *ip; 72 | } else 73 | r->max_addr = r->min_addr; 74 | 75 | free(arg); 76 | } 77 | 78 | /* Parses ports */ 79 | static void 80 | parse_ports(const char *arg, struct nf_nat_range *r) 81 | { 82 | char *end; 83 | unsigned int port, maxport; 84 | 85 | r->flags |= NF_NAT_RANGE_PROTO_SPECIFIED; 86 | 87 | if (!xtables_strtoui(arg, &end, &port, 0, UINT16_MAX)) 88 | xtables_param_act(XTF_BAD_VALUE, "FULLCONENAT", "--to-ports", arg); 89 | 90 | switch (*end) { 91 | case '\0': 92 | r->min_proto.tcp.port 93 | = r->max_proto.tcp.port 94 | = htons(port); 95 | return; 96 | case '-': 97 | if (!xtables_strtoui(end + 1, NULL, &maxport, 0, UINT16_MAX)) 98 | break; 99 | 100 | if (maxport < port) 101 | break; 102 | 103 | r->min_proto.tcp.port = htons(port); 104 | r->max_proto.tcp.port = htons(maxport); 105 | return; 106 | default: 107 | break; 108 | } 109 | xtables_param_act(XTF_BAD_VALUE, "FULLCONENAT", "--to-ports", arg); 110 | } 111 | 112 | static void FULLCONENAT_parse(struct xt_option_call *cb) 113 | { 114 | const struct ip6t_entry *entry = cb->xt_entry; 115 | struct nf_nat_range *r = cb->data; 116 | int portok; 117 | 118 | if (entry->ipv6.proto == IPPROTO_TCP 119 | || entry->ipv6.proto == IPPROTO_UDP 120 | || entry->ipv6.proto == IPPROTO_SCTP 121 | || entry->ipv6.proto == IPPROTO_DCCP 122 | || entry->ipv6.proto == IPPROTO_ICMP) 123 | portok = 1; 124 | else 125 | portok = 0; 126 | 127 | xtables_option_parse(cb); 128 | switch (cb->entry->id) { 129 | case O_TO_PORTS: 130 | if (!portok) 131 | xtables_error(PARAMETER_PROBLEM, 132 | "Need TCP, UDP, SCTP or DCCP with port specification"); 133 | parse_ports(cb->arg, r); 134 | break; 135 | case O_TO_SRC: 136 | parse_to(cb->arg, r); 137 | break; 138 | case O_RANDOM_FULLY: 139 | r->flags |= NF_NAT_RANGE_PROTO_RANDOM_FULLY; 140 | break; 141 | case O_RANDOM: 142 | r->flags |= NF_NAT_RANGE_PROTO_RANDOM; 143 | break; 144 | case O_PERSISTENT: 145 | r->flags |= NF_NAT_RANGE_PERSISTENT; 146 | break; 147 | } 148 | } 149 | 150 | static void 151 | FULLCONENAT_print(const void *ip, const struct xt_entry_target *target, 152 | int numeric) 153 | { 154 | const struct nf_nat_range *r = (const void *)target->data; 155 | 156 | if (r->flags & NF_NAT_RANGE_MAP_IPS) { 157 | printf(" to:%s", xtables_ip6addr_to_numeric(&r->min_addr.in6)); 158 | if (memcmp(&r->min_addr, &r->max_addr, sizeof(r->min_addr))) 159 | printf("-%s", xtables_ip6addr_to_numeric(&r->max_addr.in6)); 160 | } 161 | 162 | if (r->flags & NF_NAT_RANGE_PROTO_SPECIFIED) { 163 | printf(" masq ports: "); 164 | printf("%hu", ntohs(r->min_proto.tcp.port)); 165 | if (r->max_proto.tcp.port != r->min_proto.tcp.port) 166 | printf("-%hu", ntohs(r->max_proto.tcp.port)); 167 | if (r->flags & NF_NAT_RANGE_PERSISTENT) 168 | printf(" persistent"); 169 | } 170 | 171 | if (r->flags & NF_NAT_RANGE_PROTO_RANDOM) 172 | printf(" random"); 173 | 174 | if (r->flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY) 175 | printf(" random-fully"); 176 | } 177 | 178 | static void 179 | FULLCONENAT_save(const void *ip, const struct xt_entry_target *target) 180 | { 181 | const struct nf_nat_range *r = (const void *)target->data; 182 | 183 | if (r->flags & NF_NAT_RANGE_MAP_IPS) { 184 | printf(" --to-source %s", xtables_ip6addr_to_numeric(&r->min_addr.in6)); 185 | if (memcmp(&r->min_addr, &r->max_addr, sizeof(r->min_addr))) 186 | printf("-%s", xtables_ip6addr_to_numeric(&r->max_addr.in6)); 187 | if (r->flags & NF_NAT_RANGE_PERSISTENT) 188 | printf(" --persistent"); 189 | } 190 | 191 | if (r->flags & NF_NAT_RANGE_PROTO_SPECIFIED) { 192 | printf(" --to-ports %hu", ntohs(r->min_proto.tcp.port)); 193 | if (r->max_proto.tcp.port != r->min_proto.tcp.port) 194 | printf("-%hu", ntohs(r->max_proto.tcp.port)); 195 | } 196 | 197 | if (r->flags & NF_NAT_RANGE_PROTO_RANDOM) 198 | printf(" --random"); 199 | 200 | if (r->flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY) 201 | printf(" --random-fully"); 202 | } 203 | 204 | static struct xtables_target fullconenat_tg_reg = { 205 | .name = "FULLCONENAT", 206 | .version = XTABLES_VERSION, 207 | .family = NFPROTO_IPV6, 208 | .size = XT_ALIGN(sizeof(struct nf_nat_range)), 209 | .userspacesize = XT_ALIGN(sizeof(struct nf_nat_range)), 210 | .help = FULLCONENAT_help, 211 | .x6_parse = FULLCONENAT_parse, 212 | .print = FULLCONENAT_print, 213 | .save = FULLCONENAT_save, 214 | .x6_options = FULLCONENAT_opts, 215 | }; 216 | 217 | void __attribute__((constructor)) fullconenat6_init(void) 218 | { 219 | xtables_register_target(&fullconenat_tg_reg); 220 | } 221 | -------------------------------------------------------------------------------- /libipt_FULLCONENAT.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include /* INT_MAX in ip_tables.h */ 8 | #include 9 | #include 10 | 11 | #ifndef NF_NAT_RANGE_PROTO_RANDOM_FULLY 12 | #define NF_NAT_RANGE_PROTO_RANDOM_FULLY (1 << 4) 13 | #endif 14 | 15 | enum { 16 | O_TO_PORTS = 0, 17 | O_RANDOM, 18 | O_RANDOM_FULLY, 19 | O_TO_SRC, 20 | O_PERSISTENT, 21 | }; 22 | 23 | static void FULLCONENAT_help(void) 24 | { 25 | printf( 26 | "FULLCONENAT target options:\n" 27 | " --to-source [[-]] [--persistent]\n" 28 | " Address to map source to.\n" 29 | " --to-ports [-]\n" 30 | " Port (range) to map to.\n" 31 | " --random\n" 32 | " Randomize source port.\n" 33 | " --random-fully\n" 34 | " Fully randomize source port.\n"); 35 | } 36 | 37 | static const struct xt_option_entry FULLCONENAT_opts[] = { 38 | {.name = "to-ports", .id = O_TO_PORTS, .type = XTTYPE_STRING}, 39 | {.name = "random", .id = O_RANDOM, .type = XTTYPE_NONE}, 40 | {.name = "random-fully", .id = O_RANDOM_FULLY, .type = XTTYPE_NONE}, 41 | {.name = "to-source", .id = O_TO_SRC, .type = XTTYPE_STRING}, 42 | {.name = "persistent", .id = O_PERSISTENT, .type = XTTYPE_NONE}, 43 | XTOPT_TABLEEND, 44 | }; 45 | 46 | static void parse_to(const char *orig_arg, struct nf_nat_ipv4_multi_range_compat *mr) 47 | { 48 | char *arg, *dash, *error; 49 | const struct in_addr *ip; 50 | 51 | arg = strdup(orig_arg); 52 | if (arg == NULL) 53 | xtables_error(RESOURCE_PROBLEM, "strdup"); 54 | 55 | mr->range[0].flags |= NF_NAT_RANGE_MAP_IPS; 56 | dash = strchr(arg, '-'); 57 | 58 | if (dash) 59 | *dash = '\0'; 60 | 61 | ip = xtables_numeric_to_ipaddr(arg); 62 | if (!ip) 63 | xtables_error(PARAMETER_PROBLEM, "Bad IP address \"%s\"\n", 64 | arg); 65 | mr->range[0].min_ip = ip->s_addr; 66 | if (dash) { 67 | ip = xtables_numeric_to_ipaddr(dash+1); 68 | if (!ip) 69 | xtables_error(PARAMETER_PROBLEM, "Bad IP address \"%s\"\n", 70 | dash+1); 71 | mr->range[0].max_ip = ip->s_addr; 72 | } else 73 | mr->range[0].max_ip = mr->range[0].min_ip; 74 | 75 | free(arg); 76 | } 77 | 78 | static void FULLCONENAT_init(struct xt_entry_target *t) 79 | { 80 | struct nf_nat_ipv4_multi_range_compat *mr = (struct nf_nat_ipv4_multi_range_compat *)t->data; 81 | 82 | /* Actually, it's 0, but it's ignored at the moment. */ 83 | mr->rangesize = 1; 84 | } 85 | 86 | /* Parses ports */ 87 | static void 88 | parse_ports(const char *arg, struct nf_nat_ipv4_multi_range_compat *mr) 89 | { 90 | char *end; 91 | unsigned int port, maxport; 92 | 93 | mr->range[0].flags |= NF_NAT_RANGE_PROTO_SPECIFIED; 94 | 95 | if (!xtables_strtoui(arg, &end, &port, 0, UINT16_MAX)) 96 | xtables_param_act(XTF_BAD_VALUE, "FULLCONENAT", "--to-ports", arg); 97 | 98 | switch (*end) { 99 | case '\0': 100 | mr->range[0].min.tcp.port 101 | = mr->range[0].max.tcp.port 102 | = htons(port); 103 | return; 104 | case '-': 105 | if (!xtables_strtoui(end + 1, NULL, &maxport, 0, UINT16_MAX)) 106 | break; 107 | 108 | if (maxport < port) 109 | break; 110 | 111 | mr->range[0].min.tcp.port = htons(port); 112 | mr->range[0].max.tcp.port = htons(maxport); 113 | return; 114 | default: 115 | break; 116 | } 117 | xtables_param_act(XTF_BAD_VALUE, "FULLCONENAT", "--to-ports", arg); 118 | } 119 | 120 | static void FULLCONENAT_parse(struct xt_option_call *cb) 121 | { 122 | const struct ipt_entry *entry = cb->xt_entry; 123 | int portok; 124 | struct nf_nat_ipv4_multi_range_compat *mr = cb->data; 125 | 126 | if (entry->ip.proto == IPPROTO_TCP 127 | || entry->ip.proto == IPPROTO_UDP 128 | || entry->ip.proto == IPPROTO_SCTP 129 | || entry->ip.proto == IPPROTO_DCCP 130 | || entry->ip.proto == IPPROTO_ICMP) 131 | portok = 1; 132 | else 133 | portok = 0; 134 | 135 | xtables_option_parse(cb); 136 | switch (cb->entry->id) { 137 | case O_TO_PORTS: 138 | if (!portok) 139 | xtables_error(PARAMETER_PROBLEM, 140 | "Need TCP, UDP, SCTP or DCCP with port specification"); 141 | parse_ports(cb->arg, mr); 142 | break; 143 | case O_TO_SRC: 144 | parse_to(cb->arg, mr); 145 | break; 146 | case O_RANDOM: 147 | mr->range[0].flags |= NF_NAT_RANGE_PROTO_RANDOM; 148 | break; 149 | case O_RANDOM_FULLY: 150 | mr->range[0].flags |= NF_NAT_RANGE_PROTO_RANDOM_FULLY; 151 | break; 152 | case O_PERSISTENT: 153 | mr->range[0].flags |= NF_NAT_RANGE_PERSISTENT; 154 | break; 155 | } 156 | } 157 | 158 | static void 159 | FULLCONENAT_print(const void *ip, const struct xt_entry_target *target, 160 | int numeric) 161 | { 162 | const struct nf_nat_ipv4_multi_range_compat *mr = (const void *)target->data; 163 | const struct nf_nat_ipv4_range *r = &mr->range[0]; 164 | 165 | if (r->flags & NF_NAT_RANGE_MAP_IPS) { 166 | struct in_addr a; 167 | 168 | a.s_addr = r->min_ip; 169 | printf(" to:%s", xtables_ipaddr_to_numeric(&a)); 170 | if (r->max_ip != r->min_ip) { 171 | a.s_addr = r->max_ip; 172 | printf("-%s", xtables_ipaddr_to_numeric(&a)); 173 | } 174 | if (r->flags & NF_NAT_RANGE_PERSISTENT) 175 | printf(" persistent"); 176 | } 177 | 178 | if (r->flags & NF_NAT_RANGE_PROTO_SPECIFIED) { 179 | printf(" masq ports: "); 180 | printf("%hu", ntohs(r->min.tcp.port)); 181 | if (r->max.tcp.port != r->min.tcp.port) 182 | printf("-%hu", ntohs(r->max.tcp.port)); 183 | } 184 | 185 | if (r->flags & NF_NAT_RANGE_PROTO_RANDOM) 186 | printf(" random"); 187 | 188 | if (r->flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY) 189 | printf(" random-fully"); 190 | } 191 | 192 | static void 193 | FULLCONENAT_save(const void *ip, const struct xt_entry_target *target) 194 | { 195 | const struct nf_nat_ipv4_multi_range_compat *mr = (const void *)target->data; 196 | const struct nf_nat_ipv4_range *r = &mr->range[0]; 197 | 198 | if (r->flags & NF_NAT_RANGE_MAP_IPS) { 199 | struct in_addr a; 200 | 201 | a.s_addr = r->min_ip; 202 | printf(" --to-source %s", xtables_ipaddr_to_numeric(&a)); 203 | if (r->max_ip != r->min_ip) { 204 | a.s_addr = r->max_ip; 205 | printf("-%s", xtables_ipaddr_to_numeric(&a)); 206 | } 207 | if (r->flags & NF_NAT_RANGE_PERSISTENT) 208 | printf(" --persistent"); 209 | } 210 | 211 | if (r->flags & NF_NAT_RANGE_PROTO_SPECIFIED) { 212 | printf(" --to-ports %hu", ntohs(r->min.tcp.port)); 213 | if (r->max.tcp.port != r->min.tcp.port) 214 | printf("-%hu", ntohs(r->max.tcp.port)); 215 | } 216 | 217 | if (r->flags & NF_NAT_RANGE_PROTO_RANDOM) 218 | printf(" --random"); 219 | 220 | if (r->flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY) 221 | printf(" --random-fully"); 222 | } 223 | 224 | static struct xtables_target fullconenat_tg_reg = { 225 | .name = "FULLCONENAT", 226 | .version = XTABLES_VERSION, 227 | .family = NFPROTO_IPV4, 228 | .size = XT_ALIGN(sizeof(struct nf_nat_ipv4_multi_range_compat)), 229 | .userspacesize = XT_ALIGN(sizeof(struct nf_nat_ipv4_multi_range_compat)), 230 | .help = FULLCONENAT_help, 231 | .init = FULLCONENAT_init, 232 | .x6_parse = FULLCONENAT_parse, 233 | .print = FULLCONENAT_print, 234 | .save = FULLCONENAT_save, 235 | .x6_options = FULLCONENAT_opts, 236 | }; 237 | 238 | void __attribute__((constructor)) fullconenat4_init(void) 239 | { 240 | xtables_register_target(&fullconenat_tg_reg); 241 | } 242 | -------------------------------------------------------------------------------- /libipt_FULLCONENAT.t: -------------------------------------------------------------------------------- 1 | :POSTROUTING 2 | *nat 3 | -j FULLCONENAT;=;OK 4 | -j FULLCONENAT --random;=;OK 5 | -j FULLCONENAT --random-fully;=;OK 6 | -p tcp -j FULLCONENAT --to-ports 1024;=;OK 7 | -p udp -j FULLCONENAT --to-ports 1024-65535;=;OK 8 | -p udp -j FULLCONENAT --to-ports 1024-65536;;FAIL 9 | -p udp -j FULLCONENAT --to-ports -1;;FAIL 10 | -------------------------------------------------------------------------------- /xt_FULLCONENAT.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018 Chion Tang 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #ifdef CONFIG_NF_CONNTRACK_CHAIN_EVENTS 19 | #include 20 | #endif 21 | #include 22 | #include 23 | #if IS_ENABLED(CONFIG_NF_NAT_IPV6) || (IS_ENABLED(CONFIG_IPV6) && LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0)) 24 | #include 25 | #include 26 | #include 27 | #endif 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 2, 0) 36 | #include 37 | #elif LINUX_VERSION_CODE >= KERNEL_VERSION(3, 18, 0) 38 | #include 39 | #if IS_ENABLED(CONFIG_NF_NAT_MASQUERADE_IPV6) 40 | #include 41 | #endif 42 | #endif 43 | 44 | #define HASH_2(x, y) ((x + y) / 2 * (x + y + 1) + y) 45 | 46 | #define HASHTABLE_BUCKET_BITS 10 47 | 48 | #ifndef NF_NAT_RANGE_PROTO_RANDOM_FULLY 49 | #define NF_NAT_RANGE_PROTO_RANDOM_FULLY (1 << 4) 50 | #endif 51 | 52 | #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 10, 0) 53 | 54 | static inline int nf_ct_netns_get(struct net *net, u8 nfproto) { return 0; } 55 | 56 | static inline void nf_ct_netns_put(struct net *net, u8 nfproto) {} 57 | 58 | static inline struct net_device *xt_in(const struct xt_action_param *par) { 59 | return (struct net_device *)par->in; 60 | } 61 | 62 | static inline struct net_device *xt_out(const struct xt_action_param *par) { 63 | return (struct net_device *)par->out; 64 | } 65 | 66 | static inline unsigned int xt_hooknum(const struct xt_action_param *par) { 67 | return par->hooknum; 68 | } 69 | 70 | #endif 71 | 72 | struct nat_mapping_original_tuple { 73 | struct nf_conntrack_tuple tuple; 74 | 75 | struct list_head node; 76 | }; 77 | 78 | struct nat_mapping { 79 | uint16_t port; /* external source port */ 80 | __be32 addr; /* external source ip address */ 81 | 82 | __be32 int_addr; /* internal source ip address */ 83 | uint16_t int_port; /* internal source port */ 84 | 85 | int refer_count; /* how many references linked to this mapping 86 | * aka. length of original_tuple_list */ 87 | 88 | struct list_head original_tuple_list; 89 | 90 | struct hlist_node node_by_ext_port; 91 | struct hlist_node node_by_int_src; 92 | 93 | }; 94 | 95 | #if IS_ENABLED(CONFIG_NF_NAT_IPV6) || (IS_ENABLED(CONFIG_IPV6) && LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0)) 96 | struct nat_mapping6 { 97 | uint16_t port; /* external source port */ 98 | union nf_inet_addr addr; /* external source ip address */ 99 | 100 | union nf_inet_addr int_addr; /* internal source ip address */ 101 | uint16_t int_port; /* internal source port */ 102 | 103 | int refer_count; /* how many references linked to this mapping 104 | * aka. length of original_tuple_list */ 105 | 106 | struct list_head original_tuple_list; 107 | 108 | struct hlist_node node_by_ext_port; 109 | struct hlist_node node_by_int_src; 110 | 111 | }; 112 | #endif 113 | 114 | struct tuple_list { 115 | struct nf_conntrack_tuple tuple_original; 116 | struct nf_conntrack_tuple tuple_reply; 117 | struct list_head list; 118 | }; 119 | 120 | #ifdef CONFIG_NF_CONNTRACK_CHAIN_EVENTS 121 | struct notifier_block ct_event_notifier; 122 | #else 123 | struct nf_ct_event_notifier ct_event_notifier; 124 | #endif 125 | int tg_refer_count = 0; 126 | int ct_event_notifier_registered = 0; 127 | 128 | static DEFINE_MUTEX(nf_ct_net_event_lock); 129 | 130 | static DEFINE_HASHTABLE(mapping_table_by_ext_port, HASHTABLE_BUCKET_BITS); 131 | static DEFINE_HASHTABLE(mapping_table_by_int_src, HASHTABLE_BUCKET_BITS); 132 | 133 | static DEFINE_SPINLOCK(fullconenat_lock); 134 | 135 | #if IS_ENABLED(CONFIG_NF_NAT_IPV6) || (IS_ENABLED(CONFIG_IPV6) && LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0)) 136 | static DEFINE_HASHTABLE(mapping6_table_by_ext_port, HASHTABLE_BUCKET_BITS); 137 | static DEFINE_HASHTABLE(mapping6_table_by_int_src, HASHTABLE_BUCKET_BITS); 138 | 139 | static DEFINE_SPINLOCK(fullconenat6_lock); 140 | #endif 141 | 142 | static LIST_HEAD(dying_tuple_list); 143 | static DEFINE_SPINLOCK(dying_tuple_list_lock); 144 | static void gc_worker(struct work_struct *work); 145 | static struct workqueue_struct *wq __read_mostly = NULL; 146 | static DECLARE_DELAYED_WORK(gc_worker_wk, gc_worker); 147 | 148 | static char tuple_tmp_string[512]; 149 | 150 | #if IS_ENABLED(CONFIG_NF_NAT_IPV6) || (IS_ENABLED(CONFIG_IPV6) && LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0)) 151 | /* non-atomic: can only be called serially within lock zones. */ 152 | static char* nf_ct_stringify_tuple6(const struct nf_conntrack_tuple *t) { 153 | snprintf(tuple_tmp_string, sizeof(tuple_tmp_string), "[%pI6c]:%hu -> [%pI6c]:%hu", 154 | &t->src.u3.ip6, be16_to_cpu(t->src.u.all), 155 | &t->dst.u3.ip6, be16_to_cpu(t->dst.u.all)); 156 | return tuple_tmp_string; 157 | } 158 | 159 | static struct nat_mapping6* allocate_mapping6(const union nf_inet_addr *int_addr, const uint16_t int_port, const uint16_t port, const union nf_inet_addr *addr) { 160 | struct nat_mapping6 *p_new; 161 | u32 hash_src; 162 | 163 | p_new = kmalloc(sizeof(struct nat_mapping6), GFP_ATOMIC); 164 | if (p_new == NULL) { 165 | pr_debug("xt_FULLCONENAT: ERROR: kmalloc() for new nat_mapping failed.\n"); 166 | return NULL; 167 | } 168 | p_new->addr = *addr; 169 | p_new->port = port; 170 | p_new->int_addr = *int_addr; 171 | p_new->int_port = int_port; 172 | p_new->refer_count = 0; 173 | (p_new->original_tuple_list).next = &(p_new->original_tuple_list); 174 | (p_new->original_tuple_list).prev = &(p_new->original_tuple_list); 175 | 176 | hash_src = jhash2((u32 *)int_addr->all, 4, (u32)int_port); 177 | 178 | hash_add(mapping6_table_by_ext_port, &p_new->node_by_ext_port, port); 179 | hash_add(mapping6_table_by_int_src, &p_new->node_by_int_src, hash_src); 180 | 181 | pr_debug("xt_FULLCONENAT: new mapping allocated for [%pI6c]:%d ==> [%pI6c]:%d\n", 182 | &p_new->int_addr, p_new->int_port, &p_new->addr, p_new->port); 183 | 184 | return p_new; 185 | } 186 | 187 | static void add_original_tuple_to_mapping6(struct nat_mapping6 *mapping, const struct nf_conntrack_tuple* original_tuple) { 188 | struct nat_mapping_original_tuple *item = kmalloc(sizeof(struct nat_mapping_original_tuple), GFP_ATOMIC); 189 | if (item == NULL) { 190 | pr_debug("xt_FULLCONENAT: ERROR: kmalloc() for nat_mapping_original_tuple failed.\n"); 191 | return; 192 | } 193 | memcpy(&item->tuple, original_tuple, sizeof(struct nf_conntrack_tuple)); 194 | list_add(&item->node, &mapping->original_tuple_list); 195 | (mapping->refer_count)++; 196 | } 197 | 198 | static struct nat_mapping6* get_mapping6_by_int_src(const union nf_inet_addr *src_ip, const uint16_t src_port, const union nf_inet_addr *ext_ip) { 199 | struct nat_mapping6 *p_current; 200 | u32 hash_src = jhash2((u32 *)src_ip->all, 4, (u32)src_port); 201 | 202 | hash_for_each_possible(mapping6_table_by_int_src, p_current, node_by_int_src, hash_src) { 203 | if (nf_inet_addr_cmp(&p_current->int_addr, src_ip) && p_current->int_port == src_port && nf_inet_addr_cmp(&p_current->addr, ext_ip)) { 204 | return p_current; 205 | } 206 | } 207 | 208 | return NULL; 209 | } 210 | 211 | static struct nat_mapping6* get_mapping6_by_int_src_inrange(const union nf_inet_addr *src_ip, const uint16_t src_port, const union nf_inet_addr *min_ip, const union nf_inet_addr *max_ip) { 212 | struct nat_mapping6 *p_current; 213 | u32 hash_src = jhash2((u32 *)src_ip->all, 4, (u32)src_port); 214 | 215 | hash_for_each_possible(mapping6_table_by_int_src, p_current, node_by_int_src, hash_src) { 216 | if (nf_inet_addr_cmp(&p_current->int_addr, src_ip) && p_current->int_port == src_port && memcmp(&p_current->addr, min_ip, sizeof(union nf_inet_addr)) >= 0 && memcmp(&p_current->addr, max_ip, sizeof(union nf_inet_addr)) <= 0) { 217 | return p_current; 218 | } 219 | } 220 | 221 | return NULL; 222 | } 223 | 224 | static void kill_mapping6(struct nat_mapping6 *mapping) { 225 | struct list_head *iter, *tmp; 226 | struct nat_mapping_original_tuple *original_tuple_item; 227 | 228 | if (mapping == NULL) { 229 | return; 230 | } 231 | 232 | list_for_each_safe(iter, tmp, &mapping->original_tuple_list) { 233 | original_tuple_item = list_entry(iter, struct nat_mapping_original_tuple, node); 234 | list_del(&original_tuple_item->node); 235 | kfree(original_tuple_item); 236 | } 237 | 238 | hash_del(&mapping->node_by_ext_port); 239 | hash_del(&mapping->node_by_int_src); 240 | kfree(mapping); 241 | } 242 | 243 | /* check if a mapping is valid. 244 | * possibly delete and free an invalid mapping. 245 | * the mapping should not be used anymore after check_mapping6() returns 0. */ 246 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0) 247 | static int check_mapping6(struct nat_mapping6* mapping, struct net *net, const struct nf_conntrack_zone *zone) { 248 | #else 249 | static int check_mapping6(struct nat_mapping6* mapping, struct net *net, const u16 zone) { 250 | #endif 251 | struct list_head *iter, *tmp; 252 | struct nat_mapping_original_tuple *original_tuple_item; 253 | struct nf_conntrack_tuple_hash *tuple_hash; 254 | struct nf_conn *ct; 255 | 256 | /* for dying/unconfirmed conntrack tuples, an IPCT_DESTROY event may NOT be fired. 257 | * so we manually kill one of those tuples once we acquire one. */ 258 | 259 | list_for_each_safe(iter, tmp, &mapping->original_tuple_list) { 260 | original_tuple_item = list_entry(iter, struct nat_mapping_original_tuple, node); 261 | 262 | tuple_hash = nf_conntrack_find_get(net, zone, &original_tuple_item->tuple); 263 | 264 | if (tuple_hash == NULL) { 265 | pr_debug("xt_FULLCONENAT: check_mapping6(): tuple %s dying/unconfirmed. free this tuple.\n", nf_ct_stringify_tuple6(&original_tuple_item->tuple)); 266 | 267 | list_del(&original_tuple_item->node); 268 | kfree(original_tuple_item); 269 | (mapping->refer_count)--; 270 | } else { 271 | ct = nf_ct_tuplehash_to_ctrack(tuple_hash); 272 | if (likely(ct != NULL)) 273 | nf_ct_put(ct); 274 | } 275 | 276 | } 277 | 278 | /* kill the mapping if need */ 279 | pr_debug("xt_FULLCONENAT: check_mapping6() refer_count for mapping at ext_port %d is now %d\n", mapping->port, mapping->refer_count); 280 | if (mapping->refer_count <= 0) { 281 | pr_debug("xt_FULLCONENAT: check_mapping6(): kill dying/unconfirmed mapping at ext port %d\n", mapping->port); 282 | kill_mapping6(mapping); 283 | return 0; 284 | } else { 285 | return 1; 286 | } 287 | } 288 | 289 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0) 290 | static struct nat_mapping6* get_mapping6_by_ext_port(const uint16_t port, const union nf_inet_addr *ext_ip, struct net *net, const struct nf_conntrack_zone *zone) { 291 | #else 292 | static struct nat_mapping6* get_mapping6_by_ext_port(const uint16_t port, const union nf_inet_addr *ext_ip, struct net *net, const u16 zone) { 293 | #endif 294 | struct nat_mapping6 *p_current; 295 | struct hlist_node *tmp; 296 | 297 | hash_for_each_possible_safe(mapping6_table_by_ext_port, p_current, tmp, node_by_ext_port, port) { 298 | if (p_current->port == port && check_mapping6(p_current, net, zone) && nf_inet_addr_cmp(&p_current->addr, ext_ip)) { 299 | return p_current; 300 | } 301 | } 302 | 303 | return NULL; 304 | } 305 | 306 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0) 307 | static uint16_t find_appropriate_port6(struct net *net, const struct nf_conntrack_zone *zone, const uint16_t original_port, const union nf_inet_addr *ext_ip, const struct nf_nat_range *range) { 308 | #else 309 | static uint16_t find_appropriate_port6(struct net *net, const u16 zone, const uint16_t original_port, const union nf_inet_addr *ext_ip, const struct nf_nat_range *range) { 310 | #endif 311 | uint16_t min, start, selected, range_size, i; 312 | struct nat_mapping6* mapping = NULL; 313 | 314 | if (range->flags & NF_NAT_RANGE_PROTO_SPECIFIED) { 315 | min = be16_to_cpu((range->min_proto).udp.port); 316 | range_size = be16_to_cpu((range->max_proto).udp.port) - min + 1; 317 | } else { 318 | /* minimum port is 1024. same behavior as default linux NAT. */ 319 | min = 1024; 320 | range_size = 65535 - min + 1; 321 | } 322 | 323 | if ((range->flags & NF_NAT_RANGE_PROTO_RANDOM) 324 | || (range->flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY)) { 325 | /* for now we do the same thing for both --random and --random-fully */ 326 | 327 | /* select a random starting point */ 328 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 11, 0) 329 | start = (uint16_t)(get_random_u32() % (u32)range_size); 330 | #else 331 | start = (uint16_t)(prandom_u32() % (u32)range_size); 332 | #endif 333 | } else { 334 | 335 | if ((original_port >= min && original_port <= min + range_size - 1) 336 | || !(range->flags & NF_NAT_RANGE_PROTO_SPECIFIED)) { 337 | /* 1. try to preserve the port if it's available */ 338 | mapping = get_mapping6_by_ext_port(original_port, ext_ip, net, zone); 339 | if (mapping == NULL) { 340 | return original_port; 341 | } 342 | } 343 | 344 | /* otherwise, we start from zero */ 345 | start = 0; 346 | } 347 | 348 | for (i = 0; i < range_size; i++) { 349 | /* 2. try to find an available port */ 350 | selected = min + ((start + i) % range_size); 351 | mapping = get_mapping6_by_ext_port(selected, ext_ip, net, zone); 352 | if (mapping == NULL) { 353 | return selected; 354 | } 355 | } 356 | 357 | /* 3. at least we tried. override a previous mapping. */ 358 | selected = min + start; 359 | mapping = get_mapping6_by_ext_port(selected, ext_ip, net, zone); 360 | kill_mapping6(mapping); 361 | 362 | return selected; 363 | } 364 | 365 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0) 366 | static void find_leastused_ip6(const struct nf_conntrack_zone *zone, const struct nf_nat_range *range, const union nf_inet_addr *src, const union nf_inet_addr *dst, union nf_inet_addr *var_ipp) 367 | #else 368 | static void find_leastused_ip6(const u16 zone, const struct nf_nat_range *range, const union nf_inet_addr *src, const union nf_inet_addr *dst, union nf_inet_addr *var_ipp) 369 | #endif 370 | { 371 | unsigned int i; 372 | /* Host order */ 373 | u32 minip, maxip, j, dist; 374 | bool full_range; 375 | 376 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0) 377 | j = jhash2((u32 *)src, 4, range->flags & NF_NAT_RANGE_PERSISTENT ? 0 : dst->all[3] ^ zone->id); 378 | #else 379 | j = jhash2((u32 *)src, 4, range->flags & NF_NAT_RANGE_PERSISTENT ? 0 : dst->all[3] ^ zone); 380 | #endif 381 | 382 | full_range = false; 383 | for (i = 0; i <= 3; i++) { 384 | /* If first bytes of the address are at the maximum, use the 385 | * distance. Otherwise use the full range. */ 386 | if (!full_range) { 387 | minip = ntohl(range->min_addr.all[i]); 388 | maxip = ntohl(range->max_addr.all[i]); 389 | dist = maxip - minip + 1; 390 | } else { 391 | minip = 0; 392 | dist = ~0; 393 | } 394 | 395 | var_ipp->all[i] = (__force __be32) htonl(minip + reciprocal_scale(j, dist)); 396 | if (var_ipp->all[i] != range->max_addr.all[i]) 397 | full_range = true; 398 | 399 | if (!(range->flags & NF_NAT_RANGE_PERSISTENT)) 400 | j ^= (__force u32)dst->all[i]; 401 | } 402 | } 403 | 404 | static unsigned int fullconenat_tg6(struct sk_buff *skb, const struct xt_action_param *par) 405 | { 406 | const struct nf_nat_range *range; 407 | 408 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0) 409 | const struct nf_conntrack_zone *zone; 410 | #else 411 | u16 zone; 412 | #endif 413 | struct net *net; 414 | struct nf_conn *ct; 415 | enum ip_conntrack_info ctinfo; 416 | struct nf_conn_nat *nat; 417 | struct nf_conntrack_tuple *ct_tuple, *ct_tuple_origin; 418 | 419 | struct nat_mapping6 *mapping, *src_mapping; 420 | unsigned int ret; 421 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 18, 0) 422 | struct nf_nat_range2 newrange; 423 | #else 424 | struct nf_nat_range newrange; 425 | #endif 426 | 427 | union nf_inet_addr *ip; 428 | uint16_t port, original_port, want_port; 429 | uint8_t protonum; 430 | 431 | ip = NULL; 432 | original_port = 0; 433 | src_mapping = NULL; 434 | 435 | range = par->targinfo; 436 | 437 | mapping = NULL; 438 | ret = XT_CONTINUE; 439 | 440 | ct = nf_ct_get(skb, &ctinfo); 441 | net = nf_ct_net(ct); 442 | zone = nf_ct_zone(ct); 443 | 444 | newrange.flags = range->flags | NF_NAT_RANGE_MAP_IPS; 445 | newrange.min_proto = range->min_proto; 446 | newrange.max_proto = range->max_proto; 447 | 448 | if (xt_hooknum(par) == NF_INET_PRE_ROUTING) { 449 | /* inbound packets */ 450 | ct_tuple_origin = &(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple); 451 | 452 | protonum = (ct_tuple_origin->dst).protonum; 453 | if (protonum != IPPROTO_UDP) { 454 | return ret; 455 | } 456 | ip = &(ct_tuple_origin->dst).u3; 457 | port = be16_to_cpu((ct_tuple_origin->dst).u.udp.port); 458 | 459 | spin_lock_bh(&fullconenat6_lock); 460 | 461 | /* find an active mapping based on the inbound port */ 462 | mapping = get_mapping6_by_ext_port(port, ip, net, zone); 463 | if (mapping != NULL) { 464 | newrange.flags = NF_NAT_RANGE_MAP_IPS | NF_NAT_RANGE_PROTO_SPECIFIED; 465 | newrange.min_addr = mapping->int_addr; 466 | newrange.max_addr = mapping->int_addr; 467 | newrange.min_proto.udp.port = cpu_to_be16(mapping->int_port); 468 | newrange.max_proto = newrange.min_proto; 469 | 470 | pr_debug("xt_FULLCONENAT: %s ==> [%pI6c]:%d\n", nf_ct_stringify_tuple6(ct_tuple_origin), &mapping->int_addr, mapping->int_port); 471 | 472 | ret = nf_nat_setup_info(ct, &newrange, HOOK2MANIP(xt_hooknum(par))); 473 | 474 | if (ret == NF_ACCEPT) { 475 | add_original_tuple_to_mapping6(mapping, ct_tuple_origin); 476 | pr_debug("xt_FULLCONENAT: fullconenat_tg6(): INBOUND: refer_count for mapping at ext_port %d is now %d\n", mapping->port, mapping->refer_count); 477 | } 478 | } 479 | spin_unlock_bh(&fullconenat6_lock); 480 | return ret; 481 | 482 | } else if (xt_hooknum(par) == NF_INET_POST_ROUTING) { 483 | /* outbound packets */ 484 | ct_tuple_origin = &(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple); 485 | protonum = (ct_tuple_origin->dst).protonum; 486 | 487 | if(range->flags & NF_NAT_RANGE_MAP_IPS) { 488 | newrange.min_addr = range->min_addr; 489 | newrange.max_addr = range->max_addr; 490 | } else { 491 | if (unlikely(ipv6_dev_get_saddr(nf_ct_net(ct), xt_out(par), &ipv6_hdr(skb)->daddr, 0, (struct in6_addr*)&newrange.min_addr) < 0)) 492 | return NF_DROP; 493 | newrange.max_addr = newrange.min_addr; 494 | 495 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 16, 0) 496 | nat = nf_ct_nat_ext_add(ct); 497 | #else 498 | nat = nfct_nat(ct); 499 | #endif 500 | if (likely(nat)) 501 | nat->masq_index = xt_out(par)->ifindex; 502 | 503 | } 504 | 505 | if (protonum == IPPROTO_UDP) { 506 | ip = &(ct_tuple_origin->src).u3; 507 | original_port = be16_to_cpu((ct_tuple_origin->src).u.udp.port); 508 | 509 | spin_lock_bh(&fullconenat6_lock); 510 | 511 | if (!nf_inet_addr_cmp(&newrange.min_addr, &newrange.max_addr)) 512 | src_mapping = get_mapping6_by_int_src_inrange(ip, original_port, &newrange.min_addr, &newrange.max_addr); 513 | else 514 | src_mapping = get_mapping6_by_int_src(ip, original_port, &newrange.min_addr); 515 | 516 | if (src_mapping != NULL && check_mapping6(src_mapping, net, zone)) { 517 | 518 | /* outbound nat: if a previously established mapping is active, 519 | * we will reuse that mapping. */ 520 | 521 | newrange.flags = NF_NAT_RANGE_MAP_IPS | NF_NAT_RANGE_PROTO_SPECIFIED; 522 | newrange.min_proto.udp.port = cpu_to_be16(src_mapping->port); 523 | newrange.max_proto = newrange.min_proto; 524 | if (!nf_inet_addr_cmp(&newrange.min_addr, &newrange.max_addr)) { 525 | newrange.min_addr = src_mapping->addr; 526 | newrange.max_addr = newrange.min_addr; 527 | } 528 | 529 | } else { 530 | /* if not, we find a new external IP:port to map to. 531 | * the SNAT may fail so we should re-check the mapped port later. */ 532 | if (!nf_inet_addr_cmp(&newrange.min_addr, &newrange.max_addr)) { 533 | find_leastused_ip6(zone, range, ip, &(ct_tuple_origin->dst).u3, &newrange.min_addr); 534 | newrange.max_addr = newrange.min_addr; 535 | } 536 | 537 | want_port = find_appropriate_port6(net, zone, original_port, &newrange.min_addr, range); 538 | 539 | newrange.flags = NF_NAT_RANGE_MAP_IPS | NF_NAT_RANGE_PROTO_SPECIFIED; 540 | newrange.min_proto.udp.port = cpu_to_be16(want_port); 541 | newrange.max_proto = newrange.min_proto; 542 | 543 | src_mapping = NULL; 544 | 545 | } 546 | } 547 | 548 | /* do SNAT now */ 549 | ret = nf_nat_setup_info(ct, &newrange, HOOK2MANIP(xt_hooknum(par))); 550 | 551 | if (protonum != IPPROTO_UDP) { 552 | /* non-UDP packets, bailout */ 553 | return ret; 554 | } 555 | if (ret != NF_ACCEPT) { 556 | /* failed SNAT, bailout */ 557 | spin_unlock_bh(&fullconenat6_lock); 558 | return ret; 559 | } 560 | 561 | /* the reply tuple contains the mapped port. */ 562 | ct_tuple = &(ct->tuplehash[IP_CT_DIR_REPLY].tuple); 563 | /* this is the resulted mapped port. */ 564 | port = be16_to_cpu((ct_tuple->dst).u.udp.port); 565 | 566 | pr_debug("xt_FULLCONENAT: %s ==> %d\n", nf_ct_stringify_tuple6(ct_tuple_origin), port); 567 | 568 | /* save the mapping information into our mapping table */ 569 | mapping = src_mapping; 570 | if (mapping == NULL) { 571 | mapping = allocate_mapping6(ip, original_port, port, &(ct_tuple->dst).u3); 572 | } 573 | if (likely(mapping != NULL)) { 574 | add_original_tuple_to_mapping6(mapping, ct_tuple_origin); 575 | pr_debug("xt_FULLCONENAT: fullconenat_tg6(): OUTBOUND: refer_count for mapping at ext_port %d is now %d\n", mapping->port, mapping->refer_count); 576 | } 577 | 578 | spin_unlock_bh(&fullconenat6_lock); 579 | return ret; 580 | } 581 | 582 | return ret; 583 | } 584 | #endif 585 | 586 | /* non-atomic: can only be called serially within lock zones. */ 587 | static char* nf_ct_stringify_tuple(const struct nf_conntrack_tuple *t) { 588 | snprintf(tuple_tmp_string, sizeof(tuple_tmp_string), "%pI4:%hu -> %pI4:%hu", 589 | &t->src.u3.ip, be16_to_cpu(t->src.u.all), 590 | &t->dst.u3.ip, be16_to_cpu(t->dst.u.all)); 591 | return tuple_tmp_string; 592 | } 593 | 594 | static struct nat_mapping* allocate_mapping(const __be32 int_addr, const uint16_t int_port, const uint16_t port, const __be32 addr) { 595 | struct nat_mapping *p_new; 596 | u32 hash_src; 597 | 598 | p_new = kmalloc(sizeof(struct nat_mapping), GFP_ATOMIC); 599 | if (p_new == NULL) { 600 | pr_debug("xt_FULLCONENAT: ERROR: kmalloc() for new nat_mapping failed.\n"); 601 | return NULL; 602 | } 603 | p_new->addr = addr; 604 | p_new->port = port; 605 | p_new->int_addr = int_addr; 606 | p_new->int_port = int_port; 607 | p_new->refer_count = 0; 608 | (p_new->original_tuple_list).next = &(p_new->original_tuple_list); 609 | (p_new->original_tuple_list).prev = &(p_new->original_tuple_list); 610 | 611 | hash_src = HASH_2(int_addr, (u32)int_port); 612 | 613 | hash_add(mapping_table_by_ext_port, &p_new->node_by_ext_port, port); 614 | hash_add(mapping_table_by_int_src, &p_new->node_by_int_src, hash_src); 615 | 616 | pr_debug("xt_FULLCONENAT: new mapping allocated for %pI4:%d ==> %pI4:%d\n", 617 | &p_new->int_addr, p_new->int_port, &p_new->addr, p_new->port); 618 | 619 | return p_new; 620 | } 621 | 622 | static void add_original_tuple_to_mapping(struct nat_mapping *mapping, const struct nf_conntrack_tuple* original_tuple) { 623 | struct nat_mapping_original_tuple *item = kmalloc(sizeof(struct nat_mapping_original_tuple), GFP_ATOMIC); 624 | if (item == NULL) { 625 | pr_debug("xt_FULLCONENAT: ERROR: kmalloc() for nat_mapping_original_tuple failed.\n"); 626 | return; 627 | } 628 | memcpy(&item->tuple, original_tuple, sizeof(struct nf_conntrack_tuple)); 629 | list_add(&item->node, &mapping->original_tuple_list); 630 | (mapping->refer_count)++; 631 | } 632 | 633 | static struct nat_mapping* get_mapping_by_int_src(const __be32 src_ip, const uint16_t src_port, const __be32 ext_ip) { 634 | struct nat_mapping *p_current; 635 | u32 hash_src = HASH_2(src_ip, (u32)src_port); 636 | 637 | hash_for_each_possible(mapping_table_by_int_src, p_current, node_by_int_src, hash_src) { 638 | if (p_current->int_addr == src_ip && p_current->int_port == src_port && p_current->addr == ext_ip) { 639 | return p_current; 640 | } 641 | } 642 | 643 | return NULL; 644 | } 645 | 646 | static struct nat_mapping* get_mapping_by_int_src_inrange(const __be32 src_ip, const uint16_t src_port, const __be32 min_ip, const __be32 max_ip) { 647 | struct nat_mapping *p_current; 648 | u32 hash_src = HASH_2(src_ip, (u32)src_port); 649 | 650 | hash_for_each_possible(mapping_table_by_int_src, p_current, node_by_int_src, hash_src) { 651 | if (p_current->int_addr == src_ip && p_current->int_port == src_port && memcmp(&p_current->addr, &min_ip, sizeof(__be32)) >=0 && memcmp(&p_current->addr, &max_ip, sizeof(__be32)) <= 0) { 652 | return p_current; 653 | } 654 | } 655 | 656 | return NULL; 657 | } 658 | 659 | static void kill_mapping(struct nat_mapping *mapping) { 660 | struct list_head *iter, *tmp; 661 | struct nat_mapping_original_tuple *original_tuple_item; 662 | 663 | if (mapping == NULL) { 664 | return; 665 | } 666 | 667 | list_for_each_safe(iter, tmp, &mapping->original_tuple_list) { 668 | original_tuple_item = list_entry(iter, struct nat_mapping_original_tuple, node); 669 | list_del(&original_tuple_item->node); 670 | kfree(original_tuple_item); 671 | } 672 | 673 | hash_del(&mapping->node_by_ext_port); 674 | hash_del(&mapping->node_by_int_src); 675 | kfree(mapping); 676 | } 677 | 678 | static void destroy_mappings(void) { 679 | struct nat_mapping *p_current; 680 | #if IS_ENABLED(CONFIG_NF_NAT_IPV6) || (IS_ENABLED(CONFIG_IPV6) && LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0)) 681 | struct nat_mapping6 *p6_current; 682 | #endif 683 | struct hlist_node *tmp; 684 | int i; 685 | 686 | spin_lock_bh(&fullconenat_lock); 687 | 688 | hash_for_each_safe(mapping_table_by_ext_port, i, tmp, p_current, node_by_ext_port) { 689 | kill_mapping(p_current); 690 | } 691 | 692 | spin_unlock_bh(&fullconenat_lock); 693 | 694 | #if IS_ENABLED(CONFIG_NF_NAT_IPV6) || (IS_ENABLED(CONFIG_IPV6) && LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0)) 695 | spin_lock_bh(&fullconenat6_lock); 696 | 697 | hash_for_each_safe(mapping6_table_by_ext_port, i, tmp, p6_current, node_by_ext_port) { 698 | kill_mapping6(p6_current); 699 | } 700 | 701 | spin_unlock_bh(&fullconenat6_lock); 702 | #endif 703 | } 704 | 705 | /* check if a mapping is valid. 706 | * possibly delete and free an invalid mapping. 707 | * the mapping should not be used anymore after check_mapping() returns 0. */ 708 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0) 709 | static int check_mapping(struct nat_mapping* mapping, struct net *net, const struct nf_conntrack_zone *zone) { 710 | #else 711 | static int check_mapping(struct nat_mapping* mapping, struct net *net, const u16 zone) { 712 | #endif 713 | struct list_head *iter, *tmp; 714 | struct nat_mapping_original_tuple *original_tuple_item; 715 | struct nf_conntrack_tuple_hash *tuple_hash; 716 | struct nf_conn *ct; 717 | 718 | /* for dying/unconfirmed conntrack tuples, an IPCT_DESTROY event may NOT be fired. 719 | * so we manually kill one of those tuples once we acquire one. */ 720 | 721 | list_for_each_safe(iter, tmp, &mapping->original_tuple_list) { 722 | original_tuple_item = list_entry(iter, struct nat_mapping_original_tuple, node); 723 | 724 | tuple_hash = nf_conntrack_find_get(net, zone, &original_tuple_item->tuple); 725 | 726 | if (tuple_hash == NULL) { 727 | pr_debug("xt_FULLCONENAT: check_mapping(): tuple %s dying/unconfirmed. free this tuple.\n", nf_ct_stringify_tuple(&original_tuple_item->tuple)); 728 | 729 | list_del(&original_tuple_item->node); 730 | kfree(original_tuple_item); 731 | (mapping->refer_count)--; 732 | } else { 733 | ct = nf_ct_tuplehash_to_ctrack(tuple_hash); 734 | if (likely(ct != NULL)) 735 | nf_ct_put(ct); 736 | } 737 | 738 | } 739 | 740 | /* kill the mapping if need */ 741 | pr_debug("xt_FULLCONENAT: check_mapping() refer_count for mapping at ext_port %d is now %d\n", mapping->port, mapping->refer_count); 742 | if (mapping->refer_count <= 0) { 743 | pr_debug("xt_FULLCONENAT: check_mapping(): kill dying/unconfirmed mapping at ext port %d\n", mapping->port); 744 | kill_mapping(mapping); 745 | return 0; 746 | } else { 747 | return 1; 748 | } 749 | } 750 | 751 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0) 752 | static struct nat_mapping* get_mapping_by_ext_port(const uint16_t port, const __be32 ext_ip, struct net *net, const struct nf_conntrack_zone *zone) { 753 | #else 754 | static struct nat_mapping* get_mapping_by_ext_port(const uint16_t port, const __be32 ext_ip, struct net *net, const u16 zone) { 755 | #endif 756 | struct nat_mapping *p_current; 757 | struct hlist_node *tmp; 758 | 759 | hash_for_each_possible_safe(mapping_table_by_ext_port, p_current, tmp, node_by_ext_port, port) { 760 | if (p_current->port == port && check_mapping(p_current, net, zone) && p_current->addr == ext_ip) { 761 | return p_current; 762 | } 763 | } 764 | 765 | return NULL; 766 | } 767 | 768 | static void handle_dying_tuples(void) { 769 | struct list_head *iter, *tmp, *iter_2, *tmp_2; 770 | struct tuple_list *item; 771 | struct nf_conntrack_tuple *ct_tuple; 772 | struct nat_mapping *mapping; 773 | __be32 ip, ext_ip; 774 | uint16_t port; 775 | struct nat_mapping_original_tuple *original_tuple_item; 776 | #if IS_ENABLED(CONFIG_NF_NAT_IPV6) || (IS_ENABLED(CONFIG_IPV6) && LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0)) 777 | struct nat_mapping6 *mapping6; 778 | union nf_inet_addr *ip6, *ext_ip6; 779 | spin_lock_bh(&fullconenat6_lock); 780 | #endif 781 | 782 | spin_lock_bh(&fullconenat_lock); 783 | spin_lock_bh(&dying_tuple_list_lock); 784 | 785 | list_for_each_safe(iter, tmp, &dying_tuple_list) { 786 | item = list_entry(iter, struct tuple_list, list); 787 | 788 | /* we dont know the conntrack direction for now so we try in both ways. */ 789 | ct_tuple = &(item->tuple_original); 790 | #if IS_ENABLED(CONFIG_NF_NAT_IPV6) || (IS_ENABLED(CONFIG_IPV6) && LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0)) 791 | if (ct_tuple->src.l3num == PF_INET6) { 792 | ip6 = &(ct_tuple->src).u3; 793 | port = be16_to_cpu((ct_tuple->src).u.udp.port); 794 | ext_ip6 = &item->tuple_reply.dst.u3; 795 | mapping6 = get_mapping6_by_int_src(ip6, port, ext_ip6); 796 | if (mapping6 == NULL) { 797 | ext_ip6 = &(ct_tuple->dst).u3; 798 | ct_tuple = &(item->tuple_reply); 799 | ip6 = &(ct_tuple->src).u3; 800 | port = be16_to_cpu((ct_tuple->src).u.udp.port); 801 | mapping6 = get_mapping6_by_int_src(ip6, port, ext_ip6); 802 | if (mapping6 != NULL) { 803 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): INBOUND dying conntrack at ext port %d\n", mapping6->port); 804 | } 805 | } else { 806 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): OUTBOUND dying conntrack at ext port %d\n", mapping6->port); 807 | } 808 | 809 | if (mapping6 == NULL) { 810 | goto next; 811 | } 812 | 813 | /* look for the corresponding out-dated tuple and free it */ 814 | list_for_each_safe(iter_2, tmp_2, &mapping6->original_tuple_list) { 815 | original_tuple_item = list_entry(iter_2, struct nat_mapping_original_tuple, node); 816 | 817 | if (nf_ct_tuple_equal(&original_tuple_item->tuple, &(item->tuple_original))) { 818 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): tuple %s expired. free this tuple.\n", 819 | nf_ct_stringify_tuple6(&original_tuple_item->tuple)); 820 | list_del(&original_tuple_item->node); 821 | kfree(original_tuple_item); 822 | (mapping6->refer_count)--; 823 | } 824 | } 825 | 826 | /* then kill the mapping if needed*/ 827 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): refer_count for mapping at ext_port %d is now %d\n", mapping6->port, mapping6->refer_count); 828 | if (mapping6->refer_count <= 0) { 829 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): kill expired mapping at ext port %d\n", mapping6->port); 830 | kill_mapping6(mapping6); 831 | } 832 | goto next; 833 | } 834 | if (unlikely(ct_tuple->src.l3num != PF_INET)) 835 | #else 836 | if (ct_tuple->src.l3num != PF_INET) 837 | #endif 838 | goto next; 839 | 840 | ip = (ct_tuple->src).u3.ip; 841 | port = be16_to_cpu((ct_tuple->src).u.udp.port); 842 | ext_ip = item->tuple_reply.dst.u3.ip; 843 | mapping = get_mapping_by_int_src(ip, port, ext_ip); 844 | if (mapping == NULL) { 845 | ext_ip = (ct_tuple->dst).u3.ip; 846 | ct_tuple = &(item->tuple_reply); 847 | ip = (ct_tuple->src).u3.ip; 848 | port = be16_to_cpu((ct_tuple->src).u.udp.port); 849 | mapping = get_mapping_by_int_src(ip, port, ext_ip); 850 | if (mapping != NULL) { 851 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): INBOUND dying conntrack at ext port %d\n", mapping->port); 852 | } 853 | } else { 854 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): OUTBOUND dying conntrack at ext port %d\n", mapping->port); 855 | } 856 | 857 | if (mapping == NULL) { 858 | goto next; 859 | } 860 | 861 | /* look for the corresponding out-dated tuple and free it */ 862 | list_for_each_safe(iter_2, tmp_2, &mapping->original_tuple_list) { 863 | original_tuple_item = list_entry(iter_2, struct nat_mapping_original_tuple, node); 864 | 865 | if (nf_ct_tuple_equal(&original_tuple_item->tuple, &(item->tuple_original))) { 866 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): tuple %s expired. free this tuple.\n", 867 | nf_ct_stringify_tuple(&original_tuple_item->tuple)); 868 | list_del(&original_tuple_item->node); 869 | kfree(original_tuple_item); 870 | (mapping->refer_count)--; 871 | } 872 | } 873 | 874 | /* then kill the mapping if needed*/ 875 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): refer_count for mapping at ext_port %d is now %d\n", mapping->port, mapping->refer_count); 876 | if (mapping->refer_count <= 0) { 877 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): kill expired mapping at ext port %d\n", mapping->port); 878 | kill_mapping(mapping); 879 | } 880 | 881 | next: 882 | list_del(&item->list); 883 | kfree(item); 884 | } 885 | 886 | spin_unlock_bh(&dying_tuple_list_lock); 887 | spin_unlock_bh(&fullconenat_lock); 888 | #if IS_ENABLED(CONFIG_NF_NAT_IPV6) || (IS_ENABLED(CONFIG_IPV6) && LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0)) 889 | spin_unlock_bh(&fullconenat6_lock); 890 | #endif 891 | } 892 | 893 | static void gc_worker(struct work_struct *work) { 894 | handle_dying_tuples(); 895 | } 896 | 897 | /* conntrack destroy event callback function */ 898 | #ifdef CONFIG_NF_CONNTRACK_CHAIN_EVENTS 899 | static int ct_event_cb(struct notifier_block *this, unsigned long events, void *ptr) { 900 | struct nf_ct_event *item = ptr; 901 | #elif LINUX_VERSION_CODE >= KERNEL_VERSION(5, 15, 0) 902 | static int ct_event_cb(unsigned int events, const struct nf_ct_event *item) { 903 | #else 904 | static int ct_event_cb(unsigned int events, struct nf_ct_event *item) { 905 | #endif 906 | struct nf_conn *ct; 907 | struct nf_conntrack_tuple *ct_tuple_reply, *ct_tuple_original; 908 | uint8_t protonum; 909 | struct tuple_list *dying_tuple_item; 910 | 911 | ct = item->ct; 912 | /* we handle only conntrack destroy events */ 913 | if (ct == NULL || !(events & (1 << IPCT_DESTROY))) { 914 | return 0; 915 | } 916 | 917 | ct_tuple_original = &(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple); 918 | 919 | ct_tuple_reply = &(ct->tuplehash[IP_CT_DIR_REPLY].tuple); 920 | 921 | protonum = (ct_tuple_original->dst).protonum; 922 | if (protonum != IPPROTO_UDP) { 923 | return 0; 924 | } 925 | 926 | dying_tuple_item = kmalloc(sizeof(struct tuple_list), GFP_ATOMIC); 927 | 928 | if (dying_tuple_item == NULL) { 929 | pr_debug("xt_FULLCONENAT: warning: ct_event_cb(): kmalloc failed.\n"); 930 | return 0; 931 | } 932 | 933 | memcpy(&(dying_tuple_item->tuple_original), ct_tuple_original, sizeof(struct nf_conntrack_tuple)); 934 | memcpy(&(dying_tuple_item->tuple_reply), ct_tuple_reply, sizeof(struct nf_conntrack_tuple)); 935 | 936 | spin_lock_bh(&dying_tuple_list_lock); 937 | 938 | list_add(&(dying_tuple_item->list), &dying_tuple_list); 939 | 940 | spin_unlock_bh(&dying_tuple_list_lock); 941 | 942 | if (wq != NULL) 943 | queue_delayed_work(wq, &gc_worker_wk, msecs_to_jiffies(100)); 944 | 945 | return 0; 946 | } 947 | 948 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 15, 0) && !defined(CONFIG_NF_CONNTRACK_CHAIN_EVENTS) 949 | static int exp_event_cb(unsigned int events, const struct nf_exp_event *item) { 950 | return 0; 951 | } 952 | #endif 953 | 954 | static __be32 get_device_ip(const struct net_device* dev) { 955 | struct in_device* in_dev; 956 | struct in_ifaddr* if_info; 957 | __be32 result; 958 | 959 | if (dev == NULL) { 960 | return 0; 961 | } 962 | 963 | rcu_read_lock(); 964 | in_dev = dev->ip_ptr; 965 | if (in_dev == NULL) { 966 | rcu_read_unlock(); 967 | return 0; 968 | } 969 | if_info = in_dev->ifa_list; 970 | if (if_info) { 971 | result = if_info->ifa_local; 972 | rcu_read_unlock(); 973 | return result; 974 | } else { 975 | rcu_read_unlock(); 976 | return 0; 977 | } 978 | } 979 | 980 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0) 981 | static uint16_t find_appropriate_port(struct net *net, const struct nf_conntrack_zone *zone, const uint16_t original_port, const __be32 ext_ip, const struct nf_nat_ipv4_range *range) { 982 | #else 983 | static uint16_t find_appropriate_port(struct net *net, const u16 zone, const uint16_t original_port, const __be32 ext_ip, const struct nf_nat_ipv4_range *range) { 984 | #endif 985 | uint16_t min, start, selected, range_size, i; 986 | struct nat_mapping* mapping = NULL; 987 | 988 | if (range->flags & NF_NAT_RANGE_PROTO_SPECIFIED) { 989 | min = be16_to_cpu((range->min).udp.port); 990 | range_size = be16_to_cpu((range->max).udp.port) - min + 1; 991 | } else { 992 | /* minimum port is 1024. same behavior as default linux NAT. */ 993 | min = 1024; 994 | range_size = 65535 - min + 1; 995 | } 996 | 997 | if ((range->flags & NF_NAT_RANGE_PROTO_RANDOM) 998 | || (range->flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY)) { 999 | /* for now we do the same thing for both --random and --random-fully */ 1000 | 1001 | /* select a random starting point */ 1002 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 11, 0) 1003 | start = (uint16_t)(get_random_u32() % (u32)range_size); 1004 | #else 1005 | start = (uint16_t)(prandom_u32() % (u32)range_size); 1006 | #endif 1007 | } else { 1008 | 1009 | if ((original_port >= min && original_port <= min + range_size - 1) 1010 | || !(range->flags & NF_NAT_RANGE_PROTO_SPECIFIED)) { 1011 | /* 1. try to preserve the port if it's available */ 1012 | mapping = get_mapping_by_ext_port(original_port, ext_ip, net, zone); 1013 | if (mapping == NULL) { 1014 | return original_port; 1015 | } 1016 | } 1017 | 1018 | /* otherwise, we start from zero */ 1019 | start = 0; 1020 | } 1021 | 1022 | for (i = 0; i < range_size; i++) { 1023 | /* 2. try to find an available port */ 1024 | selected = min + ((start + i) % range_size); 1025 | mapping = get_mapping_by_ext_port(selected, ext_ip, net, zone); 1026 | if (mapping == NULL) { 1027 | return selected; 1028 | } 1029 | } 1030 | 1031 | /* 3. at least we tried. override a previous mapping. */ 1032 | selected = min + start; 1033 | mapping = get_mapping_by_ext_port(selected, ext_ip, net, zone); 1034 | kill_mapping(mapping); 1035 | 1036 | return selected; 1037 | } 1038 | 1039 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0) 1040 | static __be32 find_leastused_ip(const struct nf_conntrack_zone *zone, const struct nf_nat_ipv4_range *range, const __be32 src, const __be32 dst) 1041 | #else 1042 | static __be32 find_leastused_ip(const u16 zone, const struct nf_nat_ipv4_range *range, const __be32 src, const __be32 dst) 1043 | #endif 1044 | { 1045 | /* Host order */ 1046 | u32 minip, maxip, j, dist; 1047 | 1048 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0) 1049 | j = jhash_1word((u32)src, range->flags & NF_NAT_RANGE_PERSISTENT ? 0 : dst ^ zone->id); 1050 | #else 1051 | j = jhash_1word((u32)src, range->flags & NF_NAT_RANGE_PERSISTENT ? 0 : dst ^ zone); 1052 | #endif 1053 | 1054 | minip = ntohl(range->min_ip); 1055 | maxip = ntohl(range->max_ip); 1056 | dist = maxip - minip + 1; 1057 | 1058 | return (__be32) htonl(minip + reciprocal_scale(j, dist)); 1059 | } 1060 | 1061 | static unsigned int fullconenat_tg(struct sk_buff *skb, const struct xt_action_param *par) 1062 | { 1063 | const struct nf_nat_ipv4_multi_range_compat *mr; 1064 | const struct nf_nat_ipv4_range *range; 1065 | 1066 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 3, 0) 1067 | const struct nf_conntrack_zone *zone; 1068 | #else 1069 | u16 zone; 1070 | #endif 1071 | struct net *net; 1072 | struct nf_conn *ct; 1073 | enum ip_conntrack_info ctinfo; 1074 | struct nf_conn_nat *nat; 1075 | struct nf_conntrack_tuple *ct_tuple, *ct_tuple_origin; 1076 | 1077 | struct nat_mapping *mapping, *src_mapping; 1078 | unsigned int ret; 1079 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 18, 0) 1080 | struct nf_nat_range2 newrange; 1081 | #else 1082 | struct nf_nat_range newrange; 1083 | #endif 1084 | 1085 | __be32 ip; 1086 | uint16_t port, original_port, want_port; 1087 | uint8_t protonum; 1088 | 1089 | ip = 0; 1090 | original_port = 0; 1091 | src_mapping = NULL; 1092 | 1093 | mr = par->targinfo; 1094 | range = &mr->range[0]; 1095 | 1096 | mapping = NULL; 1097 | ret = XT_CONTINUE; 1098 | 1099 | ct = nf_ct_get(skb, &ctinfo); 1100 | net = nf_ct_net(ct); 1101 | zone = nf_ct_zone(ct); 1102 | 1103 | memset(&newrange.min_addr, 0, sizeof(newrange.min_addr)); 1104 | memset(&newrange.max_addr, 0, sizeof(newrange.max_addr)); 1105 | newrange.flags = mr->range[0].flags | NF_NAT_RANGE_MAP_IPS; 1106 | newrange.min_proto = mr->range[0].min; 1107 | newrange.max_proto = mr->range[0].max; 1108 | 1109 | if (xt_hooknum(par) == NF_INET_PRE_ROUTING) { 1110 | /* inbound packets */ 1111 | ct_tuple_origin = &(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple); 1112 | 1113 | protonum = (ct_tuple_origin->dst).protonum; 1114 | if (protonum != IPPROTO_UDP) { 1115 | return ret; 1116 | } 1117 | ip = (ct_tuple_origin->dst).u3.ip; 1118 | port = be16_to_cpu((ct_tuple_origin->dst).u.udp.port); 1119 | 1120 | spin_lock_bh(&fullconenat_lock); 1121 | 1122 | /* find an active mapping based on the inbound port */ 1123 | mapping = get_mapping_by_ext_port(port, ip, net, zone); 1124 | if (mapping != NULL) { 1125 | newrange.flags = NF_NAT_RANGE_MAP_IPS | NF_NAT_RANGE_PROTO_SPECIFIED; 1126 | newrange.min_addr.ip = mapping->int_addr; 1127 | newrange.max_addr.ip = mapping->int_addr; 1128 | newrange.min_proto.udp.port = cpu_to_be16(mapping->int_port); 1129 | newrange.max_proto = newrange.min_proto; 1130 | 1131 | pr_debug("xt_FULLCONENAT: %s ==> %pI4:%d\n", nf_ct_stringify_tuple(ct_tuple_origin), &mapping->int_addr, mapping->int_port); 1132 | 1133 | ret = nf_nat_setup_info(ct, &newrange, HOOK2MANIP(xt_hooknum(par))); 1134 | 1135 | if (ret == NF_ACCEPT) { 1136 | add_original_tuple_to_mapping(mapping, ct_tuple_origin); 1137 | pr_debug("xt_FULLCONENAT: fullconenat_tg(): INBOUND: refer_count for mapping at ext_port %d is now %d\n", mapping->port, mapping->refer_count); 1138 | } 1139 | } 1140 | spin_unlock_bh(&fullconenat_lock); 1141 | return ret; 1142 | 1143 | 1144 | } else if (xt_hooknum(par) == NF_INET_POST_ROUTING) { 1145 | /* outbound packets */ 1146 | ct_tuple_origin = &(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple); 1147 | protonum = (ct_tuple_origin->dst).protonum; 1148 | 1149 | if(range->flags & NF_NAT_RANGE_MAP_IPS) { 1150 | newrange.min_addr.ip = mr->range[0].min_ip; 1151 | newrange.max_addr.ip = mr->range[0].max_ip; 1152 | } else { 1153 | newrange.min_addr.ip = get_device_ip(skb->dev); 1154 | if (unlikely(!newrange.min_addr.ip)) 1155 | return NF_DROP; 1156 | newrange.max_addr.ip = newrange.min_addr.ip; 1157 | 1158 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 16, 0) 1159 | nat = nf_ct_nat_ext_add(ct); 1160 | #else 1161 | nat = nfct_nat(ct); 1162 | #endif 1163 | if (likely(nat)) 1164 | nat->masq_index = xt_out(par)->ifindex; 1165 | 1166 | } 1167 | 1168 | if (protonum == IPPROTO_UDP) { 1169 | ip = (ct_tuple_origin->src).u3.ip; 1170 | original_port = be16_to_cpu((ct_tuple_origin->src).u.udp.port); 1171 | 1172 | spin_lock_bh(&fullconenat_lock); 1173 | 1174 | if (newrange.min_addr.ip != newrange.max_addr.ip) 1175 | src_mapping = get_mapping_by_int_src_inrange(ip, original_port, newrange.min_addr.ip, newrange.max_addr.ip); 1176 | else 1177 | src_mapping = get_mapping_by_int_src(ip, original_port, newrange.min_addr.ip); 1178 | 1179 | if (src_mapping != NULL && check_mapping(src_mapping, net, zone)) { 1180 | 1181 | /* outbound nat: if a previously established mapping is active, 1182 | * we will reuse that mapping. */ 1183 | 1184 | newrange.flags = NF_NAT_RANGE_MAP_IPS | NF_NAT_RANGE_PROTO_SPECIFIED; 1185 | newrange.min_proto.udp.port = cpu_to_be16(src_mapping->port); 1186 | newrange.max_proto = newrange.min_proto; 1187 | if (newrange.min_addr.ip != newrange.max_addr.ip) { 1188 | newrange.min_addr.ip = src_mapping->addr; 1189 | newrange.max_addr.ip = newrange.min_addr.ip; 1190 | } 1191 | 1192 | } else { 1193 | 1194 | /* if not, we find a new external IP:port to map to. 1195 | * the SNAT may fail so we should re-check the mapped port later. */ 1196 | if (newrange.min_addr.ip != newrange.max_addr.ip) { 1197 | newrange.min_addr.ip = find_leastused_ip(zone, range, ip, (ct_tuple_origin->dst).u3.ip); 1198 | newrange.max_addr.ip = newrange.min_addr.ip; 1199 | } 1200 | want_port = find_appropriate_port(net, zone, original_port, newrange.min_addr.ip, range); 1201 | 1202 | newrange.flags = NF_NAT_RANGE_MAP_IPS | NF_NAT_RANGE_PROTO_SPECIFIED; 1203 | newrange.min_proto.udp.port = cpu_to_be16(want_port); 1204 | newrange.max_proto = newrange.min_proto; 1205 | 1206 | src_mapping = NULL; 1207 | 1208 | } 1209 | } 1210 | 1211 | /* do SNAT now */ 1212 | ret = nf_nat_setup_info(ct, &newrange, HOOK2MANIP(xt_hooknum(par))); 1213 | 1214 | if (protonum != IPPROTO_UDP) { 1215 | /* non-UDP packets, bailout */ 1216 | return ret; 1217 | } 1218 | if (ret != NF_ACCEPT) { 1219 | /* failed SNAT, bailout */ 1220 | spin_unlock_bh(&fullconenat_lock); 1221 | return ret; 1222 | } 1223 | 1224 | /* the reply tuple contains the mapped port. */ 1225 | ct_tuple = &(ct->tuplehash[IP_CT_DIR_REPLY].tuple); 1226 | /* this is the resulted mapped port. */ 1227 | port = be16_to_cpu((ct_tuple->dst).u.udp.port); 1228 | 1229 | pr_debug("xt_FULLCONENAT: %s ==> %d\n", nf_ct_stringify_tuple(ct_tuple_origin), port); 1230 | 1231 | /* save the mapping information into our mapping table */ 1232 | mapping = src_mapping; 1233 | if (mapping == NULL) { 1234 | mapping = allocate_mapping(ip, original_port, port, (ct_tuple->dst).u3.ip); 1235 | } 1236 | if (likely(mapping != NULL)) { 1237 | add_original_tuple_to_mapping(mapping, ct_tuple_origin); 1238 | pr_debug("xt_FULLCONENAT: fullconenat_tg(): OUTBOUND: refer_count for mapping at ext_port %d is now %d\n", mapping->port, mapping->refer_count); 1239 | } 1240 | 1241 | spin_unlock_bh(&fullconenat_lock); 1242 | return ret; 1243 | } 1244 | 1245 | return ret; 1246 | } 1247 | 1248 | static int fullconenat_tg_check(const struct xt_tgchk_param *par) 1249 | { 1250 | nf_ct_netns_get(par->net, par->family); 1251 | 1252 | mutex_lock(&nf_ct_net_event_lock); 1253 | 1254 | tg_refer_count++; 1255 | 1256 | pr_debug("xt_FULLCONENAT: fullconenat_tg_check(): tg_refer_count is now %d\n", tg_refer_count); 1257 | 1258 | if (tg_refer_count == 1) { 1259 | #ifdef CONFIG_NF_CONNTRACK_CHAIN_EVENTS 1260 | ct_event_notifier.notifier_call = ct_event_cb; 1261 | #elif LINUX_VERSION_CODE >= KERNEL_VERSION(5, 15, 0) 1262 | ct_event_notifier.ct_event = ct_event_cb; 1263 | ct_event_notifier.exp_event = exp_event_cb; 1264 | #else 1265 | ct_event_notifier.fcn = ct_event_cb; 1266 | #endif 1267 | 1268 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 15, 0) && !defined(CONFIG_NF_CONNTRACK_CHAIN_EVENTS) 1269 | if (!READ_ONCE(par->net->ct.nf_conntrack_event_cb)) { 1270 | nf_conntrack_register_notifier(par->net, &ct_event_notifier); 1271 | #else 1272 | if (nf_conntrack_register_notifier(par->net, &ct_event_notifier) == 0) { 1273 | #endif 1274 | ct_event_notifier_registered = 1; 1275 | pr_debug("xt_FULLCONENAT: fullconenat_tg_check(): ct_event_notifier registered\n"); 1276 | } else { 1277 | printk("xt_FULLCONENAT: warning: failed to register a conntrack notifier. Disable active GC for mappings.\n"); 1278 | } 1279 | 1280 | } 1281 | 1282 | mutex_unlock(&nf_ct_net_event_lock); 1283 | 1284 | return 0; 1285 | } 1286 | 1287 | static void fullconenat_tg_destroy(const struct xt_tgdtor_param *par) 1288 | { 1289 | mutex_lock(&nf_ct_net_event_lock); 1290 | 1291 | tg_refer_count--; 1292 | 1293 | pr_debug("xt_FULLCONENAT: fullconenat_tg_destroy(): tg_refer_count is now %d\n", tg_refer_count); 1294 | 1295 | if (tg_refer_count == 0) { 1296 | if (ct_event_notifier_registered) { 1297 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 15, 0) && !defined(CONFIG_NF_CONNTRACK_CHAIN_EVENTS) 1298 | nf_conntrack_unregister_notifier(par->net); 1299 | #else 1300 | nf_conntrack_unregister_notifier(par->net, &ct_event_notifier); 1301 | #endif 1302 | ct_event_notifier_registered = 0; 1303 | 1304 | pr_debug("xt_FULLCONENAT: fullconenat_tg_destroy(): ct_event_notifier unregistered\n"); 1305 | 1306 | } 1307 | } 1308 | 1309 | mutex_unlock(&nf_ct_net_event_lock); 1310 | 1311 | nf_ct_netns_put(par->net, par->family); 1312 | } 1313 | 1314 | static struct xt_target tg_reg[] __read_mostly = { 1315 | #if IS_ENABLED(CONFIG_NF_NAT_IPV6) || (IS_ENABLED(CONFIG_IPV6) && LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0)) 1316 | { 1317 | .name = "FULLCONENAT", 1318 | .family = NFPROTO_IPV6, 1319 | .revision = 0, 1320 | .target = fullconenat_tg6, 1321 | .targetsize = sizeof(struct nf_nat_range), 1322 | .table = "nat", 1323 | .hooks = (1 << NF_INET_PRE_ROUTING) | 1324 | (1 << NF_INET_POST_ROUTING), 1325 | .checkentry = fullconenat_tg_check, 1326 | .destroy = fullconenat_tg_destroy, 1327 | .me = THIS_MODULE, 1328 | }, 1329 | #endif 1330 | { 1331 | .name = "FULLCONENAT", 1332 | .family = NFPROTO_IPV4, 1333 | .revision = 0, 1334 | .target = fullconenat_tg, 1335 | .targetsize = sizeof(struct nf_nat_ipv4_multi_range_compat), 1336 | .table = "nat", 1337 | .hooks = (1 << NF_INET_PRE_ROUTING) | 1338 | (1 << NF_INET_POST_ROUTING), 1339 | .checkentry = fullconenat_tg_check, 1340 | .destroy = fullconenat_tg_destroy, 1341 | .me = THIS_MODULE, 1342 | }, 1343 | }; 1344 | 1345 | static int __init fullconenat_tg_init(void) 1346 | { 1347 | int ret; 1348 | wq = create_singlethread_workqueue("xt_FULLCONENAT"); 1349 | if (wq == NULL) { 1350 | printk("xt_FULLCONENAT: warning: failed to create workqueue\n"); 1351 | } 1352 | 1353 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 2, 0) 1354 | ret = nf_nat_masquerade_inet_register_notifiers(); 1355 | if (unlikely(ret)) 1356 | return ret; 1357 | #elif LINUX_VERSION_CODE >= KERNEL_VERSION(4, 19, 0) 1358 | ret = nf_nat_masquerade_ipv4_register_notifier(); 1359 | if (unlikely(ret)) 1360 | return ret; 1361 | #if IS_ENABLED(CONFIG_NF_NAT_MASQUERADE_IPV6) 1362 | ret = nf_nat_masquerade_ipv6_register_notifier(); 1363 | if (unlikely(ret)) { 1364 | nf_nat_masquerade_ipv4_unregister_notifier(); 1365 | return ret; 1366 | } 1367 | #endif 1368 | #elif LINUX_VERSION_CODE >= KERNEL_VERSION(3, 18, 0) 1369 | nf_nat_masquerade_ipv4_register_notifier(); 1370 | #if IS_ENABLED(CONFIG_NF_NAT_MASQUERADE_IPV6) 1371 | nf_nat_masquerade_ipv6_register_notifier(); 1372 | #endif 1373 | #else 1374 | #if IS_MODULE(CONFIG_IP_NF_TARGET_MASQUERADE) 1375 | if (!xt_find_revision(AF_INET, "MASQUERADE", 0, 1, &ret)) 1376 | request_module_nowait("ipt_MASQUERADE"); 1377 | #endif 1378 | #if IS_MODULE(CONFIG_IP6_NF_TARGET_MASQUERADE) 1379 | if (!xt_find_revision(AF_INET6, "MASQUERADE", 0, 1, &ret)) 1380 | request_module_nowait("ip6t_MASQUERADE"); 1381 | #endif 1382 | #endif 1383 | 1384 | return xt_register_targets(tg_reg, ARRAY_SIZE(tg_reg)); 1385 | } 1386 | 1387 | static void fullconenat_tg_exit(void) 1388 | { 1389 | xt_unregister_targets(tg_reg, ARRAY_SIZE(tg_reg)); 1390 | 1391 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 2, 0) 1392 | nf_nat_masquerade_inet_unregister_notifiers(); 1393 | #elif LINUX_VERSION_CODE >= KERNEL_VERSION(3, 18, 0) 1394 | #if IS_ENABLED(CONFIG_NF_NAT_MASQUERADE_IPV6) 1395 | nf_nat_masquerade_ipv6_unregister_notifier(); 1396 | #endif 1397 | nf_nat_masquerade_ipv4_unregister_notifier(); 1398 | #endif 1399 | 1400 | if (wq) { 1401 | cancel_delayed_work_sync(&gc_worker_wk); 1402 | flush_workqueue(wq); 1403 | destroy_workqueue(wq); 1404 | } 1405 | 1406 | handle_dying_tuples(); 1407 | destroy_mappings(); 1408 | } 1409 | 1410 | module_init(fullconenat_tg_init); 1411 | module_exit(fullconenat_tg_exit); 1412 | 1413 | MODULE_LICENSE("GPL"); 1414 | MODULE_DESCRIPTION("Xtables: implementation of RFC3489 full cone NAT"); 1415 | MODULE_AUTHOR("Chion Tang "); 1416 | #if IS_ENABLED(CONFIG_NF_NAT_IPV6) || (IS_ENABLED(CONFIG_IPV6) && LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0)) 1417 | MODULE_ALIAS("ip6t_FULLCONENAT"); 1418 | #endif 1419 | MODULE_ALIAS("ipt_FULLCONENAT"); 1420 | --------------------------------------------------------------------------------