├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── libipt_FULLCONENAT.c ├── libipt_FULLCONENAT.t └── xt_FULLCONENAT.c /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .tmp_versions 3 | *.ko 4 | *.cmd 5 | *.o 6 | modules.order 7 | Module.symvers 8 | *.mod.c 9 | .idea 10 | 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 | obj-m = xt_FULLCONENAT.o 2 | CFLAGS_xt_FULLCONENAT.o := ${CFLAGS} 3 | KVERSION = $(shell uname -r) 4 | all: 5 | make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules 6 | clean: 7 | make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean 8 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | }; 21 | 22 | static void FULLCONENAT_help(void) 23 | { 24 | printf( 25 | "FULLCONENAT target options:\n" 26 | " --to-source [[-]]\n" 27 | " Address to map source to.\n" 28 | " --to-ports [-]\n" 29 | " Port (range) to map to.\n" 30 | " --random\n" 31 | " Randomize source port.\n" 32 | " --random-fully\n" 33 | " Fully randomize source port.\n"); 34 | } 35 | 36 | static const struct xt_option_entry FULLCONENAT_opts[] = { 37 | {.name = "to-ports", .id = O_TO_PORTS, .type = XTTYPE_STRING}, 38 | {.name = "random", .id = O_RANDOM, .type = XTTYPE_NONE}, 39 | {.name = "random-fully", .id = O_RANDOM_FULLY, .type = XTTYPE_NONE}, 40 | {.name = "to-source", .id = O_TO_SRC, .type = XTTYPE_STRING}, 41 | XTOPT_TABLEEND, 42 | }; 43 | 44 | static void parse_to(const char *orig_arg, struct nf_nat_ipv4_multi_range_compat *mr) 45 | { 46 | char *arg, *dash, *error; 47 | const struct in_addr *ip; 48 | 49 | arg = strdup(orig_arg); 50 | if (arg == NULL) 51 | xtables_error(RESOURCE_PROBLEM, "strdup"); 52 | 53 | mr->range[0].flags |= NF_NAT_RANGE_MAP_IPS; 54 | dash = strchr(arg, '-'); 55 | 56 | if (dash) 57 | *dash = '\0'; 58 | 59 | ip = xtables_numeric_to_ipaddr(arg); 60 | if (!ip) 61 | xtables_error(PARAMETER_PROBLEM, "Bad IP address \"%s\"\n", 62 | arg); 63 | mr->range[0].min_ip = ip->s_addr; 64 | if (dash) { 65 | ip = xtables_numeric_to_ipaddr(dash+1); 66 | if (!ip) 67 | xtables_error(PARAMETER_PROBLEM, "Bad IP address \"%s\"\n", 68 | dash+1); 69 | mr->range[0].max_ip = ip->s_addr; 70 | } else 71 | mr->range[0].max_ip = mr->range[0].min_ip; 72 | 73 | free(arg); 74 | } 75 | 76 | static void FULLCONENAT_init(struct xt_entry_target *t) 77 | { 78 | struct nf_nat_ipv4_multi_range_compat *mr = (struct nf_nat_ipv4_multi_range_compat *)t->data; 79 | 80 | /* Actually, it's 0, but it's ignored at the moment. */ 81 | mr->rangesize = 1; 82 | } 83 | 84 | /* Parses ports */ 85 | static void 86 | parse_ports(const char *arg, struct nf_nat_ipv4_multi_range_compat *mr) 87 | { 88 | char *end; 89 | unsigned int port, maxport; 90 | 91 | mr->range[0].flags |= NF_NAT_RANGE_PROTO_SPECIFIED; 92 | 93 | if (!xtables_strtoui(arg, &end, &port, 0, UINT16_MAX)) 94 | xtables_param_act(XTF_BAD_VALUE, "FULLCONENAT", "--to-ports", arg); 95 | 96 | switch (*end) { 97 | case '\0': 98 | mr->range[0].min.tcp.port 99 | = mr->range[0].max.tcp.port 100 | = htons(port); 101 | return; 102 | case '-': 103 | if (!xtables_strtoui(end + 1, NULL, &maxport, 0, UINT16_MAX)) 104 | break; 105 | 106 | if (maxport < port) 107 | break; 108 | 109 | mr->range[0].min.tcp.port = htons(port); 110 | mr->range[0].max.tcp.port = htons(maxport); 111 | return; 112 | default: 113 | break; 114 | } 115 | xtables_param_act(XTF_BAD_VALUE, "FULLCONENAT", "--to-ports", arg); 116 | } 117 | 118 | static void FULLCONENAT_parse(struct xt_option_call *cb) 119 | { 120 | const struct ipt_entry *entry = cb->xt_entry; 121 | int portok; 122 | struct nf_nat_ipv4_multi_range_compat *mr = cb->data; 123 | 124 | if (entry->ip.proto == IPPROTO_TCP 125 | || entry->ip.proto == IPPROTO_UDP 126 | || entry->ip.proto == IPPROTO_SCTP 127 | || entry->ip.proto == IPPROTO_DCCP 128 | || entry->ip.proto == IPPROTO_ICMP) 129 | portok = 1; 130 | else 131 | portok = 0; 132 | 133 | xtables_option_parse(cb); 134 | switch (cb->entry->id) { 135 | case O_TO_PORTS: 136 | if (!portok) 137 | xtables_error(PARAMETER_PROBLEM, 138 | "Need TCP, UDP, SCTP or DCCP with port specification"); 139 | parse_ports(cb->arg, mr); 140 | break; 141 | case O_TO_SRC: 142 | parse_to(cb->arg, mr); 143 | break; 144 | case O_RANDOM: 145 | mr->range[0].flags |= NF_NAT_RANGE_PROTO_RANDOM; 146 | break; 147 | case O_RANDOM_FULLY: 148 | mr->range[0].flags |= NF_NAT_RANGE_PROTO_RANDOM_FULLY; 149 | break; 150 | } 151 | } 152 | 153 | static void 154 | FULLCONENAT_print(const void *ip, const struct xt_entry_target *target, 155 | int numeric) 156 | { 157 | const struct nf_nat_ipv4_multi_range_compat *mr = (const void *)target->data; 158 | const struct nf_nat_ipv4_range *r = &mr->range[0]; 159 | 160 | if (r->flags & NF_NAT_RANGE_MAP_IPS) { 161 | struct in_addr a; 162 | 163 | a.s_addr = r->min_ip; 164 | printf(" to:%s", xtables_ipaddr_to_numeric(&a)); 165 | if (r->max_ip != r->min_ip) { 166 | a.s_addr = r->max_ip; 167 | printf("-%s", xtables_ipaddr_to_numeric(&a)); 168 | } 169 | } 170 | 171 | if (r->flags & NF_NAT_RANGE_PROTO_SPECIFIED) { 172 | printf(" masq ports: "); 173 | printf("%hu", ntohs(r->min.tcp.port)); 174 | if (r->max.tcp.port != r->min.tcp.port) 175 | printf("-%hu", ntohs(r->max.tcp.port)); 176 | } 177 | 178 | if (r->flags & NF_NAT_RANGE_PROTO_RANDOM) 179 | printf(" random"); 180 | 181 | if (r->flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY) 182 | printf(" random-fully"); 183 | } 184 | 185 | static void 186 | FULLCONENAT_save(const void *ip, const struct xt_entry_target *target) 187 | { 188 | const struct nf_nat_ipv4_multi_range_compat *mr = (const void *)target->data; 189 | const struct nf_nat_ipv4_range *r = &mr->range[0]; 190 | 191 | if (r->flags & NF_NAT_RANGE_MAP_IPS) { 192 | struct in_addr a; 193 | 194 | a.s_addr = r->min_ip; 195 | printf(" --to-source %s", xtables_ipaddr_to_numeric(&a)); 196 | if (r->max_ip != r->min_ip) { 197 | a.s_addr = r->max_ip; 198 | printf("-%s", xtables_ipaddr_to_numeric(&a)); 199 | } 200 | } 201 | 202 | if (r->flags & NF_NAT_RANGE_PROTO_SPECIFIED) { 203 | printf(" --to-ports %hu", ntohs(r->min.tcp.port)); 204 | if (r->max.tcp.port != r->min.tcp.port) 205 | printf("-%hu", ntohs(r->max.tcp.port)); 206 | } 207 | 208 | if (r->flags & NF_NAT_RANGE_PROTO_RANDOM) 209 | printf(" --random"); 210 | 211 | if (r->flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY) 212 | printf(" --random-fully"); 213 | } 214 | 215 | static struct xtables_target fullconenat_tg_reg = { 216 | .name = "FULLCONENAT", 217 | .version = XTABLES_VERSION, 218 | .family = NFPROTO_IPV4, 219 | .size = XT_ALIGN(sizeof(struct nf_nat_ipv4_multi_range_compat)), 220 | .userspacesize = XT_ALIGN(sizeof(struct nf_nat_ipv4_multi_range_compat)), 221 | .help = FULLCONENAT_help, 222 | .init = FULLCONENAT_init, 223 | .x6_parse = FULLCONENAT_parse, 224 | .print = FULLCONENAT_print, 225 | .save = FULLCONENAT_save, 226 | .x6_options = FULLCONENAT_opts, 227 | }; 228 | 229 | void _init(void) 230 | { 231 | xtables_register_target(&fullconenat_tg_reg); 232 | } 233 | -------------------------------------------------------------------------------- /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 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | 31 | #define HASH_2(x, y) ((x + y) / 2 * (x + y + 1) + y) 32 | 33 | #define HASHTABLE_BUCKET_BITS 10 34 | 35 | #ifndef NF_NAT_RANGE_PROTO_RANDOM_FULLY 36 | #define NF_NAT_RANGE_PROTO_RANDOM_FULLY (1 << 4) 37 | #endif 38 | 39 | #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 10, 0) 40 | 41 | static inline int nf_ct_netns_get(struct net *net, u8 nfproto) { return 0; } 42 | 43 | static inline void nf_ct_netns_put(struct net *net, u8 nfproto) {} 44 | 45 | static inline struct net_device *xt_in(const struct xt_action_param *par) { 46 | return par->in; 47 | } 48 | 49 | static inline struct net_device *xt_out(const struct xt_action_param *par) { 50 | return par->out; 51 | } 52 | 53 | static inline unsigned int xt_hooknum(const struct xt_action_param *par) { 54 | return par->hooknum; 55 | } 56 | 57 | #endif 58 | 59 | struct nat_mapping_original_tuple { 60 | struct nf_conntrack_tuple tuple; 61 | 62 | struct list_head node; 63 | }; 64 | 65 | struct nat_mapping { 66 | uint16_t port; /* external UDP port */ 67 | int ifindex; /* external interface index*/ 68 | 69 | __be32 int_addr; /* internal source ip address */ 70 | uint16_t int_port; /* internal source port */ 71 | 72 | int refer_count; /* how many references linked to this mapping 73 | * aka. length of original_tuple_list */ 74 | 75 | struct list_head original_tuple_list; 76 | 77 | struct hlist_node node_by_ext_port; 78 | struct hlist_node node_by_int_src; 79 | 80 | }; 81 | 82 | struct tuple_list { 83 | struct nf_conntrack_tuple tuple_original; 84 | struct nf_conntrack_tuple tuple_reply; 85 | struct list_head list; 86 | }; 87 | 88 | #ifdef CONFIG_NF_CONNTRACK_CHAIN_EVENTS 89 | struct notifier_block ct_event_notifier; 90 | #else 91 | struct nf_ct_event_notifier ct_event_notifier; 92 | #endif 93 | int tg_refer_count = 0; 94 | int ct_event_notifier_registered = 0; 95 | 96 | static DEFINE_MUTEX(nf_ct_net_event_lock); 97 | 98 | static DEFINE_HASHTABLE(mapping_table_by_ext_port, HASHTABLE_BUCKET_BITS); 99 | static DEFINE_HASHTABLE(mapping_table_by_int_src, HASHTABLE_BUCKET_BITS); 100 | 101 | static DEFINE_SPINLOCK(fullconenat_lock); 102 | 103 | static LIST_HEAD(dying_tuple_list); 104 | static DEFINE_SPINLOCK(dying_tuple_list_lock); 105 | static void gc_worker(struct work_struct *work); 106 | static struct workqueue_struct *wq __read_mostly = NULL; 107 | static DECLARE_DELAYED_WORK(gc_worker_wk, gc_worker); 108 | 109 | static char tuple_tmp_string[512]; 110 | /* non-atomic: can only be called serially within lock zones. */ 111 | static char* nf_ct_stringify_tuple(const struct nf_conntrack_tuple *t) { 112 | snprintf(tuple_tmp_string, sizeof(tuple_tmp_string), "%pI4:%hu -> %pI4:%hu", 113 | &t->src.u3.ip, be16_to_cpu(t->src.u.all), 114 | &t->dst.u3.ip, be16_to_cpu(t->dst.u.all)); 115 | return tuple_tmp_string; 116 | } 117 | 118 | static struct nat_mapping* allocate_mapping(const __be32 int_addr, const uint16_t int_port, const uint16_t port, const int ifindex) { 119 | struct nat_mapping *p_new; 120 | u32 hash_src; 121 | 122 | p_new = kmalloc(sizeof(struct nat_mapping), GFP_ATOMIC); 123 | if (p_new == NULL) { 124 | pr_debug("xt_FULLCONENAT: ERROR: kmalloc() for new nat_mapping failed.\n"); 125 | return NULL; 126 | } 127 | p_new->port = port; 128 | p_new->int_addr = int_addr; 129 | p_new->int_port = int_port; 130 | p_new->ifindex = ifindex; 131 | p_new->refer_count = 0; 132 | (p_new->original_tuple_list).next = &(p_new->original_tuple_list); 133 | (p_new->original_tuple_list).prev = &(p_new->original_tuple_list); 134 | 135 | hash_src = HASH_2(int_addr, (u32)int_port); 136 | 137 | hash_add(mapping_table_by_ext_port, &p_new->node_by_ext_port, port); 138 | hash_add(mapping_table_by_int_src, &p_new->node_by_int_src, hash_src); 139 | 140 | pr_debug("xt_FULLCONENAT: new mapping allocated for %pI4:%d ==> %d\n", 141 | &p_new->int_addr, p_new->int_port, p_new->port); 142 | 143 | return p_new; 144 | } 145 | 146 | static void add_original_tuple_to_mapping(struct nat_mapping *mapping, const struct nf_conntrack_tuple* original_tuple) { 147 | struct nat_mapping_original_tuple *item = kmalloc(sizeof(struct nat_mapping_original_tuple), GFP_ATOMIC); 148 | if (item == NULL) { 149 | pr_debug("xt_FULLCONENAT: ERROR: kmalloc() for nat_mapping_original_tuple failed.\n"); 150 | return; 151 | } 152 | memcpy(&item->tuple, original_tuple, sizeof(struct nf_conntrack_tuple)); 153 | list_add(&item->node, &mapping->original_tuple_list); 154 | (mapping->refer_count)++; 155 | } 156 | 157 | static struct nat_mapping* get_mapping_by_ext_port(const uint16_t port, const int ifindex) { 158 | struct nat_mapping *p_current; 159 | 160 | hash_for_each_possible(mapping_table_by_ext_port, p_current, node_by_ext_port, port) { 161 | if (p_current->port == port && p_current->ifindex == ifindex) { 162 | return p_current; 163 | } 164 | } 165 | 166 | return NULL; 167 | } 168 | 169 | static struct nat_mapping* get_mapping_by_int_src(const __be32 src_ip, const uint16_t src_port) { 170 | struct nat_mapping *p_current; 171 | u32 hash_src = HASH_2(src_ip, (u32)src_port); 172 | 173 | hash_for_each_possible(mapping_table_by_int_src, p_current, node_by_int_src, hash_src) { 174 | if (p_current->int_addr == src_ip && p_current->int_port == src_port) { 175 | return p_current; 176 | } 177 | } 178 | 179 | return NULL; 180 | } 181 | 182 | static void kill_mapping(struct nat_mapping *mapping) { 183 | struct list_head *iter, *tmp; 184 | struct nat_mapping_original_tuple *original_tuple_item; 185 | 186 | if (mapping == NULL) { 187 | return; 188 | } 189 | 190 | list_for_each_safe(iter, tmp, &mapping->original_tuple_list) { 191 | original_tuple_item = list_entry(iter, struct nat_mapping_original_tuple, node); 192 | list_del(&original_tuple_item->node); 193 | kfree(original_tuple_item); 194 | } 195 | 196 | hash_del(&mapping->node_by_ext_port); 197 | hash_del(&mapping->node_by_int_src); 198 | kfree(mapping); 199 | } 200 | 201 | static void destroy_mappings(void) { 202 | struct nat_mapping *p_current; 203 | struct hlist_node *tmp; 204 | int i; 205 | 206 | spin_lock_bh(&fullconenat_lock); 207 | 208 | hash_for_each_safe(mapping_table_by_ext_port, i, tmp, p_current, node_by_ext_port) { 209 | kill_mapping(p_current); 210 | } 211 | 212 | spin_unlock_bh(&fullconenat_lock); 213 | } 214 | 215 | /* check if a mapping is valid. 216 | * possibly delete and free an invalid mapping. 217 | * the mapping should not be used anymore after check_mapping() returns 0. */ 218 | static int check_mapping(struct nat_mapping* mapping, struct net *net, const struct nf_conntrack_zone *zone) { 219 | struct list_head *iter, *tmp; 220 | struct nat_mapping_original_tuple *original_tuple_item; 221 | struct nf_conntrack_tuple_hash *tuple_hash; 222 | struct nf_conn *ct; 223 | 224 | if (mapping == NULL) { 225 | return 0; 226 | } 227 | 228 | if (mapping->port == 0 || mapping->int_addr == 0 || mapping->int_port == 0 || mapping->ifindex == -1) { 229 | return 0; 230 | } 231 | 232 | /* for dying/unconfirmed conntrack tuples, an IPCT_DESTROY event may NOT be fired. 233 | * so we manually kill one of those tuples once we acquire one. */ 234 | 235 | list_for_each_safe(iter, tmp, &mapping->original_tuple_list) { 236 | original_tuple_item = list_entry(iter, struct nat_mapping_original_tuple, node); 237 | 238 | tuple_hash = nf_conntrack_find_get(net, zone, &original_tuple_item->tuple); 239 | 240 | if (tuple_hash == NULL) { 241 | pr_debug("xt_FULLCONENAT: check_mapping(): tuple %s dying/unconfirmed. free this tuple.\n", nf_ct_stringify_tuple(&original_tuple_item->tuple)); 242 | 243 | list_del(&original_tuple_item->node); 244 | kfree(original_tuple_item); 245 | (mapping->refer_count)--; 246 | } else { 247 | ct = nf_ct_tuplehash_to_ctrack(tuple_hash); 248 | if (ct != NULL) 249 | nf_ct_put(ct); 250 | } 251 | 252 | } 253 | 254 | /* kill the mapping if need */ 255 | pr_debug("xt_FULLCONENAT: check_mapping() refer_count for mapping at ext_port %d is now %d\n", mapping->port, mapping->refer_count); 256 | if (mapping->refer_count <= 0) { 257 | pr_debug("xt_FULLCONENAT: check_mapping(): kill dying/unconfirmed mapping at ext port %d\n", mapping->port); 258 | kill_mapping(mapping); 259 | return 0; 260 | } else { 261 | return 1; 262 | } 263 | } 264 | 265 | static void handle_dying_tuples(void) { 266 | struct list_head *iter, *tmp, *iter_2, *tmp_2; 267 | struct tuple_list *item; 268 | struct nf_conntrack_tuple *ct_tuple; 269 | struct nat_mapping *mapping; 270 | __be32 ip; 271 | uint16_t port; 272 | struct nat_mapping_original_tuple *original_tuple_item; 273 | 274 | spin_lock_bh(&fullconenat_lock); 275 | spin_lock_bh(&dying_tuple_list_lock); 276 | 277 | list_for_each_safe(iter, tmp, &dying_tuple_list) { 278 | item = list_entry(iter, struct tuple_list, list); 279 | 280 | /* we dont know the conntrack direction for now so we try in both ways. */ 281 | ct_tuple = &(item->tuple_original); 282 | ip = (ct_tuple->src).u3.ip; 283 | port = be16_to_cpu((ct_tuple->src).u.udp.port); 284 | mapping = get_mapping_by_int_src(ip, port); 285 | if (mapping == NULL) { 286 | ct_tuple = &(item->tuple_reply); 287 | ip = (ct_tuple->src).u3.ip; 288 | port = be16_to_cpu((ct_tuple->src).u.udp.port); 289 | mapping = get_mapping_by_int_src(ip, port); 290 | if (mapping != NULL) { 291 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): INBOUND dying conntrack at ext port %d\n", mapping->port); 292 | } 293 | } else { 294 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): OUTBOUND dying conntrack at ext port %d\n", mapping->port); 295 | } 296 | 297 | if (mapping == NULL) { 298 | goto next; 299 | } 300 | 301 | /* look for the corresponding out-dated tuple and free it */ 302 | list_for_each_safe(iter_2, tmp_2, &mapping->original_tuple_list) { 303 | original_tuple_item = list_entry(iter_2, struct nat_mapping_original_tuple, node); 304 | 305 | if (nf_ct_tuple_equal(&original_tuple_item->tuple, &(item->tuple_original))) { 306 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): tuple %s expired. free this tuple.\n", 307 | nf_ct_stringify_tuple(&original_tuple_item->tuple)); 308 | list_del(&original_tuple_item->node); 309 | kfree(original_tuple_item); 310 | (mapping->refer_count)--; 311 | } 312 | } 313 | 314 | /* then kill the mapping if needed*/ 315 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): refer_count for mapping at ext_port %d is now %d\n", mapping->port, mapping->refer_count); 316 | if (mapping->refer_count <= 0) { 317 | pr_debug("xt_FULLCONENAT: handle_dying_tuples(): kill expired mapping at ext port %d\n", mapping->port); 318 | kill_mapping(mapping); 319 | } 320 | 321 | next: 322 | list_del(&item->list); 323 | kfree(item); 324 | } 325 | 326 | spin_unlock_bh(&dying_tuple_list_lock); 327 | spin_unlock_bh(&fullconenat_lock); 328 | } 329 | 330 | static void gc_worker(struct work_struct *work) { 331 | handle_dying_tuples(); 332 | } 333 | 334 | /* conntrack destroy event callback function */ 335 | #ifdef CONFIG_NF_CONNTRACK_CHAIN_EVENTS 336 | static int ct_event_cb(struct notifier_block *this, unsigned long events, void *ptr) { 337 | struct nf_ct_event *item = ptr; 338 | #else 339 | static int ct_event_cb(unsigned int events, struct nf_ct_event *item) { 340 | #endif 341 | struct nf_conn *ct; 342 | struct nf_conntrack_tuple *ct_tuple_reply, *ct_tuple_original; 343 | uint8_t protonum; 344 | struct tuple_list *dying_tuple_item; 345 | 346 | ct = item->ct; 347 | /* we handle only conntrack destroy events */ 348 | if (ct == NULL || !(events & (1 << IPCT_DESTROY))) { 349 | return 0; 350 | } 351 | 352 | ct_tuple_original = &(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple); 353 | 354 | ct_tuple_reply = &(ct->tuplehash[IP_CT_DIR_REPLY].tuple); 355 | 356 | protonum = (ct_tuple_original->dst).protonum; 357 | if (protonum != IPPROTO_UDP) { 358 | return 0; 359 | } 360 | 361 | dying_tuple_item = kmalloc(sizeof(struct tuple_list), GFP_ATOMIC); 362 | 363 | if (dying_tuple_item == NULL) { 364 | pr_debug("xt_FULLCONENAT: warning: ct_event_cb(): kmalloc failed.\n"); 365 | return 0; 366 | } 367 | 368 | memcpy(&(dying_tuple_item->tuple_original), ct_tuple_original, sizeof(struct nf_conntrack_tuple)); 369 | memcpy(&(dying_tuple_item->tuple_reply), ct_tuple_reply, sizeof(struct nf_conntrack_tuple)); 370 | 371 | spin_lock_bh(&dying_tuple_list_lock); 372 | 373 | list_add(&(dying_tuple_item->list), &dying_tuple_list); 374 | 375 | spin_unlock_bh(&dying_tuple_list_lock); 376 | 377 | if (wq != NULL) 378 | queue_delayed_work(wq, &gc_worker_wk, msecs_to_jiffies(100)); 379 | 380 | return 0; 381 | } 382 | 383 | static __be32 get_device_ip(const struct net_device* dev) { 384 | struct in_device* in_dev; 385 | struct in_ifaddr* if_info; 386 | __be32 result; 387 | 388 | if (dev == NULL) { 389 | return 0; 390 | } 391 | 392 | rcu_read_lock(); 393 | in_dev = dev->ip_ptr; 394 | if (in_dev == NULL) { 395 | rcu_read_unlock(); 396 | return 0; 397 | } 398 | if_info = in_dev->ifa_list; 399 | if (if_info) { 400 | result = if_info->ifa_local; 401 | rcu_read_unlock(); 402 | return result; 403 | } else { 404 | rcu_read_unlock(); 405 | return 0; 406 | } 407 | } 408 | 409 | static uint16_t find_appropriate_port(struct net *net, const struct nf_conntrack_zone *zone, const uint16_t original_port, const int ifindex, const struct nf_nat_ipv4_range *range) { 410 | uint16_t min, start, selected, range_size, i; 411 | struct nat_mapping* mapping = NULL; 412 | 413 | if (range->flags & NF_NAT_RANGE_PROTO_SPECIFIED) { 414 | min = be16_to_cpu((range->min).udp.port); 415 | range_size = be16_to_cpu((range->max).udp.port) - min + 1; 416 | } else { 417 | /* minimum port is 1024. same behavior as default linux NAT. */ 418 | min = 1024; 419 | range_size = 65535 - min + 1; 420 | } 421 | 422 | if ((range->flags & NF_NAT_RANGE_PROTO_RANDOM) 423 | || (range->flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY)) { 424 | /* for now we do the same thing for both --random and --random-fully */ 425 | 426 | /* select a random starting point */ 427 | start = (uint16_t)(prandom_u32() % (u32)range_size); 428 | } else { 429 | 430 | if ((original_port >= min && original_port <= min + range_size - 1) 431 | || !(range->flags & NF_NAT_RANGE_PROTO_SPECIFIED)) { 432 | /* 1. try to preserve the port if it's available */ 433 | mapping = get_mapping_by_ext_port(original_port, ifindex); 434 | if (mapping == NULL || !(check_mapping(mapping, net, zone))) { 435 | return original_port; 436 | } 437 | } 438 | 439 | /* otherwise, we start from zero */ 440 | start = 0; 441 | } 442 | 443 | for (i = 0; i < range_size; i++) { 444 | /* 2. try to find an available port */ 445 | selected = min + ((start + i) % range_size); 446 | mapping = get_mapping_by_ext_port(selected, ifindex); 447 | if (mapping == NULL || !(check_mapping(mapping, net, zone))) { 448 | return selected; 449 | } 450 | } 451 | 452 | /* 3. at least we tried. override a previous mapping. */ 453 | selected = min + start; 454 | mapping = get_mapping_by_ext_port(selected, ifindex); 455 | kill_mapping(mapping); 456 | 457 | return selected; 458 | } 459 | 460 | static unsigned int fullconenat_tg(struct sk_buff *skb, const struct xt_action_param *par) 461 | { 462 | const struct nf_nat_ipv4_multi_range_compat *mr; 463 | const struct nf_nat_ipv4_range *range; 464 | 465 | const struct nf_conntrack_zone *zone; 466 | struct net *net; 467 | struct nf_conn *ct; 468 | enum ip_conntrack_info ctinfo; 469 | struct nf_conntrack_tuple *ct_tuple, *ct_tuple_origin; 470 | 471 | struct net_device *net_dev; 472 | 473 | struct nat_mapping *mapping, *src_mapping; 474 | unsigned int ret; 475 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 18, 0) 476 | struct nf_nat_range2 newrange; 477 | #else 478 | struct nf_nat_range newrange; 479 | #endif 480 | 481 | __be32 new_ip, ip; 482 | uint16_t port, original_port, want_port; 483 | uint8_t protonum; 484 | int ifindex; 485 | 486 | ip = 0; 487 | original_port = 0; 488 | src_mapping = NULL; 489 | 490 | mr = par->targinfo; 491 | range = &mr->range[0]; 492 | 493 | mapping = NULL; 494 | ret = XT_CONTINUE; 495 | 496 | ct = nf_ct_get(skb, &ctinfo); 497 | net = nf_ct_net(ct); 498 | zone = nf_ct_zone(ct); 499 | 500 | memset(&newrange.min_addr, 0, sizeof(newrange.min_addr)); 501 | memset(&newrange.max_addr, 0, sizeof(newrange.max_addr)); 502 | newrange.flags = mr->range[0].flags | NF_NAT_RANGE_MAP_IPS; 503 | newrange.min_proto = mr->range[0].min; 504 | newrange.max_proto = mr->range[0].max; 505 | 506 | if (xt_hooknum(par) == NF_INET_PRE_ROUTING) { 507 | /* inbound packets */ 508 | ifindex = xt_in(par)->ifindex; 509 | 510 | ct_tuple_origin = &(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple); 511 | 512 | protonum = (ct_tuple_origin->dst).protonum; 513 | if (protonum != IPPROTO_UDP) { 514 | return ret; 515 | } 516 | ip = (ct_tuple_origin->dst).u3.ip; 517 | port = be16_to_cpu((ct_tuple_origin->dst).u.udp.port); 518 | 519 | /* get the corresponding ifindex by the dst_ip (aka. external ip of this host), 520 | * in case the packet needs to be forwarded from another inbound interface. */ 521 | net_dev = ip_dev_find(net, ip); 522 | if (net_dev != NULL) { 523 | ifindex = net_dev->ifindex; 524 | dev_put(net_dev); 525 | } 526 | 527 | spin_lock_bh(&fullconenat_lock); 528 | 529 | /* find an active mapping based on the inbound port */ 530 | mapping = get_mapping_by_ext_port(port, ifindex); 531 | if (mapping == NULL) { 532 | spin_unlock_bh(&fullconenat_lock); 533 | return ret; 534 | } 535 | if (check_mapping(mapping, net, zone)) { 536 | newrange.flags = NF_NAT_RANGE_MAP_IPS | NF_NAT_RANGE_PROTO_SPECIFIED; 537 | newrange.min_addr.ip = mapping->int_addr; 538 | newrange.max_addr.ip = mapping->int_addr; 539 | newrange.min_proto.udp.port = cpu_to_be16(mapping->int_port); 540 | newrange.max_proto = newrange.min_proto; 541 | 542 | pr_debug("xt_FULLCONENAT: %s ==> %pI4:%d\n", nf_ct_stringify_tuple(ct_tuple_origin), &mapping->int_addr, mapping->int_port); 543 | 544 | ret = nf_nat_setup_info(ct, &newrange, HOOK2MANIP(xt_hooknum(par))); 545 | 546 | if (ret == NF_ACCEPT) { 547 | add_original_tuple_to_mapping(mapping, ct_tuple_origin); 548 | pr_debug("xt_FULLCONENAT: fullconenat_tg(): INBOUND: refer_count for mapping at ext_port %d is now %d\n", mapping->port, mapping->refer_count); 549 | } 550 | } 551 | spin_unlock_bh(&fullconenat_lock); 552 | return ret; 553 | 554 | 555 | } else if (xt_hooknum(par) == NF_INET_POST_ROUTING) { 556 | /* outbound packets */ 557 | ifindex = xt_out(par)->ifindex; 558 | 559 | ct_tuple_origin = &(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple); 560 | protonum = (ct_tuple_origin->dst).protonum; 561 | 562 | spin_lock_bh(&fullconenat_lock); 563 | 564 | if (protonum == IPPROTO_UDP) { 565 | ip = (ct_tuple_origin->src).u3.ip; 566 | original_port = be16_to_cpu((ct_tuple_origin->src).u.udp.port); 567 | 568 | src_mapping = get_mapping_by_int_src(ip, original_port); 569 | if (src_mapping != NULL && check_mapping(src_mapping, net, zone)) { 570 | 571 | /* outbound nat: if a previously established mapping is active, 572 | * we will reuse that mapping. */ 573 | 574 | newrange.flags = NF_NAT_RANGE_MAP_IPS | NF_NAT_RANGE_PROTO_SPECIFIED; 575 | newrange.min_proto.udp.port = cpu_to_be16(src_mapping->port); 576 | newrange.max_proto = newrange.min_proto; 577 | 578 | } else { 579 | 580 | /* if not, we find a new external port to map to. 581 | * the SNAT may fail so we should re-check the mapped port later. */ 582 | want_port = find_appropriate_port(net, zone, original_port, ifindex, range); 583 | 584 | newrange.flags = NF_NAT_RANGE_MAP_IPS | NF_NAT_RANGE_PROTO_SPECIFIED; 585 | newrange.min_proto.udp.port = cpu_to_be16(want_port); 586 | newrange.max_proto = newrange.min_proto; 587 | 588 | src_mapping = NULL; 589 | 590 | } 591 | } 592 | 593 | if(mr->range[0].flags & NF_NAT_RANGE_MAP_IPS) { 594 | newrange.min_addr.ip = mr->range[0].min_ip; 595 | newrange.max_addr.ip = mr->range[0].max_ip; 596 | } else { 597 | new_ip = get_device_ip(skb->dev); 598 | newrange.min_addr.ip = new_ip; 599 | newrange.max_addr.ip = new_ip; 600 | } 601 | 602 | /* do SNAT now */ 603 | ret = nf_nat_setup_info(ct, &newrange, HOOK2MANIP(xt_hooknum(par))); 604 | 605 | if (protonum != IPPROTO_UDP || ret != NF_ACCEPT) { 606 | /* for non-UDP packets and failed SNAT, bailout */ 607 | spin_unlock_bh(&fullconenat_lock); 608 | return ret; 609 | } 610 | 611 | /* the reply tuple contains the mapped port. */ 612 | ct_tuple = &(ct->tuplehash[IP_CT_DIR_REPLY].tuple); 613 | /* this is the resulted mapped port. */ 614 | port = be16_to_cpu((ct_tuple->dst).u.udp.port); 615 | 616 | pr_debug("xt_FULLCONENAT: %s ==> %d\n", nf_ct_stringify_tuple(ct_tuple_origin), port); 617 | 618 | /* save the mapping information into our mapping table */ 619 | mapping = src_mapping; 620 | if (mapping == NULL || !check_mapping(mapping, net, zone)) { 621 | mapping = allocate_mapping(ip, original_port, port, ifindex); 622 | } 623 | if (mapping != NULL) { 624 | add_original_tuple_to_mapping(mapping, ct_tuple_origin); 625 | pr_debug("xt_FULLCONENAT: fullconenat_tg(): OUTBOUND: refer_count for mapping at ext_port %d is now %d\n", mapping->port, mapping->refer_count); 626 | } 627 | 628 | spin_unlock_bh(&fullconenat_lock); 629 | return ret; 630 | } 631 | 632 | return ret; 633 | } 634 | 635 | static int fullconenat_tg_check(const struct xt_tgchk_param *par) 636 | { 637 | mutex_lock(&nf_ct_net_event_lock); 638 | 639 | tg_refer_count++; 640 | 641 | pr_debug("xt_FULLCONENAT: fullconenat_tg_check(): tg_refer_count is now %d\n", tg_refer_count); 642 | 643 | if (tg_refer_count == 1) { 644 | nf_ct_netns_get(par->net, par->family); 645 | #ifdef CONFIG_NF_CONNTRACK_CHAIN_EVENTS 646 | ct_event_notifier.notifier_call = ct_event_cb; 647 | #else 648 | ct_event_notifier.fcn = ct_event_cb; 649 | #endif 650 | 651 | if (nf_conntrack_register_notifier(par->net, &ct_event_notifier) == 0) { 652 | ct_event_notifier_registered = 1; 653 | pr_debug("xt_FULLCONENAT: fullconenat_tg_check(): ct_event_notifier registered\n"); 654 | } else { 655 | printk("xt_FULLCONENAT: warning: failed to register a conntrack notifier. Disable active GC for mappings.\n"); 656 | } 657 | 658 | } 659 | 660 | mutex_unlock(&nf_ct_net_event_lock); 661 | 662 | return 0; 663 | } 664 | 665 | static void fullconenat_tg_destroy(const struct xt_tgdtor_param *par) 666 | { 667 | mutex_lock(&nf_ct_net_event_lock); 668 | 669 | tg_refer_count--; 670 | 671 | pr_debug("xt_FULLCONENAT: fullconenat_tg_destroy(): tg_refer_count is now %d\n", tg_refer_count); 672 | 673 | if (tg_refer_count == 0) { 674 | if (ct_event_notifier_registered) { 675 | nf_conntrack_unregister_notifier(par->net, &ct_event_notifier); 676 | ct_event_notifier_registered = 0; 677 | 678 | pr_debug("xt_FULLCONENAT: fullconenat_tg_destroy(): ct_event_notifier unregistered\n"); 679 | 680 | } 681 | nf_ct_netns_put(par->net, par->family); 682 | } 683 | 684 | mutex_unlock(&nf_ct_net_event_lock); 685 | } 686 | 687 | static struct xt_target tg_reg[] __read_mostly = { 688 | { 689 | .name = "FULLCONENAT", 690 | .family = NFPROTO_IPV4, 691 | .revision = 0, 692 | .target = fullconenat_tg, 693 | .targetsize = sizeof(struct nf_nat_ipv4_multi_range_compat), 694 | .table = "nat", 695 | .hooks = (1 << NF_INET_PRE_ROUTING) | 696 | (1 << NF_INET_POST_ROUTING), 697 | .checkentry = fullconenat_tg_check, 698 | .destroy = fullconenat_tg_destroy, 699 | .me = THIS_MODULE, 700 | }, 701 | }; 702 | 703 | static int __init fullconenat_tg_init(void) 704 | { 705 | wq = create_singlethread_workqueue("xt_FULLCONENAT"); 706 | if (wq == NULL) { 707 | printk("xt_FULLCONENAT: warning: failed to create workqueue\n"); 708 | } 709 | 710 | return xt_register_targets(tg_reg, ARRAY_SIZE(tg_reg)); 711 | } 712 | 713 | static void fullconenat_tg_exit(void) 714 | { 715 | xt_unregister_targets(tg_reg, ARRAY_SIZE(tg_reg)); 716 | 717 | if (wq) { 718 | cancel_delayed_work_sync(&gc_worker_wk); 719 | flush_workqueue(wq); 720 | destroy_workqueue(wq); 721 | } 722 | 723 | handle_dying_tuples(); 724 | destroy_mappings(); 725 | } 726 | 727 | module_init(fullconenat_tg_init); 728 | module_exit(fullconenat_tg_exit); 729 | 730 | MODULE_LICENSE("GPL"); 731 | MODULE_DESCRIPTION("Xtables: implementation of RFC3489 full cone NAT"); 732 | MODULE_AUTHOR("Chion Tang "); 733 | MODULE_ALIAS("ipt_FULLCONENAT"); 734 | --------------------------------------------------------------------------------