├── .dockerignore ├── .drone.yml ├── .github └── workflows │ ├── build.yml │ └── testing.yml ├── .gitignore ├── .gitmodules ├── .travis.yml ├── Dockerfile ├── LICENSE ├── README.md ├── Vagrantfile ├── docker-entrypoint.sh ├── test.sh ├── test ├── ufw-docker-service.test.sh └── ufw-docker.test.sh └── ufw-docker /.dockerignore: -------------------------------------------------------------------------------- 1 | * 2 | !LICENSE 3 | !README.md 4 | !ufw-docker 5 | !docker-entrypoint.sh -------------------------------------------------------------------------------- /.drone.yml: -------------------------------------------------------------------------------- 1 | --- 2 | kind: pipeline 3 | type: docker 4 | name: default 5 | 6 | steps: 7 | - name: Fetch Submodules 8 | image: alpine/git 9 | commands: 10 | - git submodule update --init --recursive --depth=1 --remote 11 | 12 | - name: Testing 13 | image: ubuntu:bionic 14 | commands: 15 | - ./test.sh 16 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build Images 2 | 3 | on: 4 | push: 5 | 6 | jobs: 7 | docker: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Log into DockerHub 11 | if: github.event_name != 'pull_request' 12 | uses: docker/login-action@v3 13 | with: 14 | username: ${{ github.actor }} 15 | password: ${{ secrets.DOCKERHUB_TOKEN }} 16 | 17 | - name: Set up QEMU 18 | uses: docker/setup-qemu-action@v3 19 | 20 | - name: Set up Docker Buildx 21 | uses: docker/setup-buildx-action@v3 22 | 23 | - name: Docker meta 24 | id: meta 25 | uses: docker/metadata-action@v5 26 | with: 27 | images: ${{ github.actor }}/ufw-docker-agent 28 | 29 | - name: Build and push 30 | uses: docker/build-push-action@v6 31 | with: 32 | push: ${{ github.event_name != 'pull_request' }} 33 | platforms: linux/amd64,linux/arm64/v8 34 | tags: ${{ steps.meta.outputs.tags }} 35 | labels: ${{ steps.meta.outputs.labels }} 36 | -------------------------------------------------------------------------------- /.github/workflows/testing.yml: -------------------------------------------------------------------------------- 1 | name: Unit Testing ufw-docker 2 | on: [push, pull_request] 3 | jobs: 4 | test: 5 | name: Unit Testing 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v2 9 | - name: Checkout submodules 10 | shell: bash 11 | run: | 12 | auth_header="$(git config --local --get http.https://github.com/.extraheader)" 13 | git submodule sync --recursive 14 | git -c "http.extraheader=$auth_header" -c protocol.version=2 submodule update --init --force --recursive --depth=1 15 | - name: Test ufw-docker 16 | run: ./test.sh 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vagrant 2 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "test/bach"] 2 | path = test/bach 3 | url = https://github.com/bach-sh/bach.git 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: bash 2 | os: linux 3 | dist: trusty 4 | script: 5 | - bash test.sh 6 | notifications: 7 | slack: 8 | secure: pbbwN/dxrXXvQnJM5YhLt3A7t7ptvm5G3yQOimqBJVlLY7dJdPcUy6agntyLQ5cf+CHKVgMreu5m7qdTlSUeypNSi5+gbfNQD70l5TPG/ClqN/GnaNlrv4Y9ugL7kUWBqtMZSCwHHCy3Omv+oYjBixonJBfDMr0mn6ShkHRpgmjjUtByHhGy5gyNlKjoxB+04AnLkuIiz9mRUIkgGeeIcIkS8pE4E69Mh/K78h0oCZbQF1H4Eu22nOCdQhWH5StT0G+/pDqHGP4J8mDo3NVNMyySFRY0lSwUj2OUnX+VVK9RWUicaozCgob4Oi3Pf+5bNcxTdo2ntI/e0fEcpIqiSHOy/iLBrQMGmZY7aoVNG7IWQwM2Zt6wXORcYl6l2XMOVuFx+h9PQd+nol9Eh9JxGsQjrfdQ8rNK8DkdNat0axpex3w3PWpbFRtQJ3A21ixqINsKCZC0y5vO0LF0ttsJEf9QEJrYRlA8VOw79NnCE3PimACnb0UU2cy91HmLcR2OvXqNiS0TZWS0kEajpW9BuqszNPnMrpLi9t7kHTSFjGx1Nb6XXUBG2lmoiXVNqutq+0zCEa8otObjZ0igQ6Kb2joJfbwSSWXNzDtp+jRmxQacqmXwvByz2BI37xnCs4KP0VYM37r0BmVxpBQlyFreoB7PRyezYbQSkaq2bahMLjA= 9 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:24.04 2 | 3 | ARG docker_version="27.3.1" 4 | 5 | ENV DEBIAN_FRONTEND=noninteractive 6 | RUN apt-get update \ 7 | && apt-get install -y ca-certificates curl gnupg lsb-release \ 8 | && mkdir -p /etc/apt/keyrings \ 9 | && curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg \ 10 | && echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg]" \ 11 | "https://download.docker.com/linux/ubuntu" "$(lsb_release -cs) stable" \ 12 | | tee /etc/apt/sources.list.d/docker.list > /dev/null \ 13 | && apt-get update \ 14 | && apt-get install -y --no-install-recommends locales ufw \ 15 | && apt-get install -y --no-install-recommends "docker-ce=$(apt-cache madison docker-ce | grep -m1 -F "${docker_version}" | cut -d'|' -f2 | tr -d '[[:blank:]]')" \ 16 | && locale-gen en_US.UTF-8 \ 17 | && apt-get clean autoclean \ 18 | && apt-get autoremove --yes \ 19 | && rm -rf /var/lib/{apt,dpkg,cache,log}/ 20 | 21 | ADD ufw-docker docker-entrypoint.sh /usr/bin/ 22 | 23 | ENTRYPOINT ["/usr/bin/docker-entrypoint.sh"] 24 | 25 | CMD ["start"] 26 | 27 | ADD LICENSE README.md / 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | To Fix The Docker and UFW Security Flaw Without Disabling Iptables 2 | ================== 3 | 4 | [![Build Status](https://travis-ci.org/chaifeng/ufw-docker.svg)](https://travis-ci.org/chaifeng/ufw-docker) 5 | [![chaifeng/ufw-docker-agent](https://img.shields.io/docker/pulls/chaifeng/ufw-docker-agent)](https://hub.docker.com/r/chaifeng/ufw-docker-agent) 6 | 7 | - [English](#tldr) 8 | - [中文](#太长不想读) 9 | 10 | ## TL;DR 11 | 12 | Please take a look at [Solving UFW and Docker issues](#solving-ufw-and-docker-issues). 13 | 14 | ## Problem 15 | 16 | UFW is a popular iptables front end on Ubuntu that makes it easy to manage firewall rules. But when Docker is installed, Docker bypass the UFW rules and the published ports can be accessed from outside. 17 | 18 | The issue is: 19 | 20 | 1. UFW is enabled on a server that provides external services, and all incoming connections that are not allowed are blocked by default. 21 | 2. Run a Docker container on the server and use the `-p` option to publish ports for that container on all IP addresses. 22 | For example: `docker run -d --name httpd -p 0.0.0.0:8080:80 httpd:alpine`, this command will run an httpd service and publish port 80 of the container to port 8080 of the server. 23 | 3. UFW will not block all external requests to visit port 8080. Even the command `ufw deny 8080` will not prevent external access to this port. 24 | 4. This problem is actually quite serious, which means that a port that was originally intended to provide services internally is exposed to the public network. 25 | 26 | Searching for "ufw docker" on the web can find a lot of discussion: 27 | 28 | - https://github.com/moby/moby/issues/4737 29 | - https://forums.docker.com/t/running-multiple-docker-containers-with-ufw-and-iptables-false/8953 30 | - https://www.techrepublic.com/article/how-to-fix-the-docker-and-ufw-security-flaw/ 31 | - https://blog.viktorpetersson.com/2014/11/03/the-dangers-of-ufw-docker.html 32 | - https://askubuntu.com/questions/652556/uncomplicated-firewall-ufw-is-not-blocking-anything-when-using-docker 33 | - https://chjdev.com/2016/06/08/docker-ufw/ 34 | - https://askubuntu.com/questions/652556/uncomplicated-firewall-ufw-is-not-blocking-anything-when-using-docker 35 | - https://my.oschina.net/abcfy2/blog/539485 36 | - https://www.v2ex.com/amp/t/466666 37 | - https://blog.36web.rocks/2016/07/08/docker-behind-ufw.html 38 | - ... 39 | 40 | Almost all of these solutions are similar. It requires to disable docker's iptables function first, but this also means that we give up docker's network management function. This causes containers will not be able to access the external network. It is also mentioned in some articles that you can manually add some rules in the UFW configuration file, such as `-A POSTROUTING ! -o docker0 -s 172.17.0.0/16 -j MASQUERADE`. But this only allows containers that belong to network `172.17.0.0/16` can access outside. If we create a new docker network, we must manually add such similar iptables rules for the new network. 41 | 42 | ## Expected goal 43 | 44 | The solutions that we can find on internet are very similar and not elegant, I hope a new solution can: 45 | 46 | - Don't need to disable Docker's iptables and let Docker to manage it's network. 47 | We don't need to manually maintain iptables rules for any new Docker networks, and avoid potential side effects after disabling iptables in Docker. 48 | - The public network cannot access ports that published by Docker. Even if the port is published on all IP addresses using an option like `-p 8080:80`. Containers and internal networks can visit each other normally. 49 | Although it is possible to have Docker publish a container's port to the server's private IP address, the port will not be accessed on the public network. But, this server may have multiple private IP addresses, and these private IP addresses may also change. 50 | - In a very convenient way to allow/deny public networks to access container ports without additional software and extra configurations. Just like using command `ufw allow 8080` to allow external access port 8080, then using command `ufw delete allow 8080` to deny public networks visit port 8080. 51 | 52 | ## How to do? 53 | 54 | ### Revoke the original modification 55 | 56 | If you have modified your server according to the current solution that we find on the internet, please rollback these changes first, including: 57 | 58 | - Enable Docker's iptables feature. 59 | Remove all changes like `--iptables=false` , including configuration file `/etc/docker/daemon.json`. 60 | - UFW's default FORWARD rule changes back to the default DROP instead of ACCEPT. 61 | - Remove the rules related to the Docker network in the UFW configuration file `/etc/ufw/after.rules`. 62 | - If you have modified Docker configuration files, restart Docker first. We will modify the UFW configuration later and we can restart it then. 63 | 64 | ### Solving UFW and Docker issues 65 | 66 | This solution needs to modify only one UFW configuration file, all Docker configurations and options remain the default. 67 | 68 | Modify the UFW configuration file `/etc/ufw/after.rules` and add the following rules at the end of the file: 69 | 70 | # BEGIN UFW AND DOCKER 71 | *filter 72 | :ufw-user-forward - [0:0] 73 | :ufw-docker-logging-deny - [0:0] 74 | :DOCKER-USER - [0:0] 75 | -A DOCKER-USER -j ufw-user-forward 76 | 77 | -A DOCKER-USER -j RETURN -s 10.0.0.0/8 78 | -A DOCKER-USER -j RETURN -s 172.16.0.0/12 79 | -A DOCKER-USER -j RETURN -s 192.168.0.0/16 80 | 81 | -A DOCKER-USER -p udp -m udp --sport 53 --dport 1024:65535 -j RETURN 82 | 83 | -A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 192.168.0.0/16 84 | -A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 10.0.0.0/8 85 | -A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 172.16.0.0/12 86 | -A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 192.168.0.0/16 87 | -A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 10.0.0.0/8 88 | -A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 172.16.0.0/12 89 | 90 | -A DOCKER-USER -j RETURN 91 | 92 | -A ufw-docker-logging-deny -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW DOCKER BLOCK] " 93 | -A ufw-docker-logging-deny -j DROP 94 | 95 | COMMIT 96 | # END UFW AND DOCKER 97 | 98 | Using command `sudo systemctl restart ufw` or `sudo ufw reload` to restart UFW after changing the file. Now the public network can't access any published docker ports, the container and the private network can visit each other normally, and the containers can also access the external network from inside. **There may be some unknown reasons cause the UFW rules will not take effect after restart UFW, please reboot servers.** 99 | 100 | If you want to allow public networks to access the services provided by the Docker container, for example, the service port of a container is `80`. Run the following command to allow the public networks to access this service: 101 | 102 | ufw route allow proto tcp from any to any port 80 103 | 104 | This allows the public network to access all published ports whose container port is `80`. 105 | 106 | Note: If we publish a port by using option `-p 8080:80`, we should use the container port `80`, not the host port `8080`. 107 | 108 | If there are multiple containers with a service port of `80`, but we only want the external network to access a certain container. For example, if the private address of the container is `172.17.0.2`, use the following command: 109 | 110 | ufw route allow proto tcp from any to 172.17.0.2 port 80 111 | 112 | If the network protocol of a service is UDP, for example a DNS service, you can use the following command to allow the external network to access all published DNS services: 113 | 114 | ufw route allow proto udp from any to any port 53 115 | 116 | Similarly, if only for a specific container, such as IP address `172.17.0.2`: 117 | 118 | ufw route allow proto udp from any to 172.17.0.2 port 53 119 | 120 | ## How it works? 121 | 122 | The following rules allow the private networks to be able to visit each other. Normally, private networks are more trusted than public networks. 123 | 124 | -A DOCKER-USER -j RETURN -s 10.0.0.0/8 125 | -A DOCKER-USER -j RETURN -s 172.16.0.0/12 126 | -A DOCKER-USER -j RETURN -s 192.168.0.0/16 127 | 128 | The following rules allow UFW to manage whether the public networks are allowed to visit the services provided by the Docker container. So that we can manage all firewall rules in one place. 129 | 130 | -A DOCKER-USER -j ufw-user-forward 131 | 132 | For example, we want to block all outgoing connections from inside a container whose IP address is 172.17.0.9 which means to block this container to access internet or external networks. Using the following command: 133 | 134 | ufw route deny from 172.17.0.9 to any 135 | 136 | The following rules block connection requests initiated by all public networks, but allow internal networks to access external networks. For TCP protocol, it prevents from actively establishing a TCP connection from public networks. For UDP protocol, all accesses to ports which is less then 32767 are blocked. Why is this port? Since the UDP protocol is stateless, it is not possible to block the handshake signal that initiates the connection request as TCP does. For GNU/Linux we can find the local port range in the file `/proc/sys/net/ipv4/ip_local_port_range`. The default range is `32768 60999`. When accessing a UDP protocol service from a running container, the local port will be randomly selected one from the port range, and the server will return the data to this random port. Therefore, we can assume that the listening port of the UDP protocol inside all containers are less then `32768`. This is the reason that we don't want public networks to access the UDP ports that less then `32768`. 137 | 138 | -A DOCKER-USER -j DROP -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 192.168.0.0/16 139 | -A DOCKER-USER -j DROP -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 10.0.0.0/8 140 | -A DOCKER-USER -j DROP -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 172.16.0.0/12 141 | -A DOCKER-USER -j DROP -p udp -m udp --dport 0:32767 -d 192.168.0.0/16 142 | -A DOCKER-USER -j DROP -p udp -m udp --dport 0:32767 -d 10.0.0.0/8 143 | -A DOCKER-USER -j DROP -p udp -m udp --dport 0:32767 -d 172.16.0.0/12 144 | 145 | -A DOCKER-USER -j RETURN 146 | 147 | If a docker container doesn't follow the OS's settings when receiving data, that is to say, the minimal port number less than `32768`. For example, we have a Dnsmasq container. The minimal port number that Dnsmasq uses for receiving data is `1024`. We can use the following command to allow a bigger port range used for receiving DNS packages. 148 | 149 | ufw route allow proto udp from any port 53 to any port 1024:65535 150 | 151 | Because DNS is a very common service, so there is already a firewall rule to allow a bigger port range to receive DNS packages. 152 | 153 | ## The reason for choosing `ufw-user-forward`, not `ufw-user-input` 154 | 155 | ### using `ufw-user-input` 156 | 157 | Pro: 158 | 159 | Easy to use and understand, supports older versions of Ubuntu. 160 | 161 | For example, to allow the public to visit a published port whose container port is `8080`, use the command: 162 | 163 | ufw allow 8080 164 | 165 | Con: 166 | 167 | It not only exposes ports of containers but also exposes ports of the host. 168 | 169 | For example, if a service is running on the host, and the port is `8080`. The command `ufw allow 8080` allows the public network to visit the service and all published ports whose containers' port is `8080`. But we just want to expose the service running on the host, or just the service running inside containers, not the both. 170 | 171 | To avoid this problem, we may need to use a command similar to the following for all containers: 172 | 173 | ufw allow proto tcp from any to 172.16.0.3 port 8080 174 | 175 | ### using `ufw-user-forward` 176 | 177 | Pro: 178 | 179 | Cannot expose services running on hosts and containers at the same time by the same command. 180 | 181 | For example, if we want to publish the port `8080` of containers, use the following command: 182 | 183 | ufw route allow 8080 184 | 185 | The public network can access all published ports whose container ports are `8080`. 186 | 187 | But the port `8080` of the host is still not be accessed by the public network. If we want to do so, execute the following command to allow the public access the port on the host separately: 188 | 189 | ufw allow 8080 190 | 191 | 192 | Con: 193 | 194 | Doesn't support older versions of Ubuntu, and the command is a bit more complicated. But you can use my script. 195 | 196 | 197 | ### Conclusion 198 | 199 | If we are using an older version of Ubuntu, we can use `ufw-user-input` chain. But be careful to avoid exposing services that should not be exposed 200 | 201 | If we are using a newer version of Ubuntu which is support `ufw route` sub-command, we'd better use `ufw-user-forward` chain, and use `ufw route` command to manage firewall rules for containers. 202 | 203 | ## `ufw-docker` util 204 | 205 | This script also supports Docker Swarm mode. 206 | 207 | ### Install 208 | 209 | Download `ufw-docker` script 210 | 211 | sudo wget -O /usr/local/bin/ufw-docker \ 212 | https://github.com/chaifeng/ufw-docker/raw/master/ufw-docker 213 | sudo chmod +x /usr/local/bin/ufw-docker 214 | 215 | Then using the following command to modify the `after.rules` file of `ufw` 216 | 217 | ufw-docker install 218 | 219 | This command does the following things: 220 | - Back up the file `/etc/ufw/after.rules` 221 | - Append the rules of UFW and Docker at the end of the file 222 | 223 | #### Install for Docker Swarm mode 224 | 225 | We can only use this script on manager nodes to manage firewall rules when using in Swarm mode. 226 | 227 | - Modifying all `after.rules` files on all nodes, including managers and workers 228 | - Deploying this script on manager nodes 229 | 230 | Running in Docker Swarm mode, this script will add a global service `ufw-docker-agent`. The image [chaifeng/ufw-docker-agent](https://hub.docker.com/r/chaifeng/ufw-docker-agent/) is also automatically built from this project. 231 | 232 | ### Usage 233 | 234 | Show help 235 | 236 | ufw-docker help 237 | 238 | Check the installation of firewall rules in UFW configurations 239 | 240 | ufw-docker check 241 | 242 | Update UFW configurations, add the necessary firewall rules 243 | 244 | ufw-docker install 245 | 246 | Show the current firewall allowed forward rules 247 | 248 | ufw-docker status 249 | 250 | List all firewall rules related to container `httpd` 251 | 252 | ufw-docker list httpd 253 | 254 | Expose the port `80` of the container `httpd` 255 | 256 | ufw-docker allow httpd 80 257 | 258 | Expose the `443` port of the container `httpd` and the protocol is `tcp` 259 | 260 | ufw-docker allow httpd 443/tcp 261 | 262 | Expose the `443` port of the container `httpd` and the protocol is `tcp` and the network is `foobar-external-network` when the container `httpd` is attached to multiple networks 263 | 264 | ufw-docker allow httpd 443/tcp foobar-external-network 265 | 266 | Expose all published ports of the container `httpd` 267 | 268 | ufw-docker allow httpd 269 | 270 | Remove all rules related to the container `httpd` 271 | 272 | ufw-docker delete allow httpd 273 | 274 | Remove the rule which port is `443` and protocol is `tcp` for the container `httpd` 275 | 276 | ufw-docker delete allow httpd 443/tcp 277 | 278 | Expose the port `80` of the service `web` 279 | 280 | docker service create --name web --publish 8080:80 httpd:alpine 281 | 282 | ufw-docker service allow web 80 283 | # or 284 | ufw-docker service allow web 80/tcp 285 | 286 | Remove rules from all nodes related to the service `web` 287 | 288 | ufw-docker service delete allow web 289 | 290 | ### Try it out 291 | 292 | We use [Vagrant](https://www.vagrantup.com/) to set up a local testing environment. 293 | 294 | Run the following command to create 1 master node and 2 worker nodes 295 | 296 | vagrant up 297 | 298 | Log into the master node 299 | 300 | vagrant ssh master 301 | 302 | After logging in, create a `web` service 303 | 304 | docker service create --name web --publish 8080:80 httpd:alpine 305 | 306 | We shouldn't visit this `web` service from our host 307 | 308 | curl -v http://192.168.56.131:8080 309 | 310 | On the master node, run the command to allow the public access port `80` of the `web` service. 311 | 312 | sudo ufw-docker service allow web 80 313 | 314 | We can access the `web` service from our host now 315 | 316 | curl "http://192.168.56.13{0,1,2}:8080" 317 | 318 | ## Discussions 319 | 320 | - [What is the best practice of docker + ufw under Ubuntu - Stack Overflow](https://stackoverflow.com/questions/30383845/what-is-the-best-practice-of-docker-ufw-under-ubuntu/51741599#comment91451547_51741599) 321 | - [docker and ufw serious problems · Issue #4737 · moby/moby](https://github.com/moby/moby/issues/4737#issuecomment-420112149) 322 | 323 | 324 | ## 太长不想读 325 | 326 | 请直接看[解决 UFW 和 Docker 的问题](#解决-ufw-和-docker-的问题)。 327 | 328 | ## 问题 329 | 330 | UFW 是 Ubuntu 上很流行的一个 iptables 前端,可以非常方便的管理防火墙的规则。但是当安装了 Docker,UFW 无法管理 Docker 发布出来的端口了。 331 | 332 | 具体现象是: 333 | 334 | 1. 在一个对外提供服务的服务器上启用了 UFW,并且默认阻止所有未被允许的传入连接。 335 | 2. 运行了一个 Docker 容器,并且使用 `-p` 选项来把该容器的某个端口发布到服务器的所有 IP 地址上。比如:`docker run -d --name httpd -p 0.0.0.0:8080:80 httpd:alpine` 将会运行一个 httpd 服务,并且将容器的 `80` 端口发布到服务器的 `8080` 端口上。 336 | 3. UFW 将不会阻止所有对 `8080` 端口访问的请求,用命令 `ufw deny 8080` 也无法阻止外部访问这个端口。 337 | 338 | 这个问题其实挺严重的,这意味着本来只是为了在内部提供服务的一个端口被暴露在公共网络上。 339 | 340 | 在网络上搜索 "ufw docker" 可以发现很多的讨论: 341 | 342 | - https://github.com/moby/moby/issues/4737 343 | - https://forums.docker.com/t/running-multiple-docker-containers-with-ufw-and-iptables-false/8953 344 | - https://www.techrepublic.com/article/how-to-fix-the-docker-and-ufw-security-flaw/ 345 | - https://blog.viktorpetersson.com/2014/11/03/the-dangers-of-ufw-docker.html 346 | - https://askubuntu.com/questions/652556/uncomplicated-firewall-ufw-is-not-blocking-anything-when-using-docker 347 | - https://chjdev.com/2016/06/08/docker-ufw/ 348 | - https://askubuntu.com/questions/652556/uncomplicated-firewall-ufw-is-not-blocking-anything-when-using-docker 349 | - https://my.oschina.net/abcfy2/blog/539485 350 | - https://www.v2ex.com/amp/t/466666 351 | - https://blog.36web.rocks/2016/07/08/docker-behind-ufw.html 352 | - ... 353 | 354 | 基本上可以找到的解决办法就是首先禁用 docker 的 iptables 功能,但这也意味着放弃了 docker 的网络管理功能,很典型的现象就是容器将无法访问外部网络。在有的文章中也提到了可以在 UFW 的配置文件中手工添加一条规则,比如 `-A POSTROUTING ! -o docker0 -s 172.17.0.0/16 -j MASQUERADE`。但这也只是允许了 `172.17.0.0/16` 这个网络。如果有了新增的网络,我们也必须手工再为新增的网络添加这样类似的 iptables 规则。 355 | 356 | ## 期望的目标 357 | 358 | 目前网络上的解决方案都非常类似,而且也不优雅,我希望一个新的解决方案可以: 359 | 360 | 1. 不要禁用 Docker 的 iptables,像往常一样由 Docker 来管理自己的网络。这样有任何新增的 Docker 网络时都无需手工维护 iptables 规则,也避免了在 Docker 中禁用 iptables 之后可能带来的副作用。 361 | 2. 公共网络不可以访问 Docker 发布出来的端口,即使是使用类似 `-p 0.0.0.0:8080:80` 的选项把端口发布在所有的 IP 地址上。容器之间、内部网络之间都可以正常互相访问,只有公共网络不可以访问。 362 | 虽然可以让 Docker 把容器的某一个端口映射到服务器的私有 IP 地址上,这样公共网络上将不会访问到这个端口。但是这个服务器可能有多个私有 IP 地址,这些私有 IP 地址可能也会发生变化。 363 | 3. 可以很方便的允许公共网络直接访问某个容器的端口,而无需额外的软件和配置。就像是用 `ufw allow 8080` 这样允许外部访问 8080 端口,然后用 `ufw delete allow 8080` 就不再允许外部访问。 364 | 365 | ## 如何做? 366 | 367 | ### 撤销原先的修改 368 | 369 | 如果已经按照目前网络上搜索到解决方案修改过了,请先修改回来,包括: 370 | 371 | 1. 启用 Docker 的 iptables 功能,删除所有类似 `--iptables=false` 的修改,包括 `/etc/docker/daemon.json` 配置文件。 372 | 2. UFW 的默认 `FORWARD` 规则改回默认的 `DROP`,而非 `ACCEPT`。 373 | 3. 删除 UFW 配置文件 `/etc/ufw/after.rules` 中与 Docker 网络相关的规则。 374 | 4. 如果修改了 Docker 相关的配置文件,重启 Docker。稍后还要修改 UFW 的配置,可以一并重启。 375 | 376 | ### 解决 UFW 和 Docker 的问题 377 | 378 | 目前新的解决方案只需要修改一个 UFW 配置文件即可,Docker 的所有配置和选项都保持默认。 379 | 380 | 修改 UFW 的配置文件 `/etc/ufw/after.rules`,在最后添加上如下规则: 381 | 382 | # BEGIN UFW AND DOCKER 383 | *filter 384 | :ufw-user-forward - [0:0] 385 | :ufw-docker-logging-deny - [0:0] 386 | :DOCKER-USER - [0:0] 387 | -A DOCKER-USER -j ufw-user-forward 388 | 389 | -A DOCKER-USER -j RETURN -s 10.0.0.0/8 390 | -A DOCKER-USER -j RETURN -s 172.16.0.0/12 391 | -A DOCKER-USER -j RETURN -s 192.168.0.0/16 392 | 393 | -A DOCKER-USER -p udp -m udp --sport 53 --dport 1024:65535 -j RETURN 394 | 395 | -A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 192.168.0.0/16 396 | -A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 10.0.0.0/8 397 | -A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 172.16.0.0/12 398 | -A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 192.168.0.0/16 399 | -A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 10.0.0.0/8 400 | -A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 172.16.0.0/12 401 | 402 | -A DOCKER-USER -j RETURN 403 | 404 | -A ufw-docker-logging-deny -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW DOCKER BLOCK] " 405 | -A ufw-docker-logging-deny -j DROP 406 | 407 | COMMIT 408 | # END UFW AND DOCKER 409 | 410 | 然后重启 UFW,`sudo systemctl restart ufw`。现在外部就已经无法访问 Docker 发布出来的任何端口了,但是容器内部以及私有网络地址上可以正常互相访问,而且容器也可以正常访问外部的网络。**可能由于某些未知原因,重启 UFW 之后规则也无法生效,请重启服务器。** 411 | 412 | 如果希望允许外部网络访问 Docker 容器提供的服务,比如有一个容器的服务端口是 `80`。那就可以用以下命令来允许外部网络访问这个服务: 413 | 414 | ufw route allow proto tcp from any to any port 80 415 | 416 | 这个命令会允许外部网络访问所有用 Docker 发布出来的并且内部服务端口为 `80` 的所有服务。 417 | 418 | 请注意,这个端口 `80` 是容器的端口,而非使用 `-p 0.0.0.0:8080:80` 选项发布在服务器上的 `8080` 端口。 419 | 420 | 如果有多个容器的服务端口为 80,但只希望外部网络访问某个特定的容器。比如该容器的私有地址为 `172.17.0.2`,就用类似下面的命令: 421 | 422 | ufw route allow proto tcp from any to 172.17.0.2 port 80 423 | 424 | 如果一个容器的服务是 UDP 协议,假如是 DNS 服务,可以用下面的命令来允许外部网络访问所有发布出来的 DNS 服务: 425 | 426 | ufw route allow proto udp from any to any port 53 427 | 428 | 同样的,如果只针对一个特定的容器,比如 IP 地址为 `172.17.0.2`: 429 | 430 | ufw route allow proto udp from any to 172.17.0.2 port 53 431 | 432 | ### 解释 433 | 434 | 在新增的这段规则中,下面这段规则是为了让私有网络地址可以互相访问。通常情况下,私有网络是比公共网络更信任的。 435 | 436 | -A DOCKER-USER -j RETURN -s 10.0.0.0/8 437 | -A DOCKER-USER -j RETURN -s 172.16.0.0/12 438 | -A DOCKER-USER -j RETURN -s 192.168.0.0/16 439 | 440 | 下面的规则是为了可以用 UFW 来管理外部网络是否允许访问 Docker 容器提供的服务,这样我们就可以在一个地方来管理防火墙的规则了。 441 | 442 | -A DOCKER-USER -j ufw-user-forward 443 | 444 | 例如,我们要阻止一个 IP 地址为 172.17.0.9 的容器内的所有对外连接,也就是阻止该容器访问外部网络,使用下列命令 445 | 446 | ufw route deny from 172.17.0.9 to any 447 | 448 | 下面的规则阻止了所有外部网络发起的连接请求,但是允许内部网络访问外部网络。对于 TCP 协议,是阻止了从外部网络主动建立 TCP 连接。对于 UDP,是阻止了所有小余端口 `32767` 的访问。为什么是这个端口的?由于 UDP 协议是无状态的,无法像 TCP 那样阻止发起建立连接请求的握手信号。在 GNU/Linux 上查看文件 `/proc/sys/net/ipv4/ip_local_port_range` 可以看到发出 TCP/UDP 数据后,本地源端口的范围,默认为 `32768 60999`。当从一个运行的容器对外访问一个 UDP 协议的服务时,本地端口将会从这个端口范围里面随机选择一个,服务器将会把数据返回到这个随机端口上。所以,我们可以假定所有容器内部的 UDP 协议的监听端口都小余 `32768`,不允许外部网络主动连接小余 `32768` 的 UDP 端口。 449 | 450 | -A DOCKER-USER -j DROP -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 192.168.0.0/16 451 | -A DOCKER-USER -j DROP -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 10.0.0.0/8 452 | -A DOCKER-USER -j DROP -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 172.16.0.0/12 453 | -A DOCKER-USER -j DROP -p udp -m udp --dport 0:32767 -d 192.168.0.0/16 454 | -A DOCKER-USER -j DROP -p udp -m udp --dport 0:32767 -d 10.0.0.0/8 455 | -A DOCKER-USER -j DROP -p udp -m udp --dport 0:32767 -d 172.16.0.0/12 456 | 457 | -A DOCKER-USER -j RETURN 458 | 459 | 如果一个容器在接受数据的时候,端口号没有遵循操作系统的设定,也就是说最小端口号要小余 `32768`。比如运行了一个 Dnsmasq 的容器,Dnsmasq 用于接受数据的最小端口号默认是 `1024`。那可以用下面的命令来允许 Dnsmasq 这个容器使用一个更大的端口范围来接受数据。 460 | 461 | ufw route allow proto udp from any port 53 to any port 1024:65535 462 | 463 | 因为 DNS 是一个非常常见的服务,所以已经有一条规则用于允许使用一个更大的端口范围来接受 DNS 数据包 464 | 465 | ### 选择 `ufw-user-forward` 而不是 `ufw-user-input` 的原因 466 | 467 | #### 使用 `ufw-user-input` 468 | 469 | 优点: 470 | 471 | 使用的 UFW 命令比较简单,也比较容易理解,而且也支持老版本的 Ubuntu 472 | 473 | 比如,允许公众网络访问一个已经发布出来的容器端口 `8080`,使用命令: 474 | 475 | ufw allow 8080 476 | 477 | 缺点: 478 | 479 | 不仅仅是暴露了已经发布的容器端口,也暴露了主机上的端口。 480 | 481 | 比如,如果在主机上运行了一个端口为 `8080` 的服务。命令 `ufw allow 8080` 允许了公共网络访问这个服务,也允许了访问所有已经发布的容器端口为 `8080` 的服务。但是我们可能只是希望保留主机上的这个服务,或者是运行在容器里面的服务,而不是两个同时暴露。 482 | 483 | 为了避免这个问题,我们可能需要使用类似下面的命令来管理已经发布的容器端口: 484 | 485 | ufw allow proto tcp from any to 172.16.0.3 port 8080 486 | 487 | #### 使用 `ufw-user-forward` 488 | 489 | 优点: 490 | 491 | 不会因为同一条命令而同时暴露主机和容器里面的服务。 492 | 493 | 比如,如果我们希望暴露所有容器端口为 `8080` 的服务,使用下面的命令: 494 | 495 | ufw route allow 8080 496 | 497 | 现在公共网络可以访问所有容器端口为 `8080` 的已经发布的服务,但是运行在主机上的 `8080` 服务仍然不会被公开。如果我们希望公开主机上的 `8080` 端口,可以执行下面的命令: 498 | 499 | ufw allow 8080 500 | 501 | 缺点: 502 | 503 | 不支持老版本的 Ubuntu,而且命令的使用上可能也会比较复杂。 504 | 505 | #### 结论 506 | 507 | 如果我们正在使用老版本的 Ubuntu,我们可以使用 `ufw-user-input`。但是要小心避免把不该暴露的服务暴露出去。 508 | 509 | 如果正在使用支持 `ufw route` 命令的新版本的 Ubuntu,我们最好使用 `ufw-user-forward`,并且使用 `ufw route` 来管理与容器相关的防火墙规则。 510 | 511 | ## `ufw-docker` 工具 512 | 513 | 现在这个脚本也支持 Docker Swarm。 514 | 515 | ### 安装 516 | 517 | 下载 `ufw-docker` 脚本 518 | 519 | sudo wget -O /usr/local/bin/ufw-docker \ 520 | https://github.com/chaifeng/ufw-docker/raw/master/ufw-docker 521 | chmod +x /usr/local/bin/ufw-docker 522 | 523 | 使用下列命令来修改 ufw 的 `after.rules` 文件 524 | 525 | ufw-docker install 526 | 527 | 这个命令做了以下事情: 528 | - 备份文件 `/etc/ufw/after.rules` 529 | - 把 UFW 和 Docker 的相关规则添加到文件 `after.rules` 的末尾 530 | 531 | #### 为 Docker Swarm 环境安装 532 | 533 | 仅仅可以在管理节点上使用 `ufw-docker` 这个脚本来管理防火墙规则。 534 | 535 | - 在所有的节点上修改 `after.rules` 这个文件,包括管理节点和工作节点 536 | - 在管理节点上部署这个脚本 537 | 538 | 运行在 Docker Swarm 模式下,这个脚本将会创建一个全局服务 `ufw-docker-agent`。这个镜像 [chaifeng/ufw-docker-agent](https://hub.docker.com/r/chaifeng/ufw-docker-agent/) 是由本项目自动构建的。 539 | 540 | ### 使用方法 541 | 542 | 显示帮助 543 | 544 | ufw-docker help 545 | 546 | 检查 UFW 配置文件中防火墙规则的安装 547 | 548 | ufw-docker check 549 | 550 | 更新 UFW 的配置文件,添加必要的防火墙规则 551 | 552 | ufw-docker install 553 | 554 | 显示当前防火墙允许的转发规则 555 | 556 | ufw-docker status 557 | 558 | 列出所有和容器 `httpd` 相关的防火墙规则 559 | 560 | ufw-docker list httpd 561 | 562 | 暴露容器 `httpd` 的 `80` 端口 563 | 564 | ufw-docker allow httpd 80 565 | 566 | 暴露容器 `httpd` 的 `443` 端口,且协议为 `tcp` 567 | 568 | ufw-docker allow httpd 443/tcp 569 | 570 | 如果容器 `httpd` 绑定到多个网络上,暴露其 `443` 端口,协议为 `tcp`,网络为 `foobar-external-network` 571 | 572 | ufw-docker allow httpd 443/tcp foobar-external-network 573 | 574 | 把容器 `httpd` 的所有映射端口都暴露出来 575 | 576 | ufw-docker allow httpd 577 | 578 | 删除所有和容器 `httpd` 相关的防火墙规则 579 | 580 | ufw-docker delete allow httpd 581 | 582 | 删除容器 `httpd` 的 `tcp` 端口 `443` 的规则 583 | 584 | ufw-docker delete allow httpd 443/tcp 585 | 586 | 暴露服务 `web` 的 `80` 端口 587 | 588 | docker service create --name web --publish 8080:80 httpd:alpine 589 | 590 | ufw-docker service allow web 80 591 | # 或者 592 | ufw-docker service allow web 80/tcp 593 | 594 | 删除与服务 `web` 相关的规则 595 | 596 | ufw-docker service delete allow web 597 | 598 | ### 试试 599 | 600 | 我们使用 [Vagrant](https://www.vagrantup.com/) 来创建一个本地的测试环境。 601 | 602 | 运行下面的命令来创建 1 个 master 节点和 2 个 workder 节点 603 | 604 | vagrant up 605 | 606 | 登录到 master 节点 607 | 608 | vagrant ssh master 609 | 610 | 登录后,创建 `web` 服务 611 | 612 | docker service create --name web --publish 8080:80 httpd:alpine 613 | 614 | 我们应该无法从我们的主机上访问这个 `web` 服务 615 | 616 | curl -v http://192.168.56.131:8080 617 | 618 | 在 master 节点上,运行下面的命令来允许公共访问 `web` 服务端 `80` 端口。 619 | 620 | sudo ufw-docker service allow web 80 621 | 622 | 现在我们可以在我们的主机上访问这个 `web` 服务了 623 | 624 | curl "http://192.168.56.13{0,1,2}:8080" 625 | 626 | ## 讨论 627 | 628 | - [What is the best practice of docker + ufw under Ubuntu - Stack Overflow](https://stackoverflow.com/questions/30383845/what-is-the-best-practice-of-docker-ufw-under-ubuntu/51741599#comment91451547_51741599) 629 | - [docker and ufw serious problems · Issue #4737 · moby/moby](https://github.com/moby/moby/issues/4737#issuecomment-420112149) 630 | -------------------------------------------------------------------------------- /Vagrantfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # -*- mode: ruby -*- 4 | # vi: set ft=ruby : 5 | 6 | ENV['VAGRANT_NO_PARALLEL']="true" 7 | 8 | Vagrant.configure('2') do |config| 9 | ubuntu_version = File.readlines("Dockerfile").filter { |line| 10 | line.start_with?("FROM ") 11 | }.first.match(/\d\d\.\d\d/)[0] 12 | 13 | docker_version = File.readlines("Dockerfile").filter { |line| 14 | line.start_with?("ARG docker_version=") 15 | }.first.match(/"([\d\.]+)"/)[1] 16 | 17 | config.vm.box = "chaifeng/ubuntu-#{ubuntu_version}-docker-#{docker_version}" 18 | 19 | config.vm.provider 'virtualbox' do |vb| 20 | vb.memory = '1024' 21 | vb.default_nic_type = "virtio" 22 | end 23 | 24 | config.vm.provider 'parallels' do |prl| 25 | prl.memory = '1024' 26 | prl.check_guest_tools = false 27 | end 28 | 29 | ip_prefix="192.168.56" 30 | 31 | config.vm.provision 'docker-daemon-config', type: 'shell', inline: <<-SHELL 32 | set -eu 33 | if [[ ! -f /etc/docker/daemon.json ]]; then 34 | echo '{' >> /etc/docker/daemon.json 35 | echo ' "insecure-registries": ["localhost:5000", "#{ip_prefix}.130:5000"]' >> /etc/docker/daemon.json 36 | [[ -n "#{ENV['DOCKER_REGISTRY_MIRROR']}" ]] && 37 | echo ' , "registry-mirrors": ["#{ENV['DOCKER_REGISTRY_MIRROR']}"]' >> /etc/docker/daemon.json 38 | echo '}' >> /etc/docker/daemon.json 39 | if type systemctl &>/dev/null; then 40 | systemctl restart docker 41 | else 42 | service docker restart 43 | fi 44 | fi 45 | SHELL 46 | 47 | config.vm.provision 'ufw-docker', type: 'shell', inline: <<-SHELL 48 | set -euo pipefail 49 | export DEBUG=true 50 | lsb_release -is | grep -Fi ubuntu 51 | /vagrant/ufw-docker check || { 52 | ufw allow OpenSSH 53 | ufw allow from #{ip_prefix}.128/28 to any 54 | 55 | yes | ufw enable || true 56 | ufw status | grep '^Status: active' 57 | 58 | /vagrant/ufw-docker install 59 | 60 | sed -i -e 's,192\.168\.0\.0/16,#{ip_prefix}.128/28,' /etc/ufw/after.rules 61 | 62 | systemctl restart ufw 63 | 64 | [[ -L /usr/local/bin/ufw-docker ]] || ln -s /vagrant/ufw-docker /usr/local/bin/ 65 | 66 | iptables -I DOCKER-USER 4 -p udp -j LOG --log-prefix '[UFW DOCKER] ' 67 | } 68 | SHELL 69 | 70 | private_registry="#{ip_prefix}.130:5000" 71 | 72 | config.vm.define "master" do |master| 73 | master_ip_address = "#{ip_prefix}.130" 74 | master.vm.hostname = "master" 75 | master.vm.network "private_network", ip: "#{master_ip_address}" 76 | 77 | master.vm.provision "unit-testing", preserve_order: true, type: 'shell', inline: <<-SHELL 78 | set -euo pipefail 79 | /vagrant/test.sh 80 | SHELL 81 | 82 | master.vm.provision "docker-registry", preserve_order: true, type: 'docker' do |d| 83 | d.run "registry", 84 | image: "registry:2", 85 | args: "-p 5000:5000", 86 | restart: "always", 87 | daemonize: true 88 | end 89 | 90 | ufw_docker_agent_image = "#{private_registry}/chaifeng/ufw-docker-agent:test-legacy" 91 | 92 | master.vm.provision "docker-build-ufw-docker-agent", preserve_order: true, type: 'shell', inline: <<-SHELL 93 | set -euo pipefail 94 | suffix="$(iptables --version | grep -o '\\(nf_tables\\|legacy\\)')" 95 | docker build -t "#{ufw_docker_agent_image}-${suffix}" /vagrant 96 | docker push "#{ufw_docker_agent_image}-${suffix}" 97 | 98 | echo "export UFW_DOCKER_AGENT_IMAGE=#{ufw_docker_agent_image}-${suffix}" > /etc/profile.d/ufw-docker.sh 99 | echo "export DEBUG=true" >> /etc/profile.d/ufw-docker.sh 100 | 101 | echo "Defaults env_keep += UFW_DOCKER_AGENT_IMAGE" > /etc/sudoers.d/98_ufw-docker 102 | echo "Defaults env_keep += DEBUG" >> /etc/sudoers.d/98_ufw-docker 103 | SHELL 104 | 105 | master.vm.provision "swarm-init", preserve_order: true, type: 'shell', inline: <<-SHELL 106 | set -euo pipefail 107 | docker info | fgrep 'Swarm: active' && exit 0 108 | 109 | docker swarm init --advertise-addr "#{master_ip_address}" 110 | docker swarm join-token worker --quiet > /vagrant/.vagrant/docker-join-token 111 | SHELL 112 | 113 | master.vm.provision "build-webapp", preserve_order: true, type: 'shell', inline: <<-SHELL 114 | set -euo pipefail 115 | docker build -t #{private_registry}/chaifeng/hostname-webapp - <<\\DOCKERFILE 116 | FROM httpd:alpine 117 | 118 | RUN { echo '#!/bin/sh'; \\ 119 | echo 'set -e; (echo -n "${name:-Hi} "; hostname;) > /usr/local/apache2/htdocs/index.html'; \\ 120 | echo 'grep "^Listen 7000" || echo Listen 7000 >> /usr/local/apache2/conf/httpd.conf'; \\ 121 | echo 'grep "^Listen 8080" || echo Listen 8080 >> /usr/local/apache2/conf/httpd.conf'; \\ 122 | echo 'exec "$@"'; \\ 123 | } > /entrypoint.sh; chmod +x /entrypoint.sh 124 | 125 | ENTRYPOINT ["/entrypoint.sh"] 126 | CMD ["httpd-foreground"] 127 | DOCKERFILE 128 | docker push #{private_registry}/chaifeng/hostname-webapp 129 | SHELL 130 | 131 | master.vm.provision "local-webapp", preserve_order: true, type: 'shell', inline: <<-SHELL 132 | set -euo pipefail 133 | for name in public:18080 local:8000; do 134 | webapp="${name%:*}_webapp" 135 | port="${name#*:}" 136 | if docker inspect "$webapp" &>/dev/null; then docker rm -f "$webapp"; fi 137 | docker run -d --restart unless-stopped --name "$webapp" \ 138 | -p "$port:80" --env name="$webapp" #{private_registry}/chaifeng/hostname-webapp 139 | sleep 1 140 | done 141 | 142 | ufw-docker allow public_webapp 143 | SHELL 144 | 145 | master.vm.provision "multiple-network", preserve_order: true, type: 'shell', inline: <<-SHELL 146 | set -euo pipefail 147 | if ! docker network ls | grep -F foo-internal; then 148 | docker network create --internal foo-internal 149 | fi 150 | if ! docker network ls | grep -F bar-external; then 151 | docker network create bar-external 152 | fi 153 | 154 | for app in internal-multinet-app:7000 public-multinet-app:17070; do 155 | if ! docker inspect "${app%:*}" &>/dev/null; then 156 | docker run -d --restart unless-stopped --name "${app%:*}" \ 157 | -p "${app#*:}":80 --env name="${app}" \ 158 | --network foo-internal \ 159 | 192.168.56.130:5000/chaifeng/hostname-webapp 160 | docker network connect bar-external "${app%:*}" 161 | fi 162 | done 163 | 164 | ufw-docker allow public-multinet-app 80 bar-external 165 | ufw-docker allow internal-multinet-app 80 foo-internal 166 | SHELL 167 | 168 | master.vm.provision "swarm-webapp", preserve_order: true, type: 'shell', inline: <<-SHELL 169 | set -euo pipefail 170 | for name in public:29090 local:9000; do 171 | webapp="${name%:*}_service" 172 | port="${name#*:}" 173 | if docker service inspect "$webapp" &>/dev/null; then docker service rm "$webapp"; fi 174 | docker service create --name "$webapp" \ 175 | --publish "${port}:80" --env name="$webapp" --replicas 3 #{private_registry}/chaifeng/hostname-webapp 176 | done 177 | 178 | ufw-docker service allow public_service 80/tcp 179 | 180 | docker service inspect "public_multiport" || 181 | docker service create --name "public_multiport" \ 182 | --publish "40080:80" --publish "47000:7000" --publish "48080:8080" \ 183 | --env name="public_multiport" --replicas 3 #{private_registry}/chaifeng/hostname-webapp 184 | 185 | ufw-docker service allow public_multiport 80/tcp 186 | ufw-docker service allow public_multiport 8080/tcp 187 | SHELL 188 | end 189 | 190 | 1.upto 2 do |ip| 191 | config.vm.define "node#{ip}" do | node | 192 | node.vm.hostname = "node#{ip}" 193 | node.vm.network "private_network", ip: "#{ip_prefix}.#{ 130 + ip }" 194 | 195 | node.vm.provision "swarm-join", preserve_order: true, type: 'shell', inline: <<-SHELL 196 | set -euo pipefail 197 | docker info | fgrep 'Swarm: active' && exit 0 198 | 199 | [[ -f /vagrant/.vagrant/docker-join-token ]] && 200 | docker swarm join --token "$(&2 66 | exit 1 67 | fi 68 | esac 69 | } 70 | 71 | main "$@" 72 | -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -uo pipefail 3 | 4 | function out() { 5 | printf "\n\e[1;37;497;m%s\e[0;m\n" "$@" 6 | } >&2 7 | 8 | function err() { 9 | printf "\n\e[1;37;41;m%s\e[0;m\n\n" "$@" 10 | } >&2 11 | 12 | retval=0 13 | cd "$(dirname "${BASH_SOURCE}")" 14 | for file in test/*.test.sh; do 15 | out "Running $file" 16 | if grep -E "^[[:blank:]]*BACH_TESTS=.+" "$file"; then 17 | err "Found defination of BACH_TESTS in $file" 18 | retval=1 19 | fi 20 | bash "$file" || retval=1 21 | done 22 | 23 | if [[ "$retval" -ne 0 ]]; then 24 | err "Test failed!" 25 | fi 26 | 27 | exit "$retval" 28 | -------------------------------------------------------------------------------- /test/ufw-docker-service.test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | working_dir="$(cd "$(dirname "$BASH_SOURCE")"; pwd -P)" 5 | source "$working_dir"/bach/bach.sh 6 | 7 | @setup { 8 | set -euo pipefail 9 | 10 | ufw_docker_agent=ufw-docker-agent 11 | ufw_docker_agent_image=chaifeng/ufw-docker-agent:181005 12 | } 13 | 14 | @setup-test { 15 | @mocktrue ufw status 16 | @mocktrue grep -Fq "Status: active" 17 | 18 | @ignore remove_blank_lines 19 | @ignore echo 20 | @ignore err 21 | 22 | DEFAULT_PROTO=tcp 23 | GREP_REGEXP_INSTANCE_NAME="[-_.[:alnum:]]\\+" 24 | DEBUG=false 25 | } 26 | 27 | function die() { 28 | return 1 29 | } 30 | 31 | function load-ufw-docker-function() { 32 | set -euo pipefail 33 | 34 | @load_function "$working_dir/../ufw-docker" "$1" 35 | } 36 | 37 | 38 | test-ufw-docker--service-not-parameters() { 39 | load-ufw-docker-function ufw-docker--service 40 | 41 | ufw-docker--service 42 | } 43 | test-ufw-docker--service-not-parameters-assert() { 44 | ufw-docker--help 45 | } 46 | 47 | 48 | test-ufw-docker--service-allow() { 49 | load-ufw-docker-function ufw-docker--service 50 | 51 | ufw-docker--service allow 52 | } 53 | test-ufw-docker--service-allow-assert() { 54 | @do-nothing 55 | @fail 56 | } 57 | 58 | 59 | test-ufw-docker--service-allow-webapp() { 60 | load-ufw-docker-function ufw-docker--service 61 | 62 | ufw-docker--service allow webapp 63 | } 64 | test-ufw-docker--service-allow-webapp-assert() { 65 | #ufw-docker--service-allow webapp "" "" 66 | @do-nothing 67 | @fail 68 | } 69 | 70 | 71 | test-ufw-docker--service-allow-webapp-80tcp() { 72 | load-ufw-docker-function ufw-docker--service 73 | 74 | ufw-docker--service allow webapp 80/tcp 75 | } 76 | test-ufw-docker--service-allow-webapp-80tcp-assert() { 77 | ufw-docker--service-allow webapp 80/tcp 78 | } 79 | 80 | 81 | test-ufw-docker--service-delete-deny() { 82 | load-ufw-docker-function ufw-docker--service 83 | 84 | ufw-docker--service delete deny 85 | } 86 | test-ufw-docker--service-delete-deny-assert() { 87 | @do-nothing 88 | @fail 89 | } 90 | 91 | 92 | test-ufw-docker--service-delete-allow-no-service() { 93 | load-ufw-docker-function ufw-docker--service 94 | 95 | ufw-docker--service delete allow 96 | } 97 | test-ufw-docker--service-delete-allow-no-service-assert() { 98 | @do-nothing 99 | @fail 100 | } 101 | 102 | 103 | test-ufw-docker--service-delete-allow-webapp() { 104 | load-ufw-docker-function ufw-docker--service 105 | 106 | ufw-docker--service delete allow webapp 107 | } 108 | test-ufw-docker--service-delete-allow-webapp-assert() { 109 | ufw-docker--service-delete webapp 110 | } 111 | 112 | 113 | test-ufw-docker--get-service-id() { 114 | load-ufw-docker-function ufw-docker--get-service-id 115 | ufw-docker--get-service-id database 116 | } 117 | test-ufw-docker--get-service-id-assert() { 118 | docker service inspect database --format "{{.ID}}" 119 | } 120 | 121 | 122 | test-ufw-docker--get-service-name() { 123 | load-ufw-docker-function ufw-docker--get-service-name 124 | ufw-docker--get-service-name database 125 | } 126 | test-ufw-docker--get-service-name-assert() { 127 | docker service inspect database --format "{{.Spec.Name}}" 128 | } 129 | 130 | 131 | test-ufw-docker--service-allow-invalid-port-syntax() { 132 | @mockfalse grep -E '^[0-9]+(/(tcp|udp))?$' 133 | 134 | load-ufw-docker-function ufw-docker--service-allow 135 | ufw-docker--service-allow webapp invalid-port 136 | } 137 | test-ufw-docker--service-allow-invalid-port-syntax-assert() { 138 | @do-nothing 139 | @fail 140 | } 141 | 142 | 143 | test-ufw-docker--service-allow-an-non-existed-service() { 144 | @mocktrue grep -E '^[0-9]+(/(tcp|udp))?$' 145 | @mock ufw-docker--get-service-id web404 === @stdout "" 146 | 147 | load-ufw-docker-function ufw-docker--service-allow 148 | ufw-docker--service-allow web404 80/tcp 149 | } 150 | test-ufw-docker--service-allow-an-non-existed-service-assert() { 151 | @do-nothing 152 | @fail 153 | } 154 | 155 | 156 | test-ufw-docker--service-allow-a-service-without-ports-published() { 157 | @mocktrue grep -E '^[0-9]+(/(tcp|udp))?$' 158 | @mock ufw-docker--get-service-id private-web === @stdout abcd1234 159 | @mock ufw-docker--get-service-name private-web === @stdout private-web 160 | @mock docker service inspect private-web \ 161 | --format '{{range .Endpoint.Spec.Ports}}{{.PublishedPort}} {{.TargetPort}}/{{.Protocol}}{{"\n"}}{{end}}' === @stdout "" 162 | 163 | load-ufw-docker-function ufw-docker--service-allow 164 | ufw-docker--service-allow private-web 80/tcp 165 | } 166 | test-ufw-docker--service-allow-a-service-without-ports-published-assert() { 167 | @do-nothing 168 | @fail 169 | } 170 | 171 | 172 | test-ufw-docker--service-allow-a-service-while-agent-not-running() { 173 | @mocktrue grep -E '^[0-9]+(/(tcp|udp))?$' 174 | @mock ufw-docker--get-service-id webapp === @stdout abcd1234 175 | @mock ufw-docker--get-service-name webapp === @stdout webapp 176 | @mock docker service inspect webapp \ 177 | --format '{{range .Endpoint.Spec.Ports}}{{.PublishedPort}} {{.TargetPort}}/{{.Protocol}}{{"\n"}}{{end}}' \ 178 | === @stdout "53 53/udp" "80 80/tcp" "8080 8080/tcp" 179 | @mockfalse docker service inspect ufw-docker-agent 180 | 181 | load-ufw-docker-function ufw-docker--service-allow 182 | ufw-docker--service-allow webapp 80/tcp 183 | } 184 | test-ufw-docker--service-allow-a-service-while-agent-not-running-assert() { 185 | docker service create --name ufw-docker-agent --mode global \ 186 | --mount type=bind,source=/var/run/docker.sock,target=/var/run/docker.sock \ 187 | --mount type=bind,source=/etc/ufw,target=/etc/ufw,readonly=true \ 188 | --env ufw_docker_agent_image="chaifeng/ufw-docker-agent:181005" \ 189 | --env DEBUG="false" \ 190 | --env "ufw_public_abcd1234=webapp/80/tcp" \ 191 | "chaifeng/ufw-docker-agent:181005" 192 | } 193 | 194 | 195 | test-ufw-docker--service-allow-a-service-add-new-env() { 196 | @mocktrue grep -E '^[0-9]+(/(tcp|udp))?$' 197 | @mock ufw-docker--get-service-id webapp === @stdout abcd1234 198 | @mock ufw-docker--get-service-name webapp === @stdout webapp 199 | @mock docker service inspect webapp \ 200 | --format '{{range .Endpoint.Spec.Ports}}{{.PublishedPort}} {{.TargetPort}}/{{.Protocol}}{{"\n"}}{{end}}' \ 201 | === @stdout "53 53/udp" "80 80/tcp" "8080 8080/tcp" 202 | @mocktrue docker service inspect ufw-docker-agent 203 | @mock ufw-docker--get-env-list === @stdout "abcd1234 webapp/80/tcp" 204 | 205 | load-ufw-docker-function ufw-docker--service-allow 206 | ufw-docker--service-allow webapp 80/tcp 207 | } 208 | test-ufw-docker--service-allow-a-service-add-new-env-assert() { 209 | docker service update --update-parallelism=0 \ 210 | --env-add ufw_docker_agent_image="chaifeng/ufw-docker-agent:181005" \ 211 | --env-add DEBUG="false" \ 212 | --env-add "ufw_public_abcd1234=webapp/80/tcp" \ 213 | --image "chaifeng/ufw-docker-agent:181005" \ 214 | ufw-docker-agent 215 | } 216 | 217 | 218 | test-ufw-docker--service-allow-a-service-update-a-env() { 219 | @mocktrue grep -E '^[0-9]+(/(tcp|udp))?$' 220 | @mock ufw-docker--get-service-id webapp === @stdout abcd1234 221 | @mock ufw-docker--get-service-name webapp === @stdout webapp 222 | @mock docker service inspect webapp \ 223 | --format '{{range .Endpoint.Spec.Ports}}{{.PublishedPort}} {{.TargetPort}}/{{.Protocol}}{{"\n"}}{{end}}' \ 224 | === @stdout "53 53/udp" "80 80/tcp" "8080 8080/tcp" 225 | @mocktrue docker service inspect ufw-docker-agent 226 | @mock ufw-docker--get-env-list === @stdout "a_different_id webapp/80/tcp" 227 | 228 | load-ufw-docker-function ufw-docker--service-allow 229 | ufw-docker--service-allow webapp 80/tcp 230 | } 231 | test-ufw-docker--service-allow-a-service-update-a-env-assert() { 232 | docker service update --update-parallelism=0 \ 233 | --env-add ufw_docker_agent_image="chaifeng/ufw-docker-agent:181005" \ 234 | --env-add DEBUG="false" \ 235 | --env-add "ufw_public_abcd1234=webapp/80/tcp" \ 236 | --env-rm "ufw_public_a_different_id" \ 237 | --image "chaifeng/ufw-docker-agent:181005" \ 238 | ufw-docker-agent 239 | } 240 | 241 | 242 | test-ufw-docker--get-env-list() { 243 | @mock docker service inspect ufw-docker-agent \ 244 | --format '{{range $k,$v := .Spec.TaskTemplate.ContainerSpec.Env}}{{ $v }}{{"\n"}}{{end}}' \ 245 | === @stdout \ 246 | "ufw_docker_agent_image=192.168.56.130:5000/chaifeng/ufw-docker-agent:test" \ 247 | "DEBUG=true" \ 248 | "ufw_public_zv6esvmwnmmgnlauqn7m77jo4=webapp/9090/tcp" \ 249 | "OTHER_ENV=blabla" 250 | 251 | @mock sed -e '/^ufw_public_/!d' \ 252 | -e 's/^ufw_public_//' \ 253 | -e 's/=/ /' === @real sed -e '/^ufw_public_/!d' \ 254 | -e 's/^ufw_public_//' \ 255 | -e 's/=/ /' 256 | 257 | load-ufw-docker-function ufw-docker--get-env-list 258 | ufw-docker--get-env-list 259 | } 260 | test-ufw-docker--get-env-list-assert() { 261 | @stdout "zv6esvmwnmmgnlauqn7m77jo4 webapp/9090/tcp" 262 | } 263 | 264 | 265 | test-ufw-docker--service-delete-no-matches() { 266 | @mock ufw-docker--get-env-list === @stdout "ffff111 foo/80/tcp" "eeee2222 bar/53/udp" 267 | 268 | load-ufw-docker-function ufw-docker--service-delete 269 | ufw-docker--service-delete webapp 270 | } 271 | test-ufw-docker--service-delete-no-matches-assert() { 272 | @do-nothing 273 | @fail 274 | } 275 | 276 | 277 | test-ufw-docker--service-delete-matches() { 278 | @mock ufw-docker--get-env-list === @stdout "ffff111 foo/80/tcp" "eeee2222 bar/53/udp" "abcd1234 webapp/5000/tcp" 279 | 280 | load-ufw-docker-function ufw-docker--service-delete 281 | ufw-docker--service-delete webapp 282 | } 283 | test-ufw-docker--service-delete-matches-assert() { 284 | docker service update --update-parallelism=0 \ 285 | --env-add ufw_docker_agent_image="${ufw_docker_agent_image}" \ 286 | --env-add "ufw_public_abcd1234=webapp/deny" \ 287 | --image "${ufw_docker_agent_image}" \ 288 | "${ufw_docker_agent}" 289 | } 290 | -------------------------------------------------------------------------------- /test/ufw-docker.test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | working_dir="$(cd "$(dirname "$BASH_SOURCE")"; pwd -P)" 5 | source "$working_dir"/bach/bach.sh 6 | 7 | @setup { 8 | set -euo pipefail 9 | } 10 | 11 | @setup-test { 12 | @mocktrue ufw status 13 | @mocktrue grep -Fq "Status: active" 14 | 15 | @mock iptables --version 16 | @mocktrue grep -F '(legacy)' 17 | 18 | @mocktrue docker -v 19 | @mock docker -v === @stdout Docker version 0.0.0, build dummy 20 | 21 | @mockpipe remove_blank_lines 22 | @ignore echo 23 | @ignore err 24 | 25 | DEFAULT_PROTO=tcp 26 | GREP_REGEXP_INSTANCE_NAME="[-_.[:alnum:]]\\+" 27 | 28 | UFW_DOCKER_AGENT_IMAGE=chaifeng/ufw-docker-agent:090502-legacy 29 | } 30 | 31 | function ufw-docker() { 32 | @source <(@sed -n '/^# __main__$/,$p' "$working_dir/../ufw-docker") "$@" 33 | } 34 | 35 | function load-ufw-docker-function() { 36 | set -euo pipefail 37 | 38 | @load_function "$working_dir/../ufw-docker" "$1" 39 | } 40 | 41 | test-ufw-docker-init-legacy() { 42 | @mocktrue grep -F '(legacy)' 43 | @source <(@sed '/PATH=/d' "$working_dir/../ufw-docker") help 44 | } 45 | test-ufw-docker-init-legacy-assert() { 46 | iptables --version 47 | test -n chaifeng/ufw-docker-agent:090502-legacy 48 | trap on-exit EXIT INT TERM QUIT ABRT ERR 49 | @dryrun cat 50 | } 51 | 52 | 53 | test-ufw-docker-init-nf_tables() { 54 | @mockfalse grep -F '(legacy)' 55 | @source <(@sed '/PATH=/d' "$working_dir/../ufw-docker") help 56 | } 57 | test-ufw-docker-init-nf_tables-assert() { 58 | iptables --version 59 | test -n chaifeng/ufw-docker-agent:090502-nf_tables 60 | trap on-exit EXIT INT TERM QUIT ABRT ERR 61 | @dryrun cat 62 | } 63 | 64 | 65 | test-ufw-docker-init() { 66 | UFW_DOCKER_AGENT_IMAGE=chaifeng/ufw-docker-agent:100917 67 | @source <(@sed '/PATH=/d' "$working_dir/../ufw-docker") help 68 | } 69 | test-ufw-docker-init-assert() { 70 | test -n chaifeng/ufw-docker-agent:100917 71 | trap on-exit EXIT INT TERM QUIT ABRT ERR 72 | @dryrun cat 73 | } 74 | 75 | 76 | test-ufw-docker-help() { 77 | ufw-docker help 78 | } 79 | test-ufw-docker-help-assert() { 80 | ufw-docker--help 81 | } 82 | 83 | 84 | test-ufw-docker-without-parameters() { 85 | ufw-docker 86 | } 87 | test-ufw-docker-without-parameters-assert() { 88 | test-ufw-docker-help-assert 89 | } 90 | 91 | 92 | test-ufw-is-disabled() { 93 | @mockfalse grep -Fq "Status: active" 94 | @mock iptables --version === @stdout 'iptables v1.8.4 (legacy)' 95 | 96 | ufw-docker 97 | } 98 | test-ufw-is-disabled-assert() { 99 | die "UFW is disabled or you are not root user, or mismatched iptables legacy/nf_tables, current iptables v1.8.4 (legacy)" 100 | ufw-docker--help 101 | } 102 | 103 | 104 | test-docker-is-installed() { 105 | @mockfalse docker -v 106 | 107 | ufw-docker 108 | } 109 | test-docker-is-installed-assert() { 110 | die "Docker executable not found." 111 | ufw-docker--help 112 | } 113 | 114 | 115 | test-ufw-docker-status() { 116 | ufw-docker status 117 | } 118 | test-ufw-docker-status-assert() { 119 | ufw-docker--status 120 | } 121 | 122 | 123 | test-ufw-docker-install() { 124 | ufw-docker install 125 | } 126 | test-ufw-docker-install-assert() { 127 | ufw-docker--install 128 | } 129 | 130 | 131 | test-ufw-docker-check() { 132 | ufw-docker check 133 | } 134 | test-ufw-docker-check-assert() { 135 | ufw-docker--check 136 | } 137 | 138 | 139 | test-ufw-docker-service() { 140 | ufw-docker service allow httpd 141 | } 142 | test-ufw-docker-service-assert() { 143 | ufw-docker--service allow httpd 144 | } 145 | 146 | 147 | test-ufw-docker-raw-command() { 148 | ufw-docker raw-command status 149 | } 150 | test-ufw-docker-raw-command-assert() { 151 | ufw-docker--raw-command status 152 | } 153 | 154 | 155 | test-ufw-docker-add-service-rule() { 156 | ufw-docker add-service-rule httpd 80/tcp 157 | } 158 | test-ufw-docker-add-service-rule-assert() { 159 | ufw-docker--add-service-rule httpd 80/tcp 160 | } 161 | 162 | 163 | test-ASSERT-FAIL-ufw-docker-delete-must-have-parameters() { 164 | ufw-docker delete 165 | } 166 | 167 | 168 | test-ASSERT-FAIL-ufw-docker-list-must-have-parameters() { 169 | ufw-docker list 170 | } 171 | 172 | 173 | test-ASSERT-FAIL-ufw-docker-allow-must-have-parameters() { 174 | ufw-docker allow 175 | } 176 | 177 | 178 | test-ASSERT-FAIL-ufw-docker-delete-httpd-but-it-doesnt-exist() { 179 | @mockfalse ufw-docker--instance-name httpd 180 | ufw-docker delete httpd 181 | } 182 | 183 | 184 | test-ASSERT-FAIL-ufw-docker-list-httpd-but-it-doesnt-exist() { 185 | @mockfalse ufw-docker--instance-name httpd 186 | ufw-docker list httpd 187 | } 188 | 189 | 190 | test-ASSERT-FAIL-ufw-docker-allow-httpd-but-it-doesnt-exist() { 191 | @mockfalse ufw-docker--instance-name httpd 192 | ufw-docker allow httpd 193 | } 194 | 195 | 196 | test-ufw-docker-list-httpd() { 197 | @mock ufw-docker--instance-name httpd === @stdout httpd-container-name 198 | ufw-docker list httpd 199 | } 200 | test-ufw-docker-list-httpd-assert() { 201 | ufw-docker--list httpd-container-name "" tcp "" 202 | } 203 | 204 | 205 | test-ufw-docker-allow-httpd() { 206 | @mock ufw-docker--instance-name httpd === @stdout httpd-container-name 207 | ufw-docker allow httpd 208 | } 209 | test-ufw-docker-allow-httpd-assert() { 210 | ufw-docker--allow httpd-container-name "" tcp "" 211 | } 212 | 213 | 214 | test-ufw-docker-allow-httpd-80() { 215 | @mock ufw-docker--instance-name httpd === @stdout httpd-container-name 216 | ufw-docker allow httpd 80 217 | } 218 | test-ufw-docker-allow-httpd-80-assert() { 219 | ufw-docker--allow httpd-container-name 80 tcp "" 220 | } 221 | 222 | 223 | test-ufw-docker-allow-httpd-80tcp() { 224 | @mock ufw-docker--instance-name httpd === @stdout httpd-container-name 225 | ufw-docker allow httpd 80/tcp 226 | } 227 | test-ufw-docker-allow-httpd-80tcp-assert() { 228 | ufw-docker--allow httpd-container-name 80 tcp "" 229 | } 230 | 231 | 232 | test-ufw-docker-allow-httpd-80udp() { 233 | @mock ufw-docker--instance-name httpd === @stdout httpd-container-name 234 | ufw-docker allow httpd 80/udp 235 | } 236 | test-ufw-docker-allow-httpd-80udp-assert() { 237 | ufw-docker--allow httpd-container-name 80 udp "" 238 | } 239 | 240 | 241 | test-ASSERT-FAIL-ufw-docker-allow-httpd-INVALID-port() { 242 | @mock ufw-docker--instance-name httpd === @stdout httpd-container-name 243 | @mock die 'invalid port syntax: "invalid".' === exit 1 244 | 245 | ufw-docker allow httpd invalid 246 | } 247 | 248 | 249 | test-ufw-docker-list-httpd() { 250 | @mock ufw-docker--instance-name httpd === @stdout httpd-container-name 251 | ufw-docker list httpd 252 | } 253 | test-ufw-docker-list-httpd-assert() { 254 | ufw-docker--list httpd-container-name "" tcp "" 255 | } 256 | 257 | 258 | test-ufw-docker-delete-allow-httpd() { 259 | @mock ufw-docker--instance-name httpd === @stdout httpd-container-name 260 | ufw-docker delete allow httpd 261 | } 262 | test-ufw-docker-delete-allow-httpd-assert() { 263 | ufw-docker--delete httpd-container-name "" tcp "" 264 | } 265 | 266 | 267 | test-ASSERT-FAIL-ufw-docker-delete-only-supports-allowed-rules() { 268 | @mock ufw-docker--instance-name httpd === @stdout httpd-container-name 269 | ufw-docker delete non-allow 270 | } 271 | test-ASSERT-FAIL-ufw-docker-delete-only-supports-allowed-rules-assert() { 272 | die "\"delete\" command only support removing allowed rules" 273 | } 274 | 275 | 276 | function setup-ufw-docker--allow() { 277 | load-ufw-docker-function ufw-docker--allow 278 | 279 | @mocktrue docker inspect instance-name 280 | @mock docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{"\n"}}{{end}}' instance-name === @stdout 172.18.0.3 281 | @mock docker inspect --format='{{range $k, $v := .NetworkSettings.Networks}}{{printf "%s\n" $k}}{{end}}' instance-name === @stdout default 282 | @mock docker inspect --format='{{range $p, $conf := .NetworkSettings.Ports}}{{with $conf}}{{$p}}{{"\n"}}{{end}}{{end}}' instance-name === @stdout 5000/tcp 8080/tcp 5353/udp 283 | } 284 | 285 | function setup-ufw-docker--allow--multinetwork() { 286 | load-ufw-docker-function ufw-docker--allow 287 | 288 | @mocktrue docker inspect instance-name 289 | @mock docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{"\n"}}{{end}}' instance-name === @stdout 172.18.0.3 172.19.0.7 290 | @mock docker inspect --format='{{range $k, $v := .NetworkSettings.Networks}}{{printf "%s\n" $k}}{{end}}' instance-name === @stdout default awesomenet 291 | @mock docker inspect --format='{{range $p, $conf := .NetworkSettings.Ports}}{{with $conf}}{{$p}}{{"\n"}}{{end}}{{end}}' instance-name === @stdout 5000/tcp 8080/tcp 5353/udp 292 | } 293 | 294 | 295 | test-ufw-docker--allow-instance-not-found() { 296 | setup-ufw-docker--allow 297 | 298 | @mockfalse docker inspect invalid-instance 299 | @mockfalse die "Docker instance \"invalid-instance\" doesn't exist." 300 | 301 | ufw-docker--allow invalid-instance 80 tcp 302 | } 303 | test-ufw-docker--allow-instance-not-found-assert() { 304 | @do-nothing 305 | @fail 306 | } 307 | 308 | 309 | test-ufw-docker--allow-instance-but-the-port-not-match() { 310 | setup-ufw-docker--allow 311 | 312 | ufw-docker--allow instance-name 80 tcp 313 | } 314 | test-ufw-docker--allow-instance-but-the-port-not-match-assert() { 315 | @do-nothing 316 | @fail 317 | } 318 | 319 | 320 | test-ufw-docker--allow-instance-but-the-proto-not-match() { 321 | setup-ufw-docker--allow 322 | 323 | ufw-docker--allow instance-name 5353 tcp 324 | } 325 | test-ufw-docker--allow-instance-but-the-proto-not-match-assert() { 326 | @do-nothing 327 | @fail 328 | } 329 | 330 | 331 | test-ufw-docker--allow-instance-and-match-the-port() { 332 | setup-ufw-docker--allow 333 | 334 | ufw-docker--allow instance-name 5000 tcp 335 | } 336 | test-ufw-docker--allow-instance-and-match-the-port-assert() { 337 | ufw-docker--add-rule instance-name 172.18.0.3 5000 tcp default 338 | } 339 | 340 | 341 | test-ufw-docker--allow-instance-all-published-port() { 342 | setup-ufw-docker--allow 343 | 344 | ufw-docker--allow instance-name "" "" 345 | } 346 | test-ufw-docker--allow-instance-all-published-port-assert() { 347 | ufw-docker--add-rule instance-name 172.18.0.3 5000 tcp default 348 | ufw-docker--add-rule instance-name 172.18.0.3 8080 tcp default 349 | ufw-docker--add-rule instance-name 172.18.0.3 5353 udp default 350 | } 351 | 352 | 353 | test-ufw-docker--allow-instance-all-published-tcp-port() { 354 | setup-ufw-docker--allow 355 | 356 | ufw-docker--allow instance-name "" tcp 357 | } 358 | test-ufw-docker--allow-instance-all-published-tcp-port-assert() { 359 | ufw-docker--add-rule instance-name 172.18.0.3 5000 tcp default 360 | ufw-docker--add-rule instance-name 172.18.0.3 8080 tcp default 361 | ufw-docker--add-rule instance-name 172.18.0.3 5353 udp default # FIXME 362 | } 363 | 364 | 365 | test-ufw-docker--allow-instance-all-published-port-multinetwork() { 366 | setup-ufw-docker--allow--multinetwork 367 | 368 | ufw-docker--allow instance-name "" "" 369 | } 370 | test-ufw-docker--allow-instance-all-published-port-multinetwork-assert() { 371 | ufw-docker--add-rule instance-name 172.18.0.3 5000 tcp default 372 | ufw-docker--add-rule instance-name 172.19.0.7 5000 tcp awesomenet 373 | ufw-docker--add-rule instance-name 172.18.0.3 8080 tcp default 374 | ufw-docker--add-rule instance-name 172.19.0.7 8080 tcp awesomenet 375 | ufw-docker--add-rule instance-name 172.18.0.3 5353 udp default 376 | ufw-docker--add-rule instance-name 172.19.0.7 5353 udp awesomenet 377 | } 378 | 379 | test-ufw-docker--allow-instance-all-published-port-multinetwork-select-network() { 380 | setup-ufw-docker--allow--multinetwork 381 | 382 | ufw-docker--allow instance-name "" "" awesomenet 383 | } 384 | test-ufw-docker--allow-instance-all-published-port-multinetwork-select-network-assert() { 385 | ufw-docker--add-rule instance-name 172.19.0.7 5000 tcp awesomenet 386 | ufw-docker--add-rule instance-name 172.19.0.7 8080 tcp awesomenet 387 | ufw-docker--add-rule instance-name 172.19.0.7 5353 udp awesomenet 388 | } 389 | 390 | test-ufw-docker--add-rule-a-non-existing-rule() { 391 | @mockfalse ufw-docker--list webapp 5000 tcp "" 392 | 393 | load-ufw-docker-function ufw-docker--add-rule 394 | ufw-docker--add-rule webapp 172.18.0.4 5000 tcp 395 | } 396 | test-ufw-docker--add-rule-a-non-existing-rule-assert() { 397 | ufw route allow proto tcp from any to 172.18.0.4 port 5000 comment "allow webapp 5000/tcp" 398 | } 399 | 400 | test-ufw-docker--add-rule-a-non-existing-rule-with-network() { 401 | @mockfalse ufw-docker--list webapp 5000 tcp default 402 | 403 | load-ufw-docker-function ufw-docker--add-rule 404 | ufw-docker--add-rule webapp 172.18.0.4 5000 tcp default 405 | } 406 | test-ufw-docker--add-rule-a-non-existing-rule-with-network-assert() { 407 | ufw route allow proto tcp from any to 172.18.0.4 port 5000 comment "allow webapp 5000/tcp default" 408 | } 409 | 410 | 411 | test-ufw-docker--add-rule-modify-an-existing-rule() { 412 | @mocktrue ufw-docker--list webapp 5000 tcp default 413 | @mocktrue ufw --dry-run route allow proto tcp from any to 172.18.0.4 port 5000 comment "allow webapp 5000/tcp default" 414 | @mockfalse grep "^Skipping" 415 | 416 | load-ufw-docker-function ufw-docker--add-rule 417 | ufw-docker--add-rule webapp 172.18.0.4 5000 tcp default 418 | } 419 | test-ufw-docker--add-rule-modify-an-existing-rule-assert() { 420 | ufw-docker--delete webapp 5000 tcp default 421 | 422 | ufw route allow proto tcp from any to 172.18.0.4 port 5000 comment "allow webapp 5000/tcp default" 423 | } 424 | 425 | 426 | test-ufw-docker--add-rule-skip-an-existing-rule() { 427 | @mocktrue ufw-docker--list webapp 5000 tcp "" 428 | @mocktrue ufw --dry-run route allow proto tcp from any to 172.18.0.4 port 5000 comment "allow webapp 5000/tcp" 429 | @mocktrue grep "^Skipping" 430 | 431 | load-ufw-docker-function ufw-docker--add-rule 432 | ufw-docker--add-rule webapp 172.18.0.4 5000 tcp "" 433 | } 434 | test-ufw-docker--add-rule-skip-an-existing-rule-assert() { 435 | @do-nothing 436 | } 437 | 438 | 439 | test-ufw-docker--add-rule-modify-an-existing-rule-without-port() { 440 | @mocktrue ufw-docker--list webapp "" tcp "" 441 | 442 | @mocktrue ufw --dry-run route allow proto tcp from any to 172.18.0.4 comment "allow webapp" 443 | @mockfalse grep "^Skipping" 444 | 445 | load-ufw-docker-function ufw-docker--add-rule 446 | 447 | ufw-docker--add-rule webapp 172.18.0.4 "" tcp "" 448 | } 449 | test-ufw-docker--add-rule-modify-an-existing-rule-without-port-assert() { 450 | ufw-docker--delete webapp "" tcp "" 451 | 452 | ufw route allow proto tcp from any to 172.18.0.4 comment "allow webapp" 453 | } 454 | 455 | 456 | test-ufw-docker--instance-name-found-a-name() { 457 | @mock docker inspect --format="{{.Name}}" foo 458 | @mock sed -e 's,^/,,' 459 | @mockfalse grep "^$GREP_REGEXP_INSTANCE_NAME\$" 460 | 461 | @mock echo -n foo 462 | 463 | load-ufw-docker-function ufw-docker--instance-name 464 | ufw-docker--instance-name foo 465 | } 466 | test-ufw-docker--instance-name-found-a-name-assert() { 467 | docker inspect --format="{{.Name}}" foo 468 | @dryrun echo -n foo 469 | } 470 | 471 | 472 | test-ufw-docker--instance-name-found-an-id() { 473 | @mock docker inspect --format="{{.Name}}" fooid 474 | @mock sed -e 's,^/,,' 475 | @mockfalse grep "^$GREP_REGEXP_INSTANCE_NAME\$" 476 | 477 | load-ufw-docker-function ufw-docker--instance-name 478 | ufw-docker--instance-name fooid 479 | } 480 | test-ufw-docker--instance-name-found-an-id-assert() { 481 | docker inspect --format="{{.Name}}" fooid 482 | } 483 | 484 | 485 | test-ufw-docker--list-name() { 486 | @mocktrue ufw status numbered 487 | load-ufw-docker-function ufw-docker--list 488 | ufw-docker--list foo 489 | } 490 | test-ufw-docker--list-name-assert() { 491 | grep "# allow foo\\( [[:digit:]]\\+\\/\\(tcp\\|udp\\)\\)\\( [[:graph:]]*\\)\$" 492 | } 493 | 494 | test-ufw-docker--list-name-udp() { 495 | @mocktrue ufw status numbered 496 | load-ufw-docker-function ufw-docker--list 497 | ufw-docker--list foo "" udp 498 | } 499 | test-ufw-docker--list-name-udp-assert() { 500 | grep "# allow foo\\( [[:digit:]]\\+\\/\\(tcp\\|udp\\)\\)\\( [[:graph:]]*\\)\$" 501 | } 502 | 503 | 504 | test-ufw-docker--list-name-80() { 505 | @mocktrue ufw status numbered 506 | load-ufw-docker-function ufw-docker--list 507 | ufw-docker--list foo 80 508 | } 509 | test-ufw-docker--list-name-80-assert() { 510 | grep "# allow foo\\( 80\\/tcp\\)\\( [[:graph:]]*\\)\$" 511 | } 512 | 513 | 514 | test-ufw-docker--list-name-80-udp() { 515 | @mocktrue ufw status numbered 516 | load-ufw-docker-function ufw-docker--list 517 | ufw-docker--list foo 80 udp 518 | } 519 | test-ufw-docker--list-name-80-udp-assert() { 520 | grep "# allow foo\\( 80\\/udp\\)\\( [[:graph:]]*\\)\$" 521 | } 522 | 523 | 524 | test-ufw-docker--list-grep-without-network() { 525 | @mocktrue ufw status numbered 526 | @mockfalse grep "# allow foo\\( 80\\/udp\\)\\( [[:graph:]]*\\)\$" 527 | load-ufw-docker-function ufw-docker--list 528 | ufw-docker--list foo 80 udp 529 | } 530 | test-ufw-docker--list-grep-without-network-assert() { 531 | grep "# allow foo\\( 80\\/udp\\)\$" 532 | } 533 | 534 | 535 | test-ufw-docker--list-grep-without-network-and-port() { 536 | @mocktrue ufw status numbered 537 | @mockfalse grep "# allow foo\\( 80\\/udp\\)\\( [[:graph:]]*\\)\$" 538 | @mockfalse grep "# allow foo\\( 80\\/udp\\)\$" 539 | load-ufw-docker-function ufw-docker--list 540 | ufw-docker--list foo 80 udp 541 | } 542 | test-ufw-docker--list-grep-without-network-and-port-assert() { 543 | grep "# allow foo\$" 544 | } 545 | 546 | 547 | test-ufw-docker--list-number() { 548 | @mocktrue ufw-docker--list foo 53 udp 549 | 550 | load-ufw-docker-function ufw-docker--list-number 551 | ufw-docker--list-number foo 53 udp 552 | } 553 | test-ufw-docker--list-number-assert() { 554 | sed -e 's/^\[[[:blank:]]*\([[:digit:]]\+\)\].*/\1/' 555 | } 556 | 557 | 558 | test-ufw-docker--delete-empty-result() { 559 | @mock ufw-docker--list-number webapp 80 tcp === @stdout "" 560 | @mockpipe sort -rn 561 | 562 | load-ufw-docker-function ufw-docker--delete 563 | ufw-docker--delete webapp 80 tcp 564 | } 565 | test-ufw-docker--delete-empty-result-assert() { 566 | @do-nothing 567 | } 568 | 569 | 570 | test-ufw-docker--delete-all() { 571 | @mock ufw-docker--list-number webapp 80 tcp === @stdout 5 8 9 572 | @mockpipe sort -rn 573 | 574 | load-ufw-docker-function ufw-docker--delete 575 | ufw-docker--delete webapp 80 tcp 576 | } 577 | test-ufw-docker--delete-all-assert() { 578 | ufw delete 5 579 | ufw delete 8 580 | ufw delete 9 581 | } 582 | -------------------------------------------------------------------------------- /ufw-docker: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | [[ -n "${DEBUG:-}" ]] && set -x 4 | 5 | LANG=en_US.UTF-8 6 | LANGUAGE=en_US: 7 | LC_ALL=en_US.UTF-8 8 | PATH="/bin:/usr/bin:/sbin:/usr/sbin:/snap/bin/" 9 | 10 | GREP_REGEXP_INSTANCE_NAME="[-_.[:alnum:]]\\+" 11 | DEFAULT_PROTO=tcp 12 | 13 | ufw_docker_agent=ufw-docker-agent 14 | ufw_docker_agent_image="${UFW_DOCKER_AGENT_IMAGE:-chaifeng/${ufw_docker_agent}:221002-nf_tables}" 15 | 16 | if [[ "${ufw_docker_agent_image}" = *-@(legacy|nf_tables) ]]; then 17 | if iptables --version | grep -F '(legacy)' &>/dev/null; then 18 | ufw_docker_agent_image="${ufw_docker_agent_image%-*}-legacy" 19 | else 20 | ufw_docker_agent_image="${ufw_docker_agent_image%-*}-nf_tables" 21 | fi 22 | fi 23 | 24 | test -n "$ufw_docker_agent_image" 25 | 26 | function ufw-docker--status() { 27 | ufw-docker--list "$GREP_REGEXP_INSTANCE_NAME" 28 | } 29 | 30 | function ufw-docker--list() { 31 | local INSTANCE_NAME="$1" 32 | local INSTANCE_PORT="${2:-}" 33 | local PROTO="${3:-${DEFAULT_PROTO}}" 34 | local NETWORK="${4:-}" 35 | 36 | if [[ -z "$INSTANCE_PORT" ]]; then 37 | INSTANCE_PORT="[[:digit:]]\\+" 38 | PROTO="\\(tcp\\|udp\\)" 39 | fi 40 | 41 | if [[ -z "$NETWORK" ]]; then 42 | NETWORK="[[:graph:]]*" 43 | fi 44 | 45 | ufw status numbered | grep "# allow ${INSTANCE_NAME}\\( ${INSTANCE_PORT}\\/${PROTO}\\)\\( ${NETWORK}\\)\$" || \ 46 | ufw status numbered | grep "# allow ${INSTANCE_NAME}\\( ${INSTANCE_PORT}\\/${PROTO}\\)\$" || \ 47 | ufw status numbered | grep "# allow ${INSTANCE_NAME}\$" 48 | } 49 | 50 | function ufw-docker--list-number() { 51 | ufw-docker--list "$@" | sed -e 's/^\[[[:blank:]]*\([[:digit:]]\+\)\].*/\1/' 52 | } 53 | 54 | function ufw-docker--delete() { 55 | for UFW_NUMBER in $(ufw-docker--list-number "$@" | sort -rn); do 56 | echo "delete \"$UFW_NUMBER\"" 57 | echo y | ufw delete "$UFW_NUMBER" || true 58 | done 59 | } 60 | 61 | function ufw-docker--allow() { 62 | local INSTANCE_NAME="$1" 63 | local INSTANCE_PORT="$2" 64 | local PROTO="$3" 65 | local NETWORK="${4:-}" 66 | 67 | docker inspect "$INSTANCE_NAME" &>/dev/null || 68 | die "Docker instance \"$INSTANCE_NAME\" doesn't exist." 69 | 70 | mapfile -t INSTANCE_IP_ADDRESSES < <(docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{"\n"}}{{end}}' "$INSTANCE_NAME" 2>/dev/null | remove_blank_lines) 71 | 72 | [[ -z "${INSTANCE_IP_ADDRESSES:-}" ]] && die "Could not find a running instance \"$INSTANCE_NAME\"." 73 | 74 | mapfile -t INSTANCE_NETWORK_NAMES < <(docker inspect --format='{{range $k, $v := .NetworkSettings.Networks}}{{printf "%s\n" $k}}{{end}}' "$INSTANCE_NAME" 2>/dev/null | remove_blank_lines) 75 | mapfile -t PORT_PROTO_LIST < <(docker inspect --format='{{range $p, $conf := .NetworkSettings.Ports}}{{with $conf}}{{$p}}{{"\n"}}{{end}}{{end}}' "$INSTANCE_NAME" | remove_blank_lines) 76 | 77 | if [[ -z "${PORT_PROTO_LIST:-}" ]]; then 78 | err "\"$INSTANCE_NAME\" doesn't have any published ports." 79 | return 1 80 | fi 81 | 82 | RETVAL=1 83 | for PORT_PROTO in "${PORT_PROTO_LIST[@]}"; do 84 | if [[ -z "$INSTANCE_PORT" || "$PORT_PROTO" = "${INSTANCE_PORT}/${PROTO}" ]]; then 85 | ITER=0 86 | for IP in "${INSTANCE_IP_ADDRESSES[@]}"; do 87 | INSTANCE_NETWORK="${INSTANCE_NETWORK_NAMES[$ITER]}" 88 | ITER=$((ITER+1)) 89 | if [[ -n "$NETWORK" ]] && [[ "$NETWORK" != "$INSTANCE_NETWORK" ]]; then 90 | continue 91 | fi 92 | ufw-docker--add-rule "$INSTANCE_NAME" "$IP" "${PORT_PROTO%/*}" "${PORT_PROTO#*/}" "${INSTANCE_NETWORK}" 93 | RETVAL="$?" 94 | done 95 | fi 96 | done 97 | if [[ "$RETVAL" -ne 0 ]]; then 98 | err "Fail to add rule(s), cannot find the published port ${INSTANCE_PORT}/${PROTO} of instance \"${INSTANCE_NAME}\" or cannot update outdated rule(s)." 99 | fi 100 | return "$RETVAL" 101 | } 102 | 103 | function ufw-docker--add-service-rule() { 104 | declare service_id="$1" 105 | declare port="${2%/*}" 106 | declare proto="${2#*/}" 107 | 108 | declare target_ip_port 109 | target_ip_port="$(iptables -t nat -L DOCKER-INGRESS | grep -E "^DNAT\\s+${proto}\\s+.+\\sto:[.0-9]+:${port}\$" | grep -Eo "[.0-9]+:${port}\$")" 110 | 111 | [[ -z "$target_ip_port" ]] && die "Could not find VIP of service ${service_id}." 112 | 113 | ufw-docker--add-rule "$service_id" "${target_ip_port%:*}" "$port" "$proto" 114 | } 115 | 116 | function ufw-docker--add-rule() { 117 | local INSTANCE_NAME="$1" 118 | local INSTANCE_IP_ADDRESS="$2" 119 | local PORT="$3" 120 | local PROTO="$4" 121 | local NETWORK="${5:-}" 122 | 123 | declare comment 124 | 125 | echo "allow ${INSTANCE_NAME} ${PORT}/${PROTO} ${NETWORK}" 126 | typeset -a UFW_OPTS 127 | UFW_OPTS=(route allow proto "${PROTO}" 128 | from any to "$INSTANCE_IP_ADDRESS") 129 | comment="allow ${INSTANCE_NAME}" 130 | [[ -n "$PORT" ]] && { 131 | UFW_OPTS+=(port "${PORT}") 132 | comment="$comment ${PORT}/${PROTO}" 133 | } 134 | [[ -n "$NETWORK" ]] && { 135 | comment="$comment ${NETWORK}" 136 | } 137 | UFW_OPTS+=(comment "$comment") 138 | 139 | if ufw-docker--list "$INSTANCE_NAME" "$PORT" "$PROTO" "$NETWORK" &>/dev/null; then 140 | ufw --dry-run "${UFW_OPTS[@]}" | grep "^Skipping" && return 0 141 | err "Remove outdated rule." 142 | ufw-docker--delete "$INSTANCE_NAME" "$PORT" "$PROTO" "$NETWORK" 143 | fi 144 | echo ufw "${UFW_OPTS[@]}" 145 | ufw "${UFW_OPTS[@]}" 146 | } 147 | 148 | function ufw-docker--instance-name() { 149 | local INSTANCE_ID="$1" 150 | { 151 | { 152 | docker inspect --format='{{.Name}}' "$INSTANCE_ID" 2>/dev/null | sed -e 's,^/,,' | 153 | grep "^${GREP_REGEXP_INSTANCE_NAME}\$" 2>/dev/null 154 | } || echo -n "$INSTANCE_ID"; 155 | } | remove_blank_lines 156 | } 157 | 158 | function ufw-docker--service() { 159 | declare service_action="${1:-help}" 160 | case "$service_action" in 161 | delete) 162 | shift || true 163 | if [[ "${1:?Invalid 'delete' command syntax.}" != "allow" ]]; then 164 | die "\"delete\" command only support removing allowed rules" 165 | fi 166 | shift || true 167 | declare service_id_or_name="${1:?Missing swarm service name or service ID}" 168 | 169 | "ufw-docker--service-${service_action}" "${service_id_or_name}" 170 | ;; 171 | allow) 172 | shift || true 173 | declare service_id_or_name="${1:?Missing swarm service name or service ID}" 174 | declare service_port="${2:?Missing the port number, such as '80/tcp'.}" 175 | 176 | "ufw-docker--service-${service_action}" "${service_id_or_name}" "${service_port}" 177 | ;; 178 | *) 179 | ufw-docker--help 180 | ;; 181 | esac 182 | } 183 | 184 | function ufw-docker--get-service-id() { 185 | declare service_name="$1" 186 | docker service inspect "${service_name}" --format "{{.ID}}" 187 | } 188 | 189 | function ufw-docker--get-service-name() { 190 | declare service_name="$1" 191 | docker service inspect "${service_name}" --format "{{.Spec.Name}}" 192 | } 193 | 194 | function ufw-docker--service-allow() { 195 | declare service_name="$1" 196 | declare service_port="$2" 197 | declare service_proto=tcp 198 | 199 | if [[ -n "$service_port" ]] && 200 | ! grep -E '^[0-9]+(/(tcp|udp))?$' <<< "$service_port" &>/dev/null; then 201 | die "Invalid port syntax: $service_port" 202 | return 1 203 | fi 204 | 205 | if [[ "$service_port" = */* ]]; then 206 | service_proto="${service_port#*/}" 207 | service_port="${service_port%/*}" 208 | fi 209 | 210 | declare service_id 211 | service_id="$(ufw-docker--get-service-id "${service_name}")" 212 | [[ -z "${service_id:-}" ]] && die "Could not find service \"$service_name\"" 213 | 214 | service_name="$(ufw-docker--get-service-name "${service_name}")" 215 | 216 | exec 9< <(docker service inspect "$service_name" \ 217 | --format '{{range .Endpoint.Spec.Ports}}{{.PublishedPort}} {{.TargetPort}}/{{.Protocol}}{{"\n"}}{{end}}') 218 | while read -u 9 -r port target_port; do 219 | if [[ "$target_port" = "${service_port}/${service_proto}" ]]; then 220 | declare service_env="ufw_public_${service_id}=${service_name}/${port}/${service_proto}" 221 | break; 222 | fi 223 | done 224 | exec 9<&- 225 | 226 | [[ -z "${service_env:-}" ]] && die "Service $service_name does not publish port $service_port." 227 | 228 | if ! docker service inspect "$ufw_docker_agent" &>/dev/null; then 229 | err "Not found ufw-docker-agent service, creating ..." 230 | docker service create --name "$ufw_docker_agent" --mode global \ 231 | --mount type=bind,source=/var/run/docker.sock,target=/var/run/docker.sock \ 232 | --mount type=bind,source=/etc/ufw,target=/etc/ufw,readonly=true \ 233 | --env ufw_docker_agent_image="${ufw_docker_agent_image}" \ 234 | --env DEBUG="${DEBUG:-}" \ 235 | --env "${service_env}" \ 236 | "${ufw_docker_agent_image}" 237 | else 238 | declare -a service_env_list 239 | service_env_list+=(--env-add "${service_env}") 240 | 241 | exec 8< <(ufw-docker--get-env-list) 242 | while read -u 8 -r id value; do 243 | [[ "$id" = "$service_id" ]] && continue 244 | [[ "$value" = "${service_name}"/* ]] && service_env_list+=(--env-rm "ufw_public_${id}") 245 | done 246 | exec 8<&- 247 | 248 | docker service update --update-parallelism=0 \ 249 | --env-add ufw_docker_agent_image="${ufw_docker_agent_image}" \ 250 | --env-add DEBUG="${DEBUG:-}" \ 251 | "${service_env_list[@]}" \ 252 | --image "${ufw_docker_agent_image}" \ 253 | "${ufw_docker_agent}" 254 | fi 255 | } 256 | 257 | function ufw-docker--get-env-list() { 258 | docker service inspect "${ufw_docker_agent}" \ 259 | --format '{{range $k,$v := .Spec.TaskTemplate.ContainerSpec.Env}}{{ $v }}{{"\n"}}{{end}}' | 260 | sed -e '/^ufw_public_/!d' \ 261 | -e 's/^ufw_public_//' \ 262 | -e 's/=/ /' 263 | } 264 | 265 | function ufw-docker--service-delete() { 266 | declare service_name="$1" 267 | 268 | exec 8< <(ufw-docker--get-env-list) 269 | while read -u 8 -r id value; do 270 | if [[ "$id" = "$service_name" ]] || [[ "$value" = "${service_name}"/* ]]; then 271 | declare service_id="$id" 272 | service_name="${value%%/*}" 273 | declare service_env="ufw_public_${service_id}=${service_name}/deny" 274 | break; 275 | fi 276 | done 277 | exec 8<&- 278 | 279 | [[ -z "${service_env:-}" ]] && die "Could not find service \"$service_name\"" 280 | 281 | docker service update --update-parallelism=0 \ 282 | --env-add ufw_docker_agent_image="${ufw_docker_agent_image}" \ 283 | --env-add "${service_env}" \ 284 | --image "${ufw_docker_agent_image}" \ 285 | "${ufw_docker_agent}" 286 | } 287 | 288 | function ufw-docker--raw-command() { 289 | ufw "$@" 290 | } 291 | 292 | after_rules="/etc/ufw/after.rules" 293 | 294 | function ufw-docker--check() { 295 | err "\\n########## iptables -n -L DOCKER-USER ##########" 296 | iptables -n -L DOCKER-USER 297 | 298 | err "\\n\\n########## diff $after_rules ##########" 299 | ufw-docker--check-install && err "\\nCheck done." 300 | } 301 | 302 | declare -a files_to_be_deleted 303 | 304 | function rm-on-exit() { 305 | [[ $# -gt 0 ]] && files_to_be_deleted+=("$@") 306 | } 307 | 308 | function on-exit() { 309 | for file in "${files_to_be_deleted[@]:-}"; do 310 | [[ -f "$file" ]] && rm -r "$file" 311 | done 312 | files_to_be_deleted=() 313 | } 314 | 315 | trap on-exit EXIT INT TERM QUIT ABRT ERR 316 | 317 | function ufw-docker--check-install() { 318 | after_rules_tmp="${after_rules_tmp:-$(mktemp)}" 319 | rm-on-exit "$after_rules_tmp" 320 | 321 | sed "/^# BEGIN UFW AND DOCKER/,/^# END UFW AND DOCKER/d" "$after_rules" > "$after_rules_tmp" 322 | >> "${after_rules_tmp}" cat <<-\EOF 323 | # BEGIN UFW AND DOCKER 324 | *filter 325 | :ufw-user-forward - [0:0] 326 | :ufw-docker-logging-deny - [0:0] 327 | :DOCKER-USER - [0:0] 328 | -A DOCKER-USER -j ufw-user-forward 329 | 330 | -A DOCKER-USER -j RETURN -s 10.0.0.0/8 331 | -A DOCKER-USER -j RETURN -s 172.16.0.0/12 332 | -A DOCKER-USER -j RETURN -s 192.168.0.0/16 333 | 334 | -A DOCKER-USER -p udp -m udp --sport 53 --dport 1024:65535 -j RETURN 335 | 336 | -A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 192.168.0.0/16 337 | -A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 10.0.0.0/8 338 | -A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 172.16.0.0/12 339 | -A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 192.168.0.0/16 340 | -A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 10.0.0.0/8 341 | -A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 172.16.0.0/12 342 | 343 | -A DOCKER-USER -j RETURN 344 | 345 | -A ufw-docker-logging-deny -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW DOCKER BLOCK] " 346 | -A ufw-docker-logging-deny -j DROP 347 | 348 | COMMIT 349 | # END UFW AND DOCKER 350 | EOF 351 | 352 | diff -u --color=auto "$after_rules" "$after_rules_tmp" 353 | } 354 | 355 | function ufw-docker--install() { 356 | if ! ufw-docker--check-install; then 357 | local after_rules_bak 358 | after_rules_bak="${after_rules}-ufw-docker~$(date '+%Y-%m-%d-%H%M%S')~" 359 | err "\\nBacking up $after_rules to $after_rules_bak" 360 | cp "$after_rules" "$after_rules_bak" 361 | cat "$after_rules_tmp" > "$after_rules" 362 | err "Please restart UFW service manually by using the following command:" 363 | if type systemctl &>/dev/null; then 364 | err " sudo systemctl restart ufw" 365 | else 366 | err " sudo service ufw restart" 367 | fi 368 | fi 369 | } 370 | 371 | function ufw-docker--help() { 372 | cat <<-EOF >&2 373 | Usage: 374 | ufw-docker [docker-instance-id-or-name [port[/tcp|/udp]] [network]] 375 | ufw-docker delete allow [docker-instance-id-or-name [port[/tcp|/udp]] [network]] 376 | 377 | ufw-docker service allow >> 378 | ufw-docker service delete allow 379 | 380 | ufw-docker 381 | 382 | Examples: 383 | ufw-docker help 384 | 385 | ufw-docker check # Check the installation of firewall rules 386 | ufw-docker install # Install firewall rules 387 | 388 | ufw-docker status 389 | 390 | ufw-docker list httpd 391 | 392 | 393 | ufw-docker allow httpd 394 | ufw-docker allow httpd 80 395 | ufw-docker allow httpd 80/tcp 396 | ufw-docker allow httpd 80/tcp default 397 | 398 | ufw-docker delete allow httpd 399 | ufw-docker delete allow httpd 80/tcp 400 | ufw-docker delete allow httpd 80/tcp default 401 | 402 | ufw-docker service allow httpd 80/tcp 403 | 404 | ufw-docker service delete allow httpd 405 | EOF 406 | } 407 | 408 | function remove_blank_lines() { 409 | sed '/^[[:blank:]]*$/d' 410 | } 411 | 412 | function err() { 413 | echo -e "$@" >&2 414 | } 415 | 416 | function die() { 417 | err "ERROR:" "$@" 418 | exit 1 419 | } 420 | 421 | # __main__ 422 | 423 | if ! ufw status 2>/dev/null | grep -Fq "Status: active" ; then 424 | die "UFW is disabled or you are not root user, or mismatched iptables legacy/nf_tables, current $(iptables --version)" 425 | fi 426 | 427 | if ! docker -v &> /dev/null; then 428 | die "Docker executable not found." 429 | fi 430 | 431 | ufw_action="${1:-help}" 432 | 433 | case "$ufw_action" in 434 | delete) 435 | shift || true 436 | if [[ "${1:?Invalid 'delete' command syntax.}" != "allow" ]]; then 437 | die "\"delete\" command only support removing allowed rules" 438 | fi 439 | ;& 440 | list|allow) 441 | shift || true 442 | 443 | INSTANCE_ID="${1:?Docker instance name/ID cannot be empty.}" 444 | INSTANCE_NAME="$(ufw-docker--instance-name "$INSTANCE_ID")" 445 | shift || true 446 | 447 | INSTANCE_PORT="${1:-}" 448 | if [[ -n "$INSTANCE_PORT" && ! "$INSTANCE_PORT" =~ [0-9]+(/(tcp|udp))? ]]; then 449 | die "invalid port syntax: \"$INSTANCE_PORT\"." 450 | fi 451 | 452 | PROTO="$DEFAULT_PROTO" 453 | if [[ "$INSTANCE_PORT" = */udp ]]; then 454 | PROTO=udp 455 | fi 456 | shift || true 457 | 458 | NETWORK="${1:-}" 459 | 460 | INSTANCE_PORT="${INSTANCE_PORT%/*}" 461 | 462 | "ufw-docker--$ufw_action" "$INSTANCE_NAME" "$INSTANCE_PORT" "$PROTO" "$NETWORK" 463 | ;; 464 | service|raw-command|add-service-rule) 465 | shift || true 466 | "ufw-docker--$ufw_action" "$@" 467 | ;; 468 | status|install|check) 469 | ufw-docker--"$ufw_action" 470 | ;; 471 | *) 472 | ufw-docker--help 473 | ;; 474 | esac 475 | --------------------------------------------------------------------------------