├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE ├── LICENSE.GPL3 ├── README.md ├── dist ├── netifd │ └── wgconfd.sh └── systemd │ ├── wgconfd-state@.service │ └── wgconfd@.service ├── man ├── Makefile ├── wgconfd.5.scd └── wgconfd.8.scd └── src ├── config.rs ├── fileutil.rs ├── main.rs ├── manager ├── builder.rs ├── mod.rs └── updater.rs ├── model.rs ├── model └── ip.rs ├── proto.rs └── wg.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /Cargo.lock 2 | /target 3 | /man/*.[1-8] 4 | **/*.rs.bk 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | v0.3.0 2 | --- 3 | 4 | - Preshared keys are now always referred to by filename. The file must contain 5 | the base64 encoding of the key itself, followed by newline. 6 | 7 | - Sources are now given in `[[source]]` sections and the name is in a `name` 8 | attribute. Endpoints are taken from the first source that defines the peer. 9 | 10 | - Peer overrides can also set the endpoint and the keepalive timeout. 11 | 12 | - The OpenWRT procd init script has been replaced by a netifd protocol. 13 | 14 | v0.2.0 15 | --- 16 | 17 | - Peer overrides can be specified in the main configuration file. An override 18 | for a specific public key can contain a preshared key and can restrict the 19 | source that can define the peer. 20 | 21 | - The systemd service has been split in two. Restarting `wgconfd-state@.service` 22 | also wipes the state. This service should be marked as `PartOf=` the service 23 | that manages the interface. `wgconfd@.service` itself is 24 | `PartOf=wgconfd-state@.service`. 25 | 26 | 27 | v0.1.2 28 | --- 29 | 30 | - The interface is now stored under `$RUNTIME_DIRECTORY` if it is set. The 31 | state file should be removed when the interfaces is reset. 32 | 33 | - The daemon's config can now be provided via the command line. TOML config 34 | support has been made optional and is enabled by default. 35 | 36 | - There is now an init script for OpenWRT procd that gets the configuration 37 | from UCI and passes it via command line. 38 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: CC0-1.0 2 | # 3 | # Copyright 2019 Hristo Venev 4 | 5 | [package] 6 | name = "wgconfd" 7 | version = "0.3.2" 8 | edition = "2018" 9 | authors = [ "Hristo Venev " ] 10 | license = "LGPL-3.0-or-later" 11 | description = "A configuration manager for WireGuard" 12 | repository = "https://git.venev.name/hristo/wgconfd" 13 | readme = "README.md" 14 | categories = [ "config" ] 15 | keywords = [ "wireguard" ] 16 | 17 | [dependencies] 18 | arrayref = { version = "0.3.6" } 19 | base64 = { version = "0.12.0" } 20 | serde = { version = "1.0" } 21 | serde_derive = { version = "1.0" } 22 | serde_json = { version = "1.0" } 23 | chrono = { version = "0.4.10", default-features = false, features = ["std"] } 24 | toml = { version = "0.5.6", optional = true } 25 | rand = { version = "0.7.3", default-features = false, features = ["std"] } 26 | 27 | [features] 28 | default = [ "toml" ] 29 | 30 | [profile.release] 31 | panic = "abort" 32 | lto = true 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER 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 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /LICENSE.GPL3: -------------------------------------------------------------------------------- 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 | wgconfd 2 | === 3 | 4 | wgconfd is a configuration manager for [WireGuard](https://wireguard.com/). 5 | 6 | Overview 7 | --- 8 | `wgconfd INTERFACE CONFIG` starts a process that manages some peers of a WireGuard interface. It adds/overwrites peers it knows about and removes peers once they disappear from its view. It leaves any peers it has never seen intact. 9 | 10 | Peers are defined in sources. A source is a JSON file served over a protocol that `curl` understands. 11 | 12 | A "server" peer has a known IP address and talks to other servers directly. A "road warrior" peer communicates with everyone through its base server. 13 | 14 | Configuration 15 | --- 16 | 17 | The main configuration file is written in [toml](https://github.com/toml-lang/toml). 18 | 19 | ```toml 20 | refresh_sec = 1200 # default 21 | min_keepalive = 10 # default 22 | max_keepalive = 0 # default, means "never" 23 | 24 | [[source]] 25 | name = "remote1" 26 | url = "https://wg.example.org/peers.json" 27 | ipv4 = [ "172.16.0.0/12", "192.168.5.0/24" ] 28 | ipv6 = [ "2001:db8::/32" ] 29 | 30 | [[source]] 31 | name = "remote2" 32 | url = "https://wg.example.com/peers.json" 33 | ipv4 = [ "172.16.0.0/12", "192.168.6.0/24" ] 34 | ipv6 = [ "2001:db8:1234:/48" ] 35 | psk = "/path/to/psk/file" 36 | allow_road_warriors = false 37 | 38 | [[source]] 39 | name = "local-user1" 40 | url = "file:///etc/wireguard/example/user1.json" 41 | ipv4 = [ "172.16.5.54/32" ] 42 | 43 | [[source]] 44 | name = "local-user2" 45 | url = "file:///etc/wireguard/example/user2.json" 46 | ipv6 = [ "2001:db8::5/128" ] 47 | ``` 48 | 49 | All IP address ranges from the source URL not entirely contained within the ones configured are discarded - if a source claims `0.0.0.0/0` but the config only allows `10.0.0.0/8`, nothing is allowed. 50 | 51 | The preshared key is applied to all peers defined in a source. If a single peer is defined in multiple sources, both the endpoint and preshared key are taken from the first source that defines it. 52 | 53 | It is possible to override some options for a specific public key, and/or to restrict the source that can define that peer: 54 | 55 | ```toml 56 | [peer."yIOdSFrFQ1WPYS6IUWCsRjzw2Iqq0HMcyVVEXu5z+nM="] 57 | source = "remote2" 58 | endpoint = "[2001:db8::6]:10656" 59 | psk = "/path/to/psk/file" 60 | keepalive = 20 61 | ``` 62 | 63 | ### Alternative configuration 64 | 65 | There is an alternative configuration mechanism intended for integration with other software: `wgconfd --cmdline INTERFACE ARGS...` 66 | 67 | The arguments are a sequence of global options and sources: 68 | 69 | - `min_keepalive SEC` 70 | - `max_keepalive SEC` 71 | - `refresh_sec SEC` 72 | - `source NAME URL [psk PATH] [ipv4 NET,NET,...] [ipv6 NET,NET,...] [required] [allow_road_warriors | deny_road_warriors]` 73 | - `peer PUBKEY [endpoint IP:PORT] [psk PATH] [keepalive SEC] [source NAME]` 74 | 75 | Source format 76 | --- 77 | 78 | The source describes a list of peers with their associated `endpoint` address (required), `keepalive` (optional, defaults to never), and `ipv4` and `ipv6` ranges (optional, defaults to nothing): 79 | 80 | ```json 81 | { 82 | "servers": [{ 83 | "public_key": "hw0U7vI2rhjG9mQ34CUKO6M4dIF9e8ofKj5N6cAPtwY=", 84 | "endpoint": "198.51.100.66:656", 85 | "ipv4": [ "10.1.2.0/24" ] 86 | }, { 87 | "public_key": "nlFVtJrOwR2sVJji6NQjXnv//GVUK5W9T7ftkSnYPA8=", 88 | "endpoint": "[2002:cb00:71af::4]:656", 89 | "ipv4": [ "10.1.3.0/24" ] 90 | }], 91 | } 92 | ``` 93 | 94 | ### Road warriors 95 | wgconfd also supports roaming peers called "road warriors": 96 | 97 | ```json 98 | { 99 | ... 100 | "road_warriors": [{ 101 | "public_key": "YJ0Ye/Z/f+kzMu5au8JL/OP+cMs0eRsJPSQ9FZIa7Sk=", 102 | "base": "hw0U7vI2rhjG9mQ34CUKO6M4dIF9e8ofKj5N6cAPtwY=", 103 | "ipv4": [ "10.2.5.44/32" ] 104 | }, ...] 105 | } 106 | ``` 107 | 108 | A road warrior does not typically run wgconfd. It is instead expected to only talk to its base server peer. 109 | 110 | On the base peer, a WireGuard peer is created for the road warrior. On all other peers the allowed IP address ranges of the road warrior are added to its base instead. 111 | 112 | A road warrior from one source can use a server from another source, but allowed IPs are always checked against the source that contains the road warrior definition. 113 | 114 | The `allow_road_warriors` option in `[[source]]` sections can be used to deny being the base of road warriors from certain sources. 115 | 116 | ### Configuration updates 117 | The root object can contain a field `"next"` with an `"update_at"` timestamp and another configuration: 118 | 119 | ```json 120 | { 121 | "servers": [{ 122 | "public_key": "hw0U7vI2rhjG9mQ34CUKO6M4dIF9e8ofKj5N6cAPtwY=", 123 | "endpoint": "198.51.100.66:656", 124 | "ipv4": [ "10.1.2.0/24" ] 125 | }, { 126 | "public_key": "nlFVtJrOwR2sVJji6NQjXnv//GVUK5W9T7ftkSnYPA8=", 127 | "endpoint": "[2002:cb00:71af::4]:656", 128 | "ipv4": [ "10.1.3.0/24" ] 129 | }], 130 | "road_warriors": [{ 131 | "public_key": "YJ0Ye/Z/f+kzMu5au8JL/OP+cMs0eRsJPSQ9FZIa7Sk=", 132 | "base": "hw0U7vI2rhjG9mQ34CUKO6M4dIF9e8ofKj5N6cAPtwY=", 133 | "ipv4": [ "10.2.5.44/32" ] 134 | }], 135 | "next": { 136 | "update_at": "2033-05-18T03:33:20Z", 137 | "servers": [{ 138 | "public_key": "hw0U7vI2rhjG9mQ34CUKO6M4dIF9e8ofKj5N6cAPtwY=", 139 | "endpoint": "198.51.100.66:656", 140 | "ipv4": [ "10.1.2.0/24" ] 141 | }, { 142 | "public_key": "nlFVtJrOwR2sVJji6NQjXnv//GVUK5W9T7ftkSnYPA8=", 143 | "endpoint": "[2002:cb00:71af::4]:656", 144 | "ipv4": [ "10.1.3.0/25" ] 145 | }, { 146 | "public_key": "JjSETJ9ACv0sTTEtBE2qp9q4vbeq1i5suwWaJCuncFo=", 147 | "endpoint": "[2001:db8:ddcc:bbaa::5]:565", 148 | "ipv4": [ "10.1.3.128/25" ] 149 | }], 150 | "road_warriors": [{ 151 | "public_key": "YJ0Ye/Z/f+kzMu5au8JL/OP+cMs0eRsJPSQ9FZIa7Sk=", 152 | "base": "nlFVtJrOwR2sVJji6NQjXnv//GVUK5W9T7ftkSnYPA8=", 153 | "ipv4": [ "10.2.5.44/32" ] 154 | }] 155 | } 156 | } 157 | ``` 158 | 159 | All instances of `wgconfd` using that source will switch to the new configuration at the specified time according to their system clocks. Note that the regular mechanism for updates still applies - to cancel an update, remove the `"next"` field early enough so that all machines refresh the source before `"update_at"`. 160 | 161 | Operating system support 162 | --- 163 | 164 | wgconfd should work on all operating systems that provide the `wg` and `curl` commands. 165 | 166 | ### systemd-based Linux distributions 167 | 168 | Sample unit files are provided in the `dist/systemd` directory: 169 | 170 | - `wgconfd@IFNAME.service` runs wgconfd on the network interface `IFNAME` using configuration in `/etc/wireguard/IFNAME.toml`. The service expects that the interface has already been created and the prviate key has been set. 171 | - `wgconfd-state@IFNAME.service` should be restarted every time the network interface loses its configuration, for example when wg-quick is restarted. 172 | 173 | A Fedora source package is available at [https://git.venev.name/hristo/fedora/rust-wgconfd/]. 174 | 175 | ### OpenWRT 176 | 177 | There is an OpenWRT netifd protocol script in `dist/netifd`. The global options are set in the interface section in `/etc/config/network`. Sources and peers are defined in `wgconfd_source_IFNAME`/`wgconfd_peer_IFNAME` sections in the same file: 178 | 179 | ```sh 180 | config interface 'wg0' 181 | option proto 'wgconfd' 182 | option listen_port '656' 183 | option private_key 'uAoL9qoAFbAPg46NxIQJ36Zc5gJaYDBleL2iGEa8SEA=' 184 | list ip6addr '2002:db8:1:1/48' 185 | list ipaddr '10.4.0.1/10' 186 | 187 | config wgconfd_source_wg0 188 | option name 'source1' 189 | option url 'https://wg.example.org/peers.json' 190 | list ipv4 '10.5.0.0/16' 191 | list ip6addr '2002:db8:2:3/48' 192 | 193 | config wgconfd_source_wg0 194 | option name 'source2' 195 | option url 'https://wg.example.com/peers.json' 196 | list ipv4 '10.6.0.0/16' 197 | 198 | config wgconfd_peer_wg0 199 | option public_key 'dJyitquxsM3gf8a8yVDko6Se0sKrXi+glUTQN4mPZCo=' 200 | option source 'source2' 201 | option psk '/etc/wgconfd-psk/example.com-machine1' 202 | ``` 203 | -------------------------------------------------------------------------------- /dist/netifd/wgconfd.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | WG=/usr/bin/wg 4 | if [ ! -x "$WG" ]; then 5 | logger -t "wgconfd" "error: missing wgconfd (${WG})" 6 | exit 1 7 | fi 8 | 9 | CURL=/usr/bin/curl 10 | if [ ! -x "$CURL" ]; then 11 | logger -t "wgconfd" "error: missing curl (${CURL})" 12 | exit 1 13 | fi 14 | 15 | WGCONFD=/usr/bin/wgconfd 16 | if [ ! -x "$WGCONFD" ]; then 17 | logger -t "wgconfd" "error: missing wgconfd (${WGCONFD})" 18 | exit 1 19 | fi 20 | 21 | [ -n "$INCLUDE_ONLY" ] || { 22 | . /lib/functions.sh 23 | . ../netifd-proto.sh 24 | init_proto "$@" 25 | } 26 | 27 | proto_wgconfd_init_config() { 28 | proto_config_add_array 'ipaddr:ipaddr' 29 | proto_config_add_array 'ip6addr:ip6addr' 30 | proto_config_add_int 'mtu' 31 | 32 | proto_config_add_string 'private_key' 33 | proto_config_add_int 'listen_port' 34 | proto_config_add_string 'fwmark' 35 | 36 | proto_config_add_int 'refresh_sec' 37 | proto_config_add_int 'min_keepalive' 38 | proto_config_add_int 'max_keepalive' 39 | 40 | available=1 41 | } 42 | 43 | proto_wgconfd_setup__print() { 44 | local i 45 | for i; do 46 | # TODO: escape 47 | echo -n "$i " 48 | done 49 | } 50 | 51 | proto_wgconfd_setup__source() { 52 | local name val 53 | 54 | config_get name "$1" name 55 | [ -z "$name" ] && return 56 | config_get val "$1" url 57 | [ -z "$val" ] && return 58 | proto_wgconfd_setup__print source "$name" "$val" 59 | 60 | config_get val "$1" psk 61 | [ -n "$val" ] && proto_wgconfd_setup__print psk "$val" 62 | 63 | config_get_bool val "$1" required 0 64 | [ "$val" -eq 1 ] && proto_wgconfd_setup__print required 65 | 66 | config_get_bool val "$1" allow_road_warriors 1 67 | [ "$val" -eq 0 ] && proto_wgconfd_setup__print deny_road_warriors 68 | 69 | config_list_foreach "$1" ipv4 proto_wgconfd_setup__source_route ipv4 32 70 | 71 | config_list_foreach "$1" ipv6 proto_wgconfd_setup__source_route ipv6 128 72 | } 73 | 74 | proto_wgconfd_setup__source_route() { 75 | local p="$2" 76 | local maxlen="$3" 77 | local route=1 78 | set -- $1 79 | local r="$1" 80 | shift 1 81 | local i 82 | for i; do case "$i" in 83 | no-route) 84 | route=0 85 | ;; 86 | *) 87 | true 88 | ;; 89 | esac; done 90 | proto_wgconfd_setup__print "$p" "$r" 91 | if [ "$route" -eq 1 ]; then 92 | case "$r" in 93 | '') 94 | true 95 | ;; 96 | */*) 97 | echo "${p}_route ${r%/*} ${r##*/}" >> "$dir/update" 98 | ;; 99 | *) 100 | echo "${p}_route $r $maxlen" >> "$dir/update" 101 | ;; 102 | esac 103 | fi 104 | } 105 | 106 | proto_wgconfd_setup__peer() { 107 | local val 108 | 109 | config_get val "$1" public_key 110 | [ -z "$val" ] && return 111 | proto_wgconfd_setup__print peer "$val" 112 | 113 | config_get val "$1" endpoint 114 | [ -n "$val" ] && proto_wgconfd_setup__print endpoint "$val" 115 | 116 | config_get val "$1" psk 117 | [ -n "$val" ] && proto_wgconfd_setup__print psk "$val" 118 | 119 | config_get val "$1" keepalive 120 | [ -n "$val" ] && proto_wgconfd_setup__print keepalive "$val" 121 | 122 | config_get val "$1" source 123 | [ -n "$val" ] && proto_wgconfd_setup__print source "$val" 124 | } 125 | 126 | proto_wgconfd__echo_addr() { 127 | case "$1" in 128 | '') 129 | true 130 | ;; 131 | */*) 132 | echo "${3}_address ${1%/*} ${1##*/}" >> "$dir/update" 133 | ;; 134 | *) 135 | echo "${3}_address $1 $4" >> "$dir/update" 136 | ;; 137 | esac 138 | } 139 | 140 | proto_wgconfd_setup() { 141 | local interface="$1" ifname="$2" i r 142 | if [ -z "$ifname" ]; then 143 | ifname="$interface" 144 | fi 145 | 146 | local mtu 147 | local private_key listen_port fwmark 148 | local refresh_sec min_keepalive max_keepalive 149 | json_get_vars mtu private_key listen_port fwmark refresh_sec min_keepalive max_keepalive 150 | 151 | if [ -z "$private_key" ]; then 152 | proto_notify_error "$interface" NO_PRIVATE_KEY 153 | proto_block_restart "$interface" 154 | exit 155 | fi 156 | 157 | [ -n "$fwmark" ] && fwmark="fwmark $fwmark" 158 | 159 | dir="/tmp/wgconfd/$interface" 160 | if [ -d "$dir" ]; then 161 | rm -rf "$dir" 162 | fi 163 | mkdir -p /tmp/wgconfd 164 | if ! mkdir -m 0700 "$dir" || ! mkdir "$dir/cache" || ! echo "$private_key" > "$dir/private" || ! true > "$dir/update" ; then 165 | proto_notify_error "$interface" FS_ERROR 166 | return 1 167 | fi 168 | 169 | json_for_each_item proto_wgconfd__echo_addr ipaddr ipv4 32 170 | json_for_each_item proto_wgconfd__echo_addr ip6addr ipv6 128 171 | 172 | wgconfd_command="$( 173 | proto_wgconfd_setup__print "$WGCONFD" --cmdline "$ifname" 174 | config_load network 175 | config_foreach proto_wgconfd_setup__source wgconfd_source_"$interface" 176 | config_foreach proto_wgconfd_setup__peer wgconfd_peer_"$interface" 177 | )" 178 | 179 | ip link del dev "$ifname" 2>/dev/null 180 | if ! ip link add dev "$ifname" mtu "${mtu:-1420}" type wireguard; then 181 | proto_notify_error "$interface" IFACE_ERROR 182 | exit 183 | fi 184 | 185 | "$WG" set "$ifname" private-key "$dir/private" listen-port "${listen_port:-656}" $fwmark 186 | r="$?" 187 | rm -f "$dir/private" 188 | if [ "$r" != 0 ]; then 189 | ip link del dev "$ifname" 2>/dev/null 190 | proto_notify_error "$interface" WG_ERROR 191 | exit 192 | fi 193 | 194 | proto_init_update "$ifname" 1 0 195 | proto_set_keep 0 196 | while read i r; do 197 | proto_add_"$i" $r 198 | done < "$dir/update" 199 | # rm -f "$dir/update" 200 | proto_send_update "$interface" 201 | 202 | 203 | proto_export "WG=$WG" 204 | proto_export "CURL=$CURL" 205 | proto_export "RUNTIME_DIRECTORY=$dir" 206 | proto_export "CACHE_DIRECTORY=$dir/cache" 207 | proto_run_command "$interface" $wgconfd_command 208 | } 209 | 210 | proto_wgconfd_teardown() { 211 | local interface="$1" ifname="$2" i r 212 | if [ -z "$ifname" ]; then 213 | ifname="$interface" 214 | fi 215 | 216 | proto_kill_command "$interface" 217 | ip link del dev "$ifname" 2>/dev/null 218 | } 219 | 220 | [ -n "$INCLUDE_ONLY" ] || { 221 | add_protocol wgconfd 222 | } 223 | -------------------------------------------------------------------------------- /dist/systemd/wgconfd-state@.service: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: CC0-1.0 2 | # 3 | # Copyright 2019 Hristo Venev 4 | 5 | [Unit] 6 | Description=WireGuard runtime state for %i 7 | 8 | [Service] 9 | Type=oneshot 10 | ExecStart=/bin/true 11 | RemainAfterExit=true 12 | RuntimeDirectory=wgconfd/%i 13 | RuntimeDirectoryMode=0700 14 | RuntimeDirectoryPreserve=no 15 | -------------------------------------------------------------------------------- /dist/systemd/wgconfd@.service: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: CC0-1.0 2 | # 3 | # Copyright 2019 Hristo Venev 4 | 5 | [Unit] 6 | Description=WireGuard configuration daemon on %i 7 | Wants=network.target 8 | Requires=wgconfd-state@%i.service 9 | After=network-pre.target wgconfd-state@%i.service 10 | Before=network.target 11 | 12 | [Service] 13 | Type=simple 14 | CapabilityBoundingSet=CAP_NET_ADMIN 15 | Restart=on-failure 16 | RestartSec=0 17 | CacheDirectory=wgconfd/%i 18 | CacheDirectoryMode=0700 19 | Environment=RUNTIME_DIRECTORY=%t/wgconfd/%i 20 | ExecStart=/usr/bin/env wgconfd %i /etc/wireguard/%i.toml 21 | StandardError=journal 22 | SyslogLevelPrefix=true 23 | 24 | [Install] 25 | WantedBy=multi-user.target 26 | -------------------------------------------------------------------------------- /man/Makefile: -------------------------------------------------------------------------------- 1 | PAGES = wgconfd.5 wgconfd.8 2 | 3 | .PHONY: all clean 4 | all: $(PAGES) 5 | 6 | clean: 7 | rm $(PAGES) 8 | 9 | %: %.scd 10 | scdoc < $< > $@ 11 | -------------------------------------------------------------------------------- /man/wgconfd.5.scd: -------------------------------------------------------------------------------- 1 | wgconfd(5) 2 | 3 | # NAME 4 | 5 | wgconfd - configuration file 6 | 7 | # GLOBAL OPTIONS 8 | 9 | The following global options are available: 10 | 11 | *min_keepalive* 12 | The minimum value for the persistent keepalive timeout, in seconds. Any peer 13 | with a smaller timeout uses this one instead. Set to 0 to disable the 14 | timeout altogether. 15 | 16 | Default: _10_ 17 | 18 | *max_keepalive* 19 | The maximum value for the persistent keepalive timeout, in seconds. Any peer 20 | with a larger (or missing) timeout uses this one instead. If set to 0, there 21 | is no maximum. 22 | 23 | Default: _0_ 24 | 25 | *refresh_sec* 26 | The time between configuration updates, in seconds. 27 | 28 | Default: _1200_ 29 | 30 | *cache_directory* 31 | Path to the cache directory. 32 | 33 | Default: _$CACHE_DIRECTORY_ 34 | 35 | *runtime_directory* 36 | Path to the runtime state directory. 37 | 38 | Default: _$RUNTIME_DIRECTORY_ 39 | 40 | # SOURCE SECTIONS 41 | 42 | Sources are defined in *[[source]]* sections. The following options are available: 43 | 44 | *name* 45 | The name used to identify the source in logs and in the cache. All sources 46 | should have distinct names. Should only contain characters that can be put 47 | in a filename. Required. 48 | 49 | *url* 50 | The URL of the source. It must point to a JSON file following the format 51 | described in the README. 52 | 53 | *ipv4* 54 | A list of allowed IPv4 networks, each of the form _"ADDR/LEN"_. All of the 55 | address bits after the prefix must be set to 0. 56 | 57 | If a source tries to assign a range of addresses to a peer and that range 58 | has addresses that are not listed in the *ipv4* configuration option, the 59 | entire range is discarded. 60 | 61 | Default: _[]_ 62 | 63 | *ipv6* 64 | A list of allowed IPv6 networks, each of the form _"ADDR/LEN"_. All of the 65 | address bits after the prefix must be set to 0. 66 | 67 | If a source tries to assign a range of addresses to a peer and that range 68 | has addresses that are not listed in the *ipv6* configuration option, the 69 | entire range is discarded. 70 | 71 | Default: _[]_ 72 | 73 | *psk* 74 | Path to a file containing the default preshared key used for all peers 75 | defined by this source. 76 | 77 | Default: no preshared key 78 | 79 | *required* 80 | Boolean. If set to true, *wgconfd*(8) will fail to start if fetching the 81 | source fails. 82 | 83 | Default: _false_ 84 | 85 | *allow_road_warriors* 86 | Boolean. If set to false, road warriors from this source will not be allowed 87 | to use this interface machine as their base peer. 88 | 89 | Default: _true_ 90 | 91 | # PEER SECTIONS 92 | 93 | In some cases one may want to override some settings for individual peers. 94 | This can be achieved through *[peer."public_key"]* sections: 95 | 96 | *source* 97 | If specified, ignore attempts by other sources to define this peer. Note 98 | that even if this is set, other sources can add allowed IP addresses for 99 | the peer by creating road warriors. 100 | 101 | Default: do not restrict source 102 | 103 | *endpoint* 104 | Override the endpoint address of the peer. 105 | 106 | Default: use the endpoint address from the source 107 | 108 | *psk* 109 | Path to a preshared key to use for this peer. 110 | 111 | Default: the PSK of the source, if any 112 | 113 | *keepalive* 114 | Override the persistent keepalive timeout for this peer. The value here is 115 | not affected by the *min_keepalive* and *max_keepalive* configuration 116 | options. 117 | 118 | Default: the keepalive value from the source, or infinite if not set, 119 | restricted by *min_keepalive* and *max_keepalive* 120 | 121 | Note that having a *[peer.*]* section is not enough to create a peer. It must 122 | also exist in one of the sources. 123 | -------------------------------------------------------------------------------- /man/wgconfd.8.scd: -------------------------------------------------------------------------------- 1 | wgconfd(8) 2 | 3 | # NAME 4 | 5 | wgconfd - configuration manager for WireGuard 6 | 7 | # SYNOPSIS 8 | 9 | *wgconfd* _IFNAME_ _CONFIG_++ 10 | *wgconfd* --cmdline _IFNAME_ _ARGS_...++ 11 | *wgconfd* --check-source _PATH_ 12 | 13 | # DESCRIPTION 14 | 15 | In the 1st and 2nd form, run wgconfd on the network interface named IFNAME. In 16 | the 1st form, CONFIG is the path to the configuration file, the format of which 17 | is described in *wgconfd*(5). In the 2nd form, the configuration is provided on 18 | the command line. The way this is done is described in the _COMMAND-LINE 19 | CONFIGURATION_ section. 20 | 21 | In the 3rd form, wgconfd checks the validity of a source JSON. PATH is a path 22 | to a local file. 23 | 24 | # COMMAND-LINE CONFIGURATION 25 | 26 | While the usual way to configure wgconfd is through a file, in some cases it 27 | is easier to pass everything on the command line. The arguments consist of a 28 | sequence of global options, sources, and peers: 29 | 30 | min_keepalive _SEC_++ 31 | max_keepalive _SEC_++ 32 | refresh_sec _SEC_++ 33 | source _NAME_ _URL_ [psk _PATH_] [ipv4 _NET_,_NET_,...] [ipv6 _NET_,_NET_,...] [required] [allow_road_warriors | deny_road_warriors]++ 34 | peer _PUBKEY_ [endpoint _IP_:_PORT_] [psk _PATH_] [keepalive _SEC_] [source _NAME_] 35 | 36 | # EXIT VALUE 37 | 38 | When managing an interface, wgconfd does not exit. When checking the validity of 39 | a source, a nonzero exit status would indicate a problem with the source. 40 | 41 | # ENVIRONMENT 42 | 43 | *wgconfd* uses the following environment variables: 44 | 45 | WG - the *wg*(8) command. Used for configuring the interface. Default: _wg_ 46 | 47 | CURL - the *curl*(1) command. Used for fetching sources. Default: _curl_ 48 | 49 | CACHE_DIRECTORY - the path where sources are cached. 50 | 51 | RUNTIME_DIRECTORY - the path where the runtime state is preserved. 52 | 53 | # SEE ALSO 54 | 55 | *wgconfd*(5), *wg*(8), *curl*(1) 56 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-3.0-or-later 2 | // 3 | // Copyright 2019,2020 Hristo Venev 4 | 5 | use crate::model::{Endpoint, Ipv4Set, Ipv6Set, Key, Secret}; 6 | use serde_derive; 7 | use std::collections::HashMap; 8 | use std::path::PathBuf; 9 | 10 | #[derive(serde_derive::Deserialize)] 11 | #[serde(deny_unknown_fields)] 12 | pub struct Source { 13 | pub name: String, 14 | pub url: String, 15 | #[serde(default, deserialize_with = "deserialize_key_from_file")] 16 | pub psk: Option, 17 | pub ipv4: Ipv4Set, 18 | pub ipv6: Ipv6Set, 19 | #[serde(default)] 20 | pub required: bool, 21 | #[serde(default = "default_allow_road_warriors")] 22 | pub allow_road_warriors: bool, 23 | } 24 | 25 | #[derive(serde_derive::Deserialize)] 26 | #[serde(deny_unknown_fields)] 27 | pub struct Peer { 28 | pub source: Option, 29 | pub endpoint: Option, 30 | #[serde(default, deserialize_with = "deserialize_key_from_file")] 31 | pub psk: Option, 32 | pub keepalive: Option, 33 | } 34 | 35 | pub struct GlobalConfig { 36 | pub min_keepalive: u32, 37 | pub max_keepalive: u32, 38 | pub peers: HashMap, 39 | } 40 | 41 | impl Default for GlobalConfig { 42 | #[inline] 43 | fn default() -> Self { 44 | Self { 45 | min_keepalive: default_min_keepalive(), 46 | max_keepalive: default_max_keepalive(), 47 | peers: HashMap::new(), 48 | } 49 | } 50 | } 51 | 52 | impl GlobalConfig { 53 | pub fn fix_keepalive(&self, mut k: u32) -> u32 { 54 | if self.max_keepalive != 0 && (k == 0 || k > self.max_keepalive) { 55 | k = self.max_keepalive; 56 | } 57 | if k != 0 && k < self.min_keepalive { 58 | k = self.min_keepalive; 59 | } 60 | k 61 | } 62 | } 63 | 64 | pub struct UpdaterConfig { 65 | pub cache_directory: Option, 66 | 67 | // Number of seconds between regular updates. 68 | pub refresh_sec: u32, 69 | } 70 | 71 | impl Default for UpdaterConfig { 72 | #[inline] 73 | fn default() -> Self { 74 | Self { 75 | cache_directory: None, 76 | refresh_sec: default_refresh_sec(), 77 | } 78 | } 79 | } 80 | 81 | #[derive(serde_derive::Deserialize)] 82 | #[serde(from = "ConfigRepr")] 83 | #[derive(Default)] 84 | pub struct Config { 85 | pub runtime_directory: Option, 86 | pub global: GlobalConfig, 87 | pub updater: UpdaterConfig, 88 | pub sources: Vec, 89 | } 90 | 91 | #[derive(serde_derive::Deserialize)] 92 | #[serde(deny_unknown_fields)] 93 | struct ConfigRepr { 94 | runtime_directory: Option, 95 | cache_directory: Option, 96 | 97 | #[serde(default = "default_min_keepalive")] 98 | min_keepalive: u32, 99 | #[serde(default = "default_max_keepalive")] 100 | max_keepalive: u32, 101 | #[serde(default, rename = "peer")] 102 | peers: HashMap, 103 | 104 | #[serde(default = "default_refresh_sec")] 105 | refresh_sec: u32, 106 | 107 | #[serde(default, rename = "source")] 108 | sources: Vec, 109 | } 110 | 111 | impl From for Config { 112 | #[inline] 113 | fn from(v: ConfigRepr) -> Self { 114 | let ConfigRepr { 115 | runtime_directory, 116 | cache_directory, 117 | min_keepalive, 118 | max_keepalive, 119 | peers, 120 | refresh_sec, 121 | sources, 122 | } = v; 123 | Self { 124 | runtime_directory, 125 | global: GlobalConfig { 126 | min_keepalive, 127 | max_keepalive, 128 | peers, 129 | }, 130 | updater: UpdaterConfig { 131 | cache_directory, 132 | refresh_sec, 133 | }, 134 | sources, 135 | } 136 | } 137 | } 138 | 139 | #[inline] 140 | const fn default_allow_road_warriors() -> bool { 141 | true 142 | } 143 | 144 | #[inline] 145 | const fn default_min_keepalive() -> u32 { 146 | 10 147 | } 148 | 149 | #[inline] 150 | const fn default_max_keepalive() -> u32 { 151 | 0 152 | } 153 | 154 | #[inline] 155 | const fn default_refresh_sec() -> u32 { 156 | 1200 157 | } 158 | 159 | fn deserialize_key_from_file<'de, D>(d: D) -> Result, D::Error> 160 | where 161 | D: serde::Deserializer<'de>, 162 | { 163 | let path = >::deserialize(d)?; 164 | Secret::from_file(&path).map_err(|e| ::custom(e.to_string())) 165 | } 166 | -------------------------------------------------------------------------------- /src/fileutil.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-3.0-or-later 2 | // 3 | // Copyright 2019 Hristo Venev 4 | 5 | #[cfg(unix)] 6 | use std::os::unix::fs::OpenOptionsExt; 7 | use std::path::{Path, PathBuf}; 8 | use std::{fs, io, mem}; 9 | 10 | #[repr(transparent)] 11 | pub struct Temp { 12 | path: PathBuf, 13 | } 14 | 15 | impl Drop for Temp { 16 | fn drop(&mut self) { 17 | if self.path.as_os_str().is_empty() { 18 | return; 19 | } 20 | if let Err(err) = fs::remove_file(&self.path) { 21 | eprintln!("<3>Failed to clean up temporary file: {}", err); 22 | } 23 | } 24 | } 25 | 26 | impl Temp { 27 | #[inline] 28 | pub fn path(&self) -> &Path { 29 | &self.path 30 | } 31 | 32 | #[inline] 33 | pub fn leave(mut self) -> PathBuf { 34 | mem::replace(&mut self.path, PathBuf::new()) 35 | } 36 | 37 | #[inline] 38 | pub fn rename_to(self, to: impl AsRef) -> io::Result<()> { 39 | fs::rename(self.leave(), to) 40 | } 41 | } 42 | 43 | pub struct Writer { 44 | inner: Temp, 45 | file: fs::File, 46 | } 47 | 48 | impl Writer { 49 | pub fn new(path: PathBuf) -> io::Result { 50 | let mut file = fs::OpenOptions::new(); 51 | file.create_new(true); 52 | file.append(true); 53 | #[cfg(unix)] 54 | file.mode(0o0600); 55 | let file = file.open(&path)?; 56 | 57 | Ok(Self { 58 | inner: Temp { path }, 59 | file, 60 | }) 61 | } 62 | 63 | pub fn new_in(path: &Path) -> io::Result { 64 | use rand::RngCore; 65 | let mut rng = rand::thread_rng(); 66 | loop { 67 | let i: u64 = rng.next_u64(); 68 | let mut p: PathBuf = path.into(); 69 | p.push(format!(".tmp.{:16x}", i)); 70 | match Self::new(p) { 71 | Ok(v) => return Ok(v), 72 | Err(e) => { 73 | if e.kind() != io::ErrorKind::AlreadyExists { 74 | return Err(e); 75 | } 76 | } 77 | } 78 | } 79 | } 80 | 81 | #[inline] 82 | pub fn file(&mut self) -> &mut fs::File { 83 | &mut self.file 84 | } 85 | 86 | #[inline] 87 | pub fn sync_done(self) -> io::Result { 88 | self.file.sync_data()?; 89 | Ok(self.done()) 90 | } 91 | 92 | #[inline] 93 | pub fn done(self) -> Temp { 94 | self.inner 95 | } 96 | } 97 | 98 | pub fn update(path: &Path, data: &[u8]) -> io::Result<()> { 99 | let mut tmp = Writer::new_in(path.parent().unwrap())?; 100 | io::Write::write_all(tmp.file(), data)?; 101 | tmp.sync_done()?.rename_to(path) 102 | } 103 | 104 | #[inline] 105 | pub fn load(path: &impl AsRef) -> io::Result> { 106 | _load(path.as_ref()) 107 | } 108 | 109 | fn _load(path: &Path) -> io::Result> { 110 | let mut file = fs::File::open(&path)?; 111 | let mut data = Vec::new(); 112 | io::Read::read_to_end(&mut file, &mut data)?; 113 | Ok(data) 114 | } 115 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-3.0-or-later 2 | // 3 | // Copyright 2019 Hristo Venev 4 | 5 | #![deny(rust_2018_idioms)] 6 | 7 | #[macro_use] 8 | extern crate arrayref; 9 | 10 | use std::ffi::{OsStr, OsString}; 11 | use std::time::Instant; 12 | use std::{env, mem, process, thread}; 13 | 14 | mod config; 15 | mod fileutil; 16 | mod manager; 17 | mod model; 18 | mod proto; 19 | mod wg; 20 | 21 | fn cli_config(mut args: impl Iterator) -> Option { 22 | enum State<'a> { 23 | Source(&'a mut config::Source), 24 | Peer(&'a mut config::Peer), 25 | None, 26 | } 27 | 28 | use std::str::FromStr; 29 | 30 | let mut cfg = config::Config::default(); 31 | 32 | let mut cur = State::None; 33 | while let Some(key) = args.next() { 34 | let arg; 35 | 36 | match cur { 37 | State::Source(ref mut s) => { 38 | if key == "psk" { 39 | arg = args.next()?; 40 | s.psk = model::Secret::from_file(&arg).ok()?; 41 | continue; 42 | } 43 | if key == "ipv4" { 44 | arg = args.next()?; 45 | let arg = arg.to_str()?; 46 | for arg in arg.split(',') { 47 | s.ipv4.insert(model::Ipv4Net::from_str(arg).ok()?); 48 | } 49 | continue; 50 | } 51 | if key == "ipv6" { 52 | arg = args.next()?; 53 | let arg = arg.to_str()?; 54 | for arg in arg.split(',') { 55 | s.ipv6.insert(model::Ipv6Net::from_str(arg).ok()?); 56 | } 57 | continue; 58 | } 59 | if key == "required" { 60 | s.required = true; 61 | continue; 62 | } 63 | if key == "deny_road_warriors" { 64 | s.allow_road_warriors = false; 65 | continue; 66 | } 67 | if key == "allow_road_warriors" { 68 | s.allow_road_warriors = true; 69 | continue; 70 | } 71 | } 72 | State::Peer(ref mut p) => { 73 | if key == "source" { 74 | p.source = Some(args.next()?.into_string().ok()?); 75 | continue; 76 | } 77 | if key == "endpoint" { 78 | arg = args.next()?; 79 | let arg = arg.to_str()?; 80 | p.endpoint = Some(model::Endpoint::from_str(arg).ok()?); 81 | continue; 82 | } 83 | if key == "psk" { 84 | arg = args.next()?; 85 | p.psk = model::Secret::from_file(&arg).ok()?; 86 | continue; 87 | } 88 | if key == "keepalive" { 89 | arg = args.next()?; 90 | let arg = arg.to_str()?; 91 | p.keepalive = Some(u32::from_str(arg).ok()?); 92 | continue; 93 | } 94 | } 95 | State::None => {} 96 | } 97 | cur = State::None; 98 | 99 | if key == "min_keepalive" { 100 | arg = args.next()?; 101 | let arg = arg.to_str()?; 102 | cfg.global.min_keepalive = u32::from_str(arg).ok()?; 103 | continue; 104 | } 105 | if key == "max_keepalive" { 106 | arg = args.next()?; 107 | let arg = arg.to_str()?; 108 | cfg.global.max_keepalive = u32::from_str(arg).ok()?; 109 | continue; 110 | } 111 | if key == "refresh_sec" { 112 | arg = args.next()?; 113 | let arg = arg.to_str()?; 114 | cfg.updater.refresh_sec = u32::from_str(arg).ok()?; 115 | continue; 116 | } 117 | if key == "source" { 118 | let name = args.next()?.into_string().ok()?; 119 | let url = args.next()?.into_string().ok()?; 120 | cfg.sources.push(config::Source { 121 | name, 122 | url, 123 | psk: None, 124 | ipv4: model::Ipv4Set::new(), 125 | ipv6: model::Ipv6Set::new(), 126 | required: false, 127 | allow_road_warriors: true, 128 | }); 129 | cur = State::Source(cfg.sources.last_mut().unwrap()); 130 | continue; 131 | } 132 | if key == "peer" { 133 | arg = args.next()?; 134 | let key = model::Key::from_str(arg.to_str()?).ok()?; 135 | cur = State::Peer(cfg.global.peers.entry(key).or_insert(config::Peer { 136 | source: None, 137 | endpoint: None, 138 | psk: None, 139 | keepalive: None, 140 | })); 141 | continue; 142 | } 143 | 144 | return None; 145 | } 146 | 147 | Some(cfg) 148 | } 149 | 150 | fn usage(argv0: &str) -> i32 { 151 | eprintln!( 152 | "<1>Invalid arguments. See `{} --help` for more information", 153 | argv0 154 | ); 155 | 1 156 | } 157 | 158 | fn help(argv0: &str, args: Vec) -> i32 { 159 | mem::drop(args); 160 | print!( 161 | "\ 162 | Usage: 163 | {} IFNAME CONFIG - run daemon on interface 164 | {} --cmdline IFNAME ... - run daemon using config passed as arguments 165 | {} --check-source PATH - validate source JSON 166 | ", 167 | argv0, argv0, argv0 168 | ); 169 | 1 170 | } 171 | 172 | fn run_usage(argv0: &str, _: Vec) -> i32 { 173 | usage(argv0) 174 | } 175 | 176 | fn maybe_get_var(out: &mut Option>, var: impl AsRef) { 177 | let var = var.as_ref(); 178 | if let Some(s) = env::var_os(var) { 179 | env::remove_var(var); 180 | *out = Some(s.into()); 181 | } 182 | } 183 | 184 | #[cfg(feature = "toml")] 185 | fn run_with_file(argv0: &str, args: Vec) -> i32 { 186 | let (ifname, path) = match (move || { 187 | let mut args = args.into_iter(); 188 | let a = args.next()?; 189 | let b = args.next()?; 190 | if args.next().is_some() { 191 | return None; 192 | } 193 | Some((a, b)) 194 | })() { 195 | Some(v) => v, 196 | None => return usage(argv0), 197 | }; 198 | 199 | let data = fileutil::load(&path); 200 | mem::drop(path); 201 | let data = match data { 202 | Ok(v) => v, 203 | Err(e) => { 204 | eprintln!("<1>Failed to load config file: {}", e); 205 | return 1; 206 | } 207 | }; 208 | 209 | let config = toml::from_slice(&data); 210 | mem::drop(data); 211 | let config = match config { 212 | Ok(v) => v, 213 | Err(e) => { 214 | eprintln!("<1>Failed to parse config: {}", e); 215 | return 1; 216 | } 217 | }; 218 | 219 | run_daemon(ifname, config) 220 | } 221 | 222 | #[cfg(not(feature = "toml"))] 223 | fn run_with_file(_argv0: &str, _args: Vec) -> i32 { 224 | eprintln!("<1>Config loading not supported"); 225 | 1 226 | } 227 | 228 | fn run_with_cmdline(argv0: &str, args: Vec) -> i32 { 229 | let mut args = args.into_iter(); 230 | 231 | let ifname = match args.next() { 232 | Some(v) => v, 233 | None => return usage(argv0), 234 | }; 235 | 236 | let config = match cli_config(args) { 237 | Some(c) => c, 238 | None => { 239 | eprintln!("<1>Invalid config"); 240 | return 1; 241 | } 242 | }; 243 | 244 | run_daemon(ifname, config) 245 | } 246 | 247 | fn run_daemon(ifname: OsString, mut config: config::Config) -> i32 { 248 | maybe_get_var(&mut config.updater.cache_directory, "CACHE_DIRECTORY"); 249 | maybe_get_var(&mut config.runtime_directory, "RUNTIME_DIRECTORY"); 250 | 251 | let mut m = match manager::Manager::new(ifname, config) { 252 | Ok(m) => m, 253 | Err(e) => { 254 | eprintln!("<1>Failed to start: {}", e); 255 | return 1; 256 | } 257 | }; 258 | 259 | loop { 260 | let tm = match m.update() { 261 | Ok(t) => t, 262 | Err(e) => { 263 | eprintln!("<1>{}", e); 264 | return 1; 265 | } 266 | }; 267 | let now = Instant::now(); 268 | if tm > now { 269 | let sleep = tm.duration_since(now); 270 | thread::sleep(sleep); 271 | } 272 | } 273 | } 274 | 275 | fn run_check_source(argv0: &str, args: Vec) -> i32 { 276 | let mut args = args.into_iter(); 277 | let path = match args.next() { 278 | Some(v) => v, 279 | None => return usage(argv0), 280 | }; 281 | if args.next().is_some() { 282 | return usage(argv0); 283 | } 284 | 285 | match manager::load_source(&path) { 286 | Ok(_) => { 287 | println!("OK"); 288 | 0 289 | } 290 | Err(e) => { 291 | println!("{}", e); 292 | 1 293 | } 294 | } 295 | } 296 | 297 | fn main() { 298 | let mut iter_args = env::args_os(); 299 | let argv0 = iter_args.next().unwrap(); 300 | let argv0 = argv0.to_string_lossy(); 301 | 302 | let mut args = Vec::new(); 303 | let mut run: for<'a> fn(&'a str, Vec) -> i32 = run_with_file; 304 | for arg in &mut iter_args { 305 | if !arg.to_string_lossy().starts_with('-') { 306 | args.push(arg); 307 | } else if arg == "--" { 308 | break; 309 | } else if arg == "-h" || arg == "--help" { 310 | run = help; 311 | break; 312 | } else if arg == "--check-source" { 313 | run = run_check_source; 314 | break; 315 | } else if arg == "--cmdline" { 316 | run = run_with_cmdline; 317 | break; 318 | } else { 319 | run = run_usage; 320 | break; 321 | } 322 | } 323 | args.extend(iter_args); 324 | 325 | process::exit(run(&argv0, args)); 326 | } 327 | -------------------------------------------------------------------------------- /src/manager/builder.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-3.0-or-later 2 | // 3 | // Copyright 2019 Hristo Venev 4 | 5 | use super::Source; 6 | use crate::{config, model, proto}; 7 | use std::collections::hash_map; 8 | use std::{error, fmt}; 9 | 10 | #[derive(Debug)] 11 | pub struct Error { 12 | pub src: String, 13 | pub peer: model::Key, 14 | important: bool, 15 | err: &'static str, 16 | } 17 | 18 | impl Error { 19 | fn new(err: &'static str, src: &Source, p: &proto::Peer, important: bool) -> Self { 20 | Self { 21 | src: src.config.name.clone(), 22 | peer: p.public_key, 23 | important, 24 | err, 25 | } 26 | } 27 | 28 | #[inline] 29 | pub fn important(&self) -> bool { 30 | self.important 31 | } 32 | } 33 | 34 | impl error::Error for Error {} 35 | impl fmt::Display for Error { 36 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 37 | write!( 38 | f, 39 | "{} [{}]/[{}]: {}", 40 | if self.important { 41 | "invalid peer" 42 | } else { 43 | "misconfigured peer" 44 | }, 45 | self.src, 46 | self.peer, 47 | self.err 48 | ) 49 | } 50 | } 51 | 52 | struct PeerContact<'a> { 53 | endpoint: Option, 54 | psk: Option<&'a model::Secret>, 55 | keepalive: u32, 56 | } 57 | 58 | pub(super) struct ConfigBuilder<'a> { 59 | c: model::Config, 60 | err: Vec, 61 | public_key: model::Key, 62 | gc: &'a config::GlobalConfig, 63 | } 64 | 65 | impl<'a> ConfigBuilder<'a> { 66 | #[inline] 67 | pub fn new(public_key: model::Key, gc: &'a config::GlobalConfig) -> Self { 68 | Self { 69 | c: model::Config::empty(), 70 | err: vec![], 71 | public_key, 72 | gc, 73 | } 74 | } 75 | 76 | #[inline] 77 | pub fn build(self) -> (model::Config, Vec) { 78 | (self.c, self.err) 79 | } 80 | 81 | #[inline] 82 | pub fn add_server(&mut self, src: &Source, p: &proto::Server) { 83 | let gc = self.gc; 84 | 85 | let mut contact = match peer_contact(gc, src, &p.peer) { 86 | Ok(v) => v, 87 | Err(e) => { 88 | self.err.push(e); 89 | return; 90 | } 91 | }; 92 | if contact.endpoint.is_none() { 93 | contact.endpoint = Some(p.endpoint); 94 | } 95 | 96 | if p.peer.public_key == self.public_key { 97 | return; 98 | } 99 | 100 | let ent = insert_peer(&mut self.c, &mut self.err, src, &p.peer, contact); 101 | add_peer(&mut self.err, ent, src, &p.peer) 102 | } 103 | 104 | #[inline] 105 | pub fn add_road_warrior(&mut self, src: &Source, p: &proto::RoadWarrior) { 106 | let contact = match peer_contact(self.gc, src, &p.peer) { 107 | Ok(v) => v, 108 | Err(e) => { 109 | self.err.push(e); 110 | return; 111 | } 112 | }; 113 | 114 | if p.peer.public_key == self.public_key { 115 | self.err.push(Error::new( 116 | "the local peer cannot be a road warrior", 117 | src, 118 | &p.peer, 119 | true, 120 | )); 121 | return; 122 | } 123 | 124 | let ent = if p.base == self.public_key { 125 | if !src.config.allow_road_warriors { 126 | self.err.push(Error::new( 127 | "road warriors from this source not allowed", 128 | src, 129 | &p.peer, 130 | true, 131 | )); 132 | return; 133 | } 134 | insert_peer(&mut self.c, &mut self.err, src, &p.peer, contact) 135 | } else if let Some(ent) = self.c.peers.get_mut(&p.base) { 136 | ent 137 | } else { 138 | self.err 139 | .push(Error::new("unknown base peer", src, &p.peer, true)); 140 | return; 141 | }; 142 | add_peer(&mut self.err, ent, src, &p.peer) 143 | } 144 | } 145 | 146 | #[inline] 147 | fn insert_peer<'b>( 148 | c: &'b mut model::Config, 149 | err: &mut Vec, 150 | src: &Source, 151 | p: &proto::Peer, 152 | contact: PeerContact<'_>, 153 | ) -> &'b mut model::Peer { 154 | match c.peers.entry(p.public_key) { 155 | hash_map::Entry::Occupied(ent) => { 156 | err.push(Error::new("duplicate public key", src, p, true)); 157 | ent.into_mut() 158 | } 159 | hash_map::Entry::Vacant(ent) => ent.insert(model::Peer { 160 | endpoint: contact.endpoint, 161 | psk: contact.psk.cloned(), 162 | keepalive: contact.keepalive, 163 | ipv4: vec![], 164 | ipv6: vec![], 165 | }), 166 | } 167 | } 168 | 169 | fn peer_contact<'a>( 170 | gc: &'a config::GlobalConfig, 171 | src: &'a Source, 172 | p: &proto::Peer, 173 | ) -> Result, Error> { 174 | let mut r = PeerContact { 175 | psk: src.config.psk.as_ref(), 176 | endpoint: None, 177 | keepalive: gc.fix_keepalive(p.keepalive), 178 | }; 179 | 180 | if let Some(pc) = gc.peers.get(&p.public_key) { 181 | if let Some(ref want_src) = &pc.source { 182 | if *want_src != src.config.name { 183 | return Err(Error::new("peer source not allowed", src, p, true)); 184 | } 185 | } 186 | 187 | if let Some(endpoint) = pc.endpoint { 188 | r.endpoint = Some(endpoint); 189 | } 190 | 191 | if let Some(ref psk) = &pc.psk { 192 | r.psk = Some(psk); 193 | } 194 | 195 | if let Some(keepalive) = pc.keepalive { 196 | r.keepalive = keepalive; 197 | } 198 | } 199 | 200 | Ok(r) 201 | } 202 | 203 | fn add_peer(err: &mut Vec, ent: &mut model::Peer, src: &Source, p: &proto::Peer) { 204 | let mut added = false; 205 | let mut removed = false; 206 | 207 | for i in &p.ipv4 { 208 | if src.config.ipv4.contains(i) { 209 | ent.ipv4.push(*i); 210 | added = true; 211 | } else { 212 | removed = true; 213 | } 214 | } 215 | for i in &p.ipv6 { 216 | if src.config.ipv6.contains(i) { 217 | ent.ipv6.push(*i); 218 | added = true; 219 | } else { 220 | removed = true; 221 | } 222 | } 223 | 224 | if removed { 225 | let msg = if added { 226 | "some IPs removed" 227 | } else { 228 | "all IPs removed" 229 | }; 230 | err.push(Error::new(msg, src, p, !added)); 231 | } 232 | } 233 | -------------------------------------------------------------------------------- /src/manager/mod.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-3.0-or-later 2 | // 3 | // Copyright 2019 Hristo Venev 4 | 5 | use crate::{config, fileutil, model, proto, wg}; 6 | use std::ffi::OsString; 7 | use std::io; 8 | use std::path::PathBuf; 9 | use std::time::{Duration, Instant, SystemTime}; 10 | 11 | struct Source { 12 | config: config::Source, 13 | data: proto::Source, 14 | next_update: Instant, 15 | backoff: Option, 16 | } 17 | 18 | mod updater; 19 | pub use updater::load_source; 20 | 21 | mod builder; 22 | 23 | pub struct Manager { 24 | dev: wg::Device, 25 | global_config: config::GlobalConfig, 26 | sources: Vec, 27 | current: model::Config, 28 | state_path: PathBuf, 29 | updater: updater::Updater, 30 | } 31 | 32 | impl Manager { 33 | pub fn new(ifname: OsString, c: config::Config) -> io::Result { 34 | let runtime_directory = c.runtime_directory.ok_or_else(|| { 35 | io::Error::new(io::ErrorKind::InvalidInput, "runtime directory required") 36 | })?; 37 | 38 | let mut state_path = runtime_directory.clone(); 39 | state_path.push("state.json"); 40 | 41 | let mut m = Self { 42 | dev: wg::Device::open(ifname, runtime_directory)?, 43 | global_config: c.global, 44 | sources: vec![], 45 | current: model::Config::empty(), 46 | state_path, 47 | updater: updater::Updater::new(c.updater), 48 | }; 49 | 50 | let _ = m.current_load(); 51 | 52 | for cfg in c.sources { 53 | m.add_source(cfg)?; 54 | } 55 | 56 | Ok(m) 57 | } 58 | 59 | fn current_load(&mut self) -> bool { 60 | let data = match fileutil::load(&self.state_path) { 61 | Ok(data) => data, 62 | Err(e) => { 63 | if e.kind() != io::ErrorKind::NotFound { 64 | eprintln!("<3>Failed to read interface state: {}", e); 65 | } 66 | return false; 67 | } 68 | }; 69 | 70 | let mut de = serde_json::Deserializer::from_slice(&data); 71 | match serde::Deserialize::deserialize(&mut de) { 72 | Ok(c) => { 73 | self.current = c; 74 | true 75 | } 76 | Err(e) => { 77 | eprintln!("<3>Failed to load interface state: {}", e); 78 | false 79 | } 80 | } 81 | } 82 | 83 | fn current_update(&mut self, c: &model::Config) -> io::Result<()> { 84 | let data = serde_json::to_vec(c)?; 85 | fileutil::update(&self.state_path, &data) 86 | } 87 | 88 | fn add_source(&mut self, config: config::Source) -> io::Result<()> { 89 | let mut s = Source { 90 | config, 91 | data: proto::Source::empty(), 92 | next_update: Instant::now(), 93 | backoff: None, 94 | }; 95 | 96 | self.init_source(&mut s)?; 97 | self.sources.push(s); 98 | Ok(()) 99 | } 100 | 101 | fn init_source(&mut self, s: &mut Source) -> io::Result<()> { 102 | if self.updater.update(s).0 { 103 | return Ok(()); 104 | } 105 | if self.updater.cache_load(s) { 106 | return Ok(()); 107 | } 108 | if !s.config.required { 109 | return Ok(()); 110 | } 111 | if self.updater.update(s).0 { 112 | return Ok(()); 113 | } 114 | if self.updater.update(s).0 { 115 | return Ok(()); 116 | } 117 | Err(io::Error::new( 118 | io::ErrorKind::Other, 119 | format!("failed to update required source [{}]", &s.config.url), 120 | )) 121 | } 122 | 123 | fn make_config( 124 | &self, 125 | public_key: model::Key, 126 | ts: SystemTime, 127 | ) -> (model::Config, Vec, SystemTime) { 128 | let mut t_cfg = ts + Duration::from_secs(1 << 20); 129 | let mut sources: Vec<(&Source, &proto::SourceConfig)> = vec![]; 130 | for src in &self.sources { 131 | let sc = src 132 | .data 133 | .next 134 | .as_ref() 135 | .and_then(|next| { 136 | if ts >= next.0 { 137 | Some(&next.1) 138 | } else { 139 | t_cfg = t_cfg.min(next.0); 140 | None 141 | } 142 | }) 143 | .unwrap_or(&src.data.config); 144 | sources.push((src, sc)); 145 | } 146 | 147 | let mut cfg = builder::ConfigBuilder::new(public_key, &self.global_config); 148 | 149 | for (src, sc) in &sources { 150 | for peer in &sc.servers { 151 | cfg.add_server(src, peer); 152 | } 153 | } 154 | 155 | for (src, sc) in &sources { 156 | for peer in &sc.road_warriors { 157 | cfg.add_road_warrior(src, peer); 158 | } 159 | } 160 | 161 | let (cfg, errs) = cfg.build(); 162 | (cfg, errs, t_cfg) 163 | } 164 | 165 | fn refresh(&mut self) -> io::Result { 166 | let refresh = self.updater.refresh_time(); 167 | let mut now = Instant::now(); 168 | let mut t_refresh = now + refresh; 169 | 170 | for src in &mut self.sources { 171 | if now >= src.next_update { 172 | now = self.updater.update(src).1; 173 | } 174 | t_refresh = t_refresh.min(src.next_update); 175 | } 176 | 177 | Ok(t_refresh) 178 | } 179 | 180 | pub fn update(&mut self) -> io::Result { 181 | let t_refresh = self.refresh()?; 182 | 183 | let public_key = self.dev.get_public_key()?; 184 | let now = Instant::now(); 185 | let sysnow = SystemTime::now(); 186 | let (config, errors, t_cfg) = self.make_config(public_key, sysnow); 187 | let time_to_cfg = t_cfg 188 | .duration_since(sysnow) 189 | .unwrap_or(Duration::from_secs(0)); 190 | let t_cfg = now + time_to_cfg; 191 | 192 | if config != self.current { 193 | if errors.is_empty() { 194 | eprintln!("<5>Applying configuration update"); 195 | } else { 196 | eprint!( 197 | "<{}>New update contains errors: ", 198 | if errors.iter().any(|err| err.important()) { 199 | '4' 200 | } else { 201 | '5' 202 | } 203 | ); 204 | for err in &errors { 205 | eprint!("{}; ", err); 206 | } 207 | eprintln!("applying anyway"); 208 | } 209 | self.dev.apply_diff(&self.current, &config)?; 210 | if let Err(e) = self.current_update(&config) { 211 | eprintln!("<3>Failed to persist interface state: {}", e); 212 | } 213 | self.current = config; 214 | } 215 | 216 | Ok(if t_cfg < t_refresh { 217 | eprintln!("<6>Next configuration update after {:.1?}", time_to_cfg); 218 | t_cfg 219 | } else if t_refresh > now { 220 | t_refresh 221 | } else { 222 | eprintln!("<4>Next refresh immediately?"); 223 | now 224 | }) 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /src/manager/updater.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-3.0-or-later 2 | // 3 | // Copyright 2019 Hristo Venev 4 | 5 | use super::Source; 6 | use crate::{config, fileutil, proto}; 7 | use std::ffi::{OsStr, OsString}; 8 | use std::path::PathBuf; 9 | use std::time::{Duration, Instant}; 10 | use std::{fs, io}; 11 | 12 | pub(super) struct Updater { 13 | config: config::UpdaterConfig, 14 | } 15 | 16 | impl Updater { 17 | pub fn new(config: config::UpdaterConfig) -> Self { 18 | Self { config } 19 | } 20 | 21 | fn cache_path(&self, s: &Source) -> Option { 22 | let mut p = self.config.cache_directory.as_ref()?.clone(); 23 | p.push(&s.config.name); 24 | Some(p) 25 | } 26 | 27 | fn cache_update(&self, src: &Source) { 28 | let path = match self.cache_path(src) { 29 | Some(v) => v, 30 | None => return, 31 | }; 32 | 33 | let data = serde_json::to_vec(&src.data).unwrap(); 34 | match fileutil::update(&path, &data) { 35 | Ok(()) => {} 36 | Err(e) => { 37 | eprintln!("<4>Failed to cache [{}]: {}", &src.config.name, e); 38 | } 39 | } 40 | } 41 | 42 | pub fn cache_load(&self, src: &mut Source) -> bool { 43 | let path = match self.cache_path(src) { 44 | Some(v) => v, 45 | None => return false, 46 | }; 47 | 48 | let data = match fileutil::load(&path) { 49 | Ok(data) => data, 50 | Err(e) => { 51 | if e.kind() != io::ErrorKind::NotFound { 52 | eprintln!("<3>Failed to read [{}] from cache: {}", &src.config.name, e); 53 | } 54 | return false; 55 | } 56 | }; 57 | 58 | let mut de = serde_json::Deserializer::from_slice(&data); 59 | src.data = match serde::Deserialize::deserialize(&mut de) { 60 | Ok(r) => r, 61 | Err(e) => { 62 | eprintln!("<3>Failed to load [{}] from cache: {}", &src.config.name, e); 63 | return false; 64 | } 65 | }; 66 | 67 | true 68 | } 69 | 70 | pub fn update(&self, src: &mut Source) -> (bool, Instant) { 71 | let refresh = self.refresh_time(); 72 | 73 | let r = fetch_source(&src.config.url); 74 | let now = Instant::now(); 75 | let r = match r { 76 | Ok(r) => { 77 | eprintln!("<6>Updated [{}]", &src.config.url); 78 | src.data = r; 79 | src.backoff = None; 80 | src.next_update = now + refresh; 81 | self.cache_update(src); 82 | return (true, now); 83 | } 84 | Err(r) => r, 85 | }; 86 | 87 | let b = src 88 | .backoff 89 | .unwrap_or_else(|| Duration::from_secs(10).min(refresh / 10)); 90 | src.next_update = now + b; 91 | src.backoff = Some((b + b / 3).min(refresh / 3)); 92 | eprintln!( 93 | "<3>Failed to update [{}], retrying after {:.1?}: {}", 94 | &src.config.url, b, &r 95 | ); 96 | (false, now) 97 | } 98 | 99 | pub fn refresh_time(&self) -> Duration { 100 | Duration::from_secs(u64::from(self.config.refresh_sec)) 101 | } 102 | } 103 | 104 | fn fetch_source(url: &str) -> io::Result { 105 | use std::env; 106 | use std::process::{Command, Stdio}; 107 | 108 | let curl = match env::var_os("CURL") { 109 | None => OsString::new(), 110 | Some(v) => v, 111 | }; 112 | let mut proc = Command::new(if curl.is_empty() { 113 | OsStr::new("curl") 114 | } else { 115 | curl.as_os_str() 116 | }); 117 | 118 | proc.stdin(Stdio::null()); 119 | proc.stdout(Stdio::piped()); 120 | proc.stderr(Stdio::piped()); 121 | proc.arg("-gsSfL"); 122 | proc.arg("--fail-early"); 123 | proc.arg("--max-time"); 124 | proc.arg("10"); 125 | proc.arg("--max-filesize"); 126 | proc.arg("1M"); 127 | proc.arg("--"); 128 | proc.arg(url); 129 | 130 | let out = proc.output()?; 131 | 132 | if !out.status.success() { 133 | let msg = String::from_utf8_lossy(&out.stderr); 134 | let msg = msg.replace('\n', "; "); 135 | return Err(io::Error::new(io::ErrorKind::Other, msg)); 136 | } 137 | 138 | let mut de = serde_json::Deserializer::from_slice(&out.stdout); 139 | let r = serde::Deserialize::deserialize(&mut de)?; 140 | Ok(r) 141 | } 142 | 143 | pub fn load_source(path: &OsStr) -> io::Result { 144 | let mut data = Vec::new(); 145 | { 146 | use std::io::Read; 147 | let mut f = fs::File::open(&path)?; 148 | f.read_to_end(&mut data)?; 149 | } 150 | 151 | let mut de = serde_json::Deserializer::from_slice(&data); 152 | let r = serde::Deserialize::deserialize(&mut de)?; 153 | Ok(r) 154 | } 155 | -------------------------------------------------------------------------------- /src/model.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-3.0-or-later 2 | // 3 | // Copyright 2019 Hristo Venev 4 | 5 | use crate::fileutil; 6 | use base64; 7 | use std::collections::HashMap; 8 | use std::path::Path; 9 | use std::str::FromStr; 10 | use std::{fmt, io}; 11 | 12 | mod ip; 13 | pub use ip::*; 14 | 15 | pub type KeyParseError = base64::DecodeError; 16 | 17 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 18 | pub struct Key([u8; 32]); 19 | 20 | impl Key { 21 | pub fn from_base64(s: &[u8]) -> Result { 22 | let mut v = Self([0; 32]); 23 | let l = base64::decode_config_slice(s, base64::STANDARD, &mut v.0)?; 24 | if l != v.0.len() { 25 | return Err(base64::DecodeError::InvalidLength); 26 | } 27 | Ok(v) 28 | } 29 | } 30 | 31 | impl fmt::Display for Key { 32 | #[inline] 33 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 34 | base64::display::Base64Display::with_config(&self.0, base64::STANDARD).fmt(f) 35 | } 36 | } 37 | 38 | impl FromStr for Key { 39 | type Err = KeyParseError; 40 | #[inline] 41 | fn from_str(s: &str) -> Result { 42 | Self::from_base64(s.as_bytes()) 43 | } 44 | } 45 | 46 | impl serde::Serialize for Key { 47 | fn serialize(&self, ser: S) -> Result { 48 | if ser.is_human_readable() { 49 | ser.collect_str(self) 50 | } else { 51 | ser.serialize_bytes(&self.0) 52 | } 53 | } 54 | } 55 | 56 | impl<'de> serde::Deserialize<'de> for Key { 57 | fn deserialize>(de: D) -> Result { 58 | if de.is_human_readable() { 59 | struct KeyVisitor; 60 | impl<'de> serde::de::Visitor<'de> for KeyVisitor { 61 | type Value = Key; 62 | 63 | #[inline] 64 | fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 65 | f.write_str("WireGuard key") 66 | } 67 | 68 | #[inline] 69 | fn visit_str(self, s: &str) -> Result { 70 | s.parse().map_err(E::custom) 71 | } 72 | } 73 | de.deserialize_str(KeyVisitor) 74 | } else { 75 | serde::Deserialize::deserialize(de).map(Self) 76 | } 77 | } 78 | } 79 | 80 | #[derive(serde_derive::Serialize, serde_derive::Deserialize, Clone, PartialEq, Eq)] 81 | pub struct Secret(Key); 82 | 83 | impl Secret { 84 | #[inline] 85 | pub fn from_file(path: &impl AsRef) -> io::Result> { 86 | Self::_from_file(path.as_ref()) 87 | } 88 | 89 | fn _from_file(path: &Path) -> io::Result> { 90 | let mut data = fileutil::load(&path)?; 91 | if data.last().copied() == Some(b'\n') { 92 | data.pop(); 93 | } 94 | 95 | if data.is_empty() { 96 | return Ok(None); 97 | } 98 | 99 | let k = match Key::from_base64(&data) { 100 | Ok(v) => v, 101 | Err(e) => { 102 | return Err(io::Error::new( 103 | io::ErrorKind::InvalidData, 104 | format!("failed to parse key: {}", e), 105 | )) 106 | } 107 | }; 108 | Ok(Some(Self(k))) 109 | } 110 | } 111 | 112 | impl fmt::Display for Secret { 113 | #[inline] 114 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 115 | self.0.fmt(f) 116 | } 117 | } 118 | 119 | impl fmt::Debug for Secret { 120 | #[inline] 121 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 122 | ::fmt("", f) 123 | } 124 | } 125 | 126 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 127 | pub struct Endpoint { 128 | address: Ipv6Addr, 129 | port: u16, 130 | } 131 | 132 | impl Endpoint { 133 | #[inline] 134 | pub fn ipv6_address(&self) -> Ipv6Addr { 135 | self.address 136 | } 137 | 138 | #[inline] 139 | pub fn ipv4_address(&self) -> Option { 140 | let seg = self.address.octets(); 141 | let (first, second) = array_refs![&seg, 12, 4]; 142 | if *first == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff] { 143 | Some(Ipv4Addr::from(*second)) 144 | } else { 145 | None 146 | } 147 | } 148 | 149 | #[inline] 150 | pub fn port(&self) -> u16 { 151 | self.port 152 | } 153 | } 154 | 155 | impl fmt::Display for Endpoint { 156 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 157 | if let Some(ipv4) = self.ipv4_address() { 158 | write!(f, "{}:", ipv4)?; 159 | } else { 160 | write!(f, "[{}]:", self.ipv6_address())?; 161 | } 162 | write!(f, "{}", self.port()) 163 | } 164 | } 165 | 166 | impl FromStr for Endpoint { 167 | type Err = NetParseError; 168 | fn from_str(s: &str) -> Result { 169 | use std::net; 170 | net::SocketAddr::from_str(s) 171 | .map_err(|_| NetParseError::BadAddress) 172 | .map(|v| Self { 173 | address: match v.ip() { 174 | net::IpAddr::V4(a) => a.to_ipv6_mapped(), 175 | net::IpAddr::V6(a) => a, 176 | }, 177 | port: v.port(), 178 | }) 179 | } 180 | } 181 | 182 | impl serde::Serialize for Endpoint { 183 | fn serialize(&self, ser: S) -> Result { 184 | if ser.is_human_readable() { 185 | ser.collect_str(self) 186 | } else { 187 | let mut buf = [0_u8; 16 + 2]; 188 | let (buf_addr, buf_port) = mut_array_refs![&mut buf, 16, 2]; 189 | *buf_addr = self.address.octets(); 190 | *buf_port = self.port.to_be_bytes(); 191 | ser.serialize_bytes(&buf) 192 | } 193 | } 194 | } 195 | 196 | impl<'de> serde::Deserialize<'de> for Endpoint { 197 | fn deserialize>(de: D) -> Result { 198 | if de.is_human_readable() { 199 | struct EndpointVisitor; 200 | impl<'de> serde::de::Visitor<'de> for EndpointVisitor { 201 | type Value = Endpoint; 202 | 203 | #[inline] 204 | fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 205 | f.write_str("IP:port") 206 | } 207 | 208 | #[inline] 209 | fn visit_str(self, s: &str) -> Result { 210 | s.parse().map_err(E::custom) 211 | } 212 | } 213 | de.deserialize_str(EndpointVisitor) 214 | } else { 215 | let buf = <[u8; 16 + 2] as serde::Deserialize>::deserialize(de)?; 216 | let (buf_addr, buf_port) = array_refs![&buf, 16, 2]; 217 | Ok(Self { 218 | address: (*buf_addr).into(), 219 | port: u16::from_be_bytes(*buf_port), 220 | }) 221 | } 222 | } 223 | } 224 | 225 | #[derive(serde_derive::Serialize, serde_derive::Deserialize, Clone, PartialEq, Eq, Debug)] 226 | pub struct Peer { 227 | pub endpoint: Option, 228 | pub psk: Option, 229 | pub keepalive: u32, 230 | pub ipv4: Vec, 231 | pub ipv6: Vec, 232 | } 233 | 234 | #[derive(serde_derive::Serialize, serde_derive::Deserialize, Clone, PartialEq, Eq, Debug)] 235 | pub struct Config { 236 | pub peers: HashMap, 237 | } 238 | 239 | impl Config { 240 | #[inline] 241 | pub fn empty() -> Self { 242 | Self { 243 | peers: HashMap::new(), 244 | } 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /src/model/ip.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-3.0-or-later 2 | // 3 | // Copyright 2019 Hristo Venev 4 | 5 | use serde; 6 | use std::iter::{FromIterator, IntoIterator}; 7 | pub use std::net::{Ipv4Addr, Ipv6Addr}; 8 | use std::str::FromStr; 9 | use std::{error, fmt, iter}; 10 | 11 | #[derive(Debug)] 12 | pub enum NetParseError { 13 | NoPrefixLen, 14 | BadAddress, 15 | BadPrefixLen, 16 | NotNetworkAddress, 17 | } 18 | 19 | impl error::Error for NetParseError {} 20 | impl fmt::Display for NetParseError { 21 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 22 | f.write_str(match self { 23 | Self::NoPrefixLen => "prefix length missing", 24 | Self::BadAddress => "invalid address", 25 | Self::BadPrefixLen => "prefix length out of range", 26 | Self::NotNetworkAddress => "not a network address", 27 | }) 28 | } 29 | } 30 | 31 | macro_rules! per_proto { 32 | ($nett:ident ($addrt:ident; $expecting:expr); $intt:ident($bytes:expr); $sett:ident) => { 33 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 34 | pub struct $nett { 35 | address: $addrt, 36 | prefix_len: u8, 37 | } 38 | 39 | impl $nett { 40 | const BITS: u8 = $bytes * 8; 41 | 42 | #[inline] 43 | pub fn new(address: $addrt, prefix_len: u8) -> Result { 44 | if prefix_len > Self::BITS { 45 | return Err(NetParseError::BadPrefixLen); 46 | } 47 | if prefix_len != Self::BITS { 48 | let val: $intt = address.into(); 49 | if val & ($intt::max_value() >> prefix_len) != 0 { 50 | return Err(NetParseError::NotNetworkAddress); 51 | } 52 | } 53 | Ok(Self { 54 | address, 55 | prefix_len, 56 | }) 57 | } 58 | 59 | #[inline] 60 | pub fn address(&self) -> $addrt { 61 | self.address 62 | } 63 | 64 | #[inline] 65 | pub fn prefix_len(&self) -> u8 { 66 | self.prefix_len 67 | } 68 | 69 | pub fn contains(&self, other: &Self) -> bool { 70 | if self.prefix_len > other.prefix_len { 71 | return false; 72 | } 73 | if self.prefix_len == other.prefix_len { 74 | return self.address == other.address; 75 | } 76 | if self.prefix_len == 0 { 77 | return true; 78 | } 79 | // self.prefix_len < other.prefix_len = BITS 80 | let shift = Self::BITS - self.prefix_len; 81 | let v1: $intt = self.address.into(); 82 | let v2: $intt = other.address.into(); 83 | v1 >> shift == v2 >> shift 84 | } 85 | } 86 | 87 | impl fmt::Display for $nett { 88 | #[inline] 89 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 90 | write!(f, "{}/{}", self.address, self.prefix_len) 91 | } 92 | } 93 | 94 | impl FromStr for $nett { 95 | type Err = NetParseError; 96 | fn from_str(s: &str) -> Result { 97 | let (addr, pfx) = pfx_split(s)?; 98 | let addr = $addrt::from_str(addr).map_err(|_| NetParseError::BadAddress)?; 99 | 100 | Self::new(addr, pfx) 101 | } 102 | } 103 | 104 | impl serde::Serialize for $nett { 105 | fn serialize(&self, ser: S) -> Result { 106 | if ser.is_human_readable() { 107 | ser.collect_str(self) 108 | } else { 109 | let mut buf = [0_u8; $bytes + 1]; 110 | *array_mut_ref![&mut buf, 0, $bytes] = self.address.octets(); 111 | buf[$bytes] = self.prefix_len; 112 | ser.serialize_bytes(&buf) 113 | } 114 | } 115 | } 116 | 117 | impl<'de> serde::Deserialize<'de> for $nett { 118 | fn deserialize>(de: D) -> Result { 119 | if de.is_human_readable() { 120 | struct NetVisitor; 121 | impl<'de> serde::de::Visitor<'de> for NetVisitor { 122 | type Value = $nett; 123 | 124 | #[inline] 125 | fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 126 | f.write_str($expecting) 127 | } 128 | 129 | #[inline] 130 | fn visit_str(self, s: &str) -> Result { 131 | s.parse().map_err(E::custom) 132 | } 133 | } 134 | de.deserialize_str(NetVisitor) 135 | } else { 136 | let buf = <[u8; $bytes + 1] as serde::Deserialize>::deserialize(de)?; 137 | Self::new((*array_ref![&buf, 0, $bytes]).into(), buf[$bytes]) 138 | .map_err(serde::de::Error::custom) 139 | } 140 | } 141 | } 142 | 143 | #[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)] 144 | pub struct $sett { 145 | nets: Vec<$nett>, 146 | } 147 | 148 | impl Default for $sett { 149 | #[inline] 150 | fn default() -> Self { 151 | Self::new() 152 | } 153 | } 154 | 155 | impl $sett { 156 | #[inline] 157 | pub fn new() -> Self { 158 | Self { nets: vec![] } 159 | } 160 | 161 | #[inline] 162 | fn siblings(a: $nett, b: $nett) -> bool { 163 | let pfx = a.prefix_len; 164 | if b.prefix_len != pfx || pfx == 0 { 165 | return false; 166 | } 167 | let a: $intt = a.address.into(); 168 | let b: $intt = b.address.into(); 169 | a ^ b == 1 << ($nett::BITS - pfx) 170 | } 171 | 172 | pub fn insert(&mut self, mut net: $nett) { 173 | let mut i = match self.nets.binary_search(&net) { 174 | Err(v) => v, 175 | Ok(_) => return, 176 | }; 177 | let mut j = i; 178 | if i != 0 && self.nets[i - 1].contains(&net) { 179 | net = self.nets[i - 1]; 180 | i -= 1; 181 | } 182 | while j < self.nets.len() && net.contains(&self.nets[j]) { 183 | j += 1; 184 | } 185 | loop { 186 | if j < self.nets.len() && Self::siblings(net, self.nets[j]) { 187 | j += 1; 188 | } else if i != 0 && Self::siblings(self.nets[i - 1], net) { 189 | net = self.nets[i - 1]; 190 | i -= 1; 191 | } else { 192 | break; 193 | } 194 | net.prefix_len -= 1; 195 | } 196 | self.nets.splice(i..j, iter::once(net)); 197 | } 198 | 199 | pub fn contains(&self, net: &$nett) -> bool { 200 | match self.nets.binary_search(&net) { 201 | Err(i) => { 202 | if i == 0 { 203 | return false; 204 | } 205 | self.nets[i - 1].contains(&net) 206 | } 207 | Ok(_) => true, 208 | } 209 | } 210 | 211 | #[inline] 212 | pub fn iter(&self) -> std::slice::Iter<'_, $nett> { 213 | self.nets.iter() 214 | } 215 | } 216 | 217 | impl IntoIterator for $sett { 218 | type Item = $nett; 219 | type IntoIter = std::vec::IntoIter<$nett>; 220 | 221 | #[inline] 222 | fn into_iter(self) -> Self::IntoIter { 223 | self.nets.into_iter() 224 | } 225 | } 226 | 227 | impl<'a> IntoIterator for &'a $sett { 228 | type Item = &'a $nett; 229 | type IntoIter = std::slice::Iter<'a, $nett>; 230 | 231 | #[inline] 232 | fn into_iter(self) -> Self::IntoIter { 233 | self.nets.iter() 234 | } 235 | } 236 | 237 | impl FromIterator<$nett> for $sett { 238 | #[inline] 239 | fn from_iter>(it: I) -> Self { 240 | let mut r = Self::new(); 241 | for net in it { 242 | r.insert(net); 243 | } 244 | r 245 | } 246 | } 247 | 248 | impl<'a> From<$nett> for $sett { 249 | #[inline] 250 | fn from(v: $nett) -> Self { 251 | Self { nets: vec![v] } 252 | } 253 | } 254 | 255 | impl<'a> From<[$nett; 1]> for $sett { 256 | #[inline] 257 | fn from(v: [$nett; 1]) -> Self { 258 | Self { nets: vec![v[0]] } 259 | } 260 | } 261 | 262 | impl From<$sett> for Vec<$nett> { 263 | fn from(v: $sett) -> Self { 264 | v.nets 265 | } 266 | } 267 | 268 | impl From> for $sett { 269 | fn from(nets: Vec<$nett>) -> Self { 270 | let mut s = Self { nets }; 271 | let len = s.nets.len(); 272 | if len == 0 { 273 | return s; 274 | } 275 | s.nets.sort(); 276 | let mut i = 1; 277 | for j in 1..len { 278 | let mut net = s.nets[j]; 279 | if s.nets[i - 1].contains(&net) { 280 | net = s.nets[i - 1]; 281 | i -= 1; 282 | } 283 | while i != 0 && Self::siblings(s.nets[i - 1], net) { 284 | net = s.nets[i - 1]; 285 | net.prefix_len -= 1; 286 | i -= 1; 287 | } 288 | s.nets[i] = net; 289 | i += 1; 290 | } 291 | s.nets.splice(i.., iter::empty()); 292 | s 293 | } 294 | } 295 | 296 | impl<'a> From<&'a [$nett]> for $sett { 297 | #[inline] 298 | fn from(nets: &'a [$nett]) -> Self { 299 | Vec::from(nets).into() 300 | } 301 | } 302 | 303 | impl<'a> From<&'a mut [$nett]> for $sett { 304 | #[inline] 305 | fn from(nets: &'a mut [$nett]) -> Self { 306 | Vec::from(nets).into() 307 | } 308 | } 309 | 310 | impl serde::Serialize for $sett { 311 | #[inline] 312 | fn serialize(&self, ser: S) -> Result { 313 | as serde::Serialize>::serialize(&self.nets, ser) 314 | } 315 | } 316 | 317 | impl<'de> serde::Deserialize<'de> for $sett { 318 | #[inline] 319 | fn deserialize>(de: D) -> Result { 320 | as serde::Deserialize>::deserialize(de).map(Self::from) 321 | } 322 | } 323 | }; 324 | } 325 | 326 | per_proto!(Ipv4Net(Ipv4Addr; "IPv4 network"); u32(4); Ipv4Set); 327 | per_proto!(Ipv6Net(Ipv6Addr; "IPv6 network"); u128(16); Ipv6Set); 328 | 329 | fn pfx_split(s: &str) -> Result<(&str, u8), NetParseError> { 330 | let i = match s.find('/') { 331 | Some(v) => v, 332 | None => return Err(NetParseError::NoPrefixLen), 333 | }; 334 | let (addr, pfx) = s.split_at(i); 335 | let pfx = u8::from_str(&pfx[1..]).map_err(|_| NetParseError::NoPrefixLen)?; 336 | Ok((addr, pfx)) 337 | } 338 | 339 | #[cfg(test)] 340 | mod test { 341 | use super::{pfx_split, Ipv4Addr, Ipv4Net, Ipv4Set, Ipv6Addr, Ipv6Net}; 342 | use std::str::FromStr; 343 | 344 | #[test] 345 | fn test_pfx_split() { 346 | assert_eq!(pfx_split("asdf/0").unwrap(), ("asdf", 0)); 347 | assert_eq!(pfx_split("asdf/123").unwrap(), ("asdf", 123)); 348 | assert_eq!(pfx_split("asdf/0123").unwrap(), ("asdf", 123)); 349 | assert_eq!(pfx_split("/1").unwrap(), ("", 1)); 350 | assert_eq!(pfx_split("abc/2").unwrap(), ("abc", 2)); 351 | 352 | assert!(pfx_split("no_slash").is_err()); 353 | assert!(pfx_split("asdf/abc").is_err()); 354 | assert!(pfx_split("asdf/0abc").is_err()); 355 | assert!(pfx_split("asdf/0x123").is_err()); 356 | assert!(pfx_split("asdf/12345").is_err()); 357 | } 358 | 359 | #[test] 360 | fn test_net_parse() { 361 | assert_eq!( 362 | Ipv4Net::from_str("192.0.2.5/32").unwrap(), 363 | Ipv4Net { 364 | address: Ipv4Addr::from_str("192.0.2.5").unwrap(), 365 | prefix_len: 32, 366 | } 367 | ); 368 | 369 | assert!(Ipv4Net::from_str("error").is_err()); 370 | 371 | assert!(Ipv4Net::from_str("192.0.2.128/32").is_ok()); 372 | assert!(Ipv4Net::from_str("192.0.2.128/25").is_ok()); 373 | assert!(Ipv4Net::from_str("192.0.2.128/24").is_err()); 374 | assert!(Ipv4Net::from_str("192.0.2.128").is_err()); 375 | } 376 | 377 | #[test] 378 | fn test_net_display() { 379 | assert_eq!( 380 | (Ipv4Net { 381 | address: Ipv4Addr::from_str("192.0.2.0").unwrap(), 382 | prefix_len: 28, 383 | }) 384 | .to_string(), 385 | "192.0.2.0/28" 386 | ); 387 | 388 | assert_eq!( 389 | (Ipv6Net { 390 | address: Ipv6Addr::from_str("::1").unwrap(), 391 | prefix_len: 128, 392 | }) 393 | .to_string(), 394 | "::1/128" 395 | ); 396 | } 397 | 398 | fn disp_set(s: &Ipv4Set) -> String { 399 | s.iter() 400 | .map(Ipv4Net::to_string) 401 | .collect::>() 402 | .join(",") 403 | } 404 | 405 | #[test] 406 | fn test_set_insert() { 407 | let mut s = Ipv4Set::default(); 408 | assert_eq!(disp_set(&s), ""); 409 | 410 | s.insert(Ipv4Net::from_str("192.0.2.7/32").unwrap()); 411 | assert_eq!(disp_set(&s), "192.0.2.7/32"); 412 | 413 | s.insert(Ipv4Net::from_str("192.0.2.5/32").unwrap()); 414 | assert_eq!(disp_set(&s), "192.0.2.5/32,192.0.2.7/32"); 415 | 416 | s.insert(Ipv4Net::from_str("192.0.2.6/32").unwrap()); 417 | assert_eq!(disp_set(&s), "192.0.2.5/32,192.0.2.6/31"); 418 | 419 | let mut s1 = s.clone(); 420 | s1.insert(Ipv4Net::from_str("192.0.2.0/30").unwrap()); 421 | assert_eq!(disp_set(&s1), "192.0.2.0/30,192.0.2.5/32,192.0.2.6/31"); 422 | 423 | s.insert(Ipv4Net::from_str("192.0.2.4/32").unwrap()); 424 | assert_eq!(disp_set(&s), "192.0.2.4/30"); 425 | 426 | s1.insert(Ipv4Net::from_str("192.0.2.4/32").unwrap()); 427 | assert_eq!(disp_set(&s1), "192.0.2.0/29"); 428 | 429 | s.insert(Ipv4Net::from_str("0.0.0.0/0").unwrap()); 430 | assert_eq!(disp_set(&s), "0.0.0.0/0"); 431 | } 432 | 433 | #[test] 434 | fn test_set_from_slice() { 435 | fn s(v: &[&str]) -> String { 436 | disp_set(&Ipv4Set::from( 437 | v.iter() 438 | .cloned() 439 | .map(Ipv4Net::from_str) 440 | .map(Result::unwrap) 441 | .collect::>(), 442 | )) 443 | } 444 | 445 | assert_eq!(s(&[]), ""); 446 | assert_eq!(s(&["192.0.2.7/32"]), "192.0.2.7/32"); 447 | assert_eq!(s(&["192.0.2.7/32", "192.0.2.7/32"]), "192.0.2.7/32"); 448 | assert_eq!( 449 | s(&["192.0.2.7/32", "192.0.2.5/32"]), 450 | "192.0.2.5/32,192.0.2.7/32" 451 | ); 452 | assert_eq!( 453 | s(&["192.0.2.7/32", "192.0.2.5/32", "192.0.2.6/32"]), 454 | "192.0.2.5/32,192.0.2.6/31" 455 | ); 456 | assert_eq!( 457 | s(&[ 458 | "192.0.2.7/32", 459 | "192.0.2.5/32", 460 | "192.0.2.6/32", 461 | "192.0.2.4/32" 462 | ]), 463 | "192.0.2.4/30" 464 | ); 465 | assert_eq!( 466 | s(&["192.0.2.7/32", "192.0.2.6/32", "192.0.2.5/32", "0.0.0.0/0"]), 467 | "0.0.0.0/0" 468 | ); 469 | } 470 | } 471 | -------------------------------------------------------------------------------- /src/proto.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-3.0-or-later 2 | // 3 | // Copyright 2019 Hristo Venev 4 | 5 | use crate::model::{Endpoint, Ipv4Net, Ipv6Net, Key}; 6 | use serde_derive; 7 | use std::time::SystemTime; 8 | 9 | #[derive(Clone, PartialEq, Eq, Debug)] 10 | pub struct Peer { 11 | pub public_key: Key, 12 | pub ipv4: Vec, 13 | pub ipv6: Vec, 14 | pub keepalive: u32, 15 | } 16 | 17 | #[serde(from = "ServerRepr", into = "ServerRepr")] 18 | #[derive(serde_derive::Serialize, serde_derive::Deserialize, Clone, PartialEq, Eq, Debug)] 19 | pub struct Server { 20 | pub peer: Peer, 21 | pub endpoint: Endpoint, 22 | } 23 | 24 | #[derive(serde_derive::Serialize, serde_derive::Deserialize)] 25 | #[serde(deny_unknown_fields)] 26 | struct ServerRepr { 27 | public_key: Key, 28 | #[serde(default)] 29 | ipv4: Vec, 30 | #[serde(default)] 31 | ipv6: Vec, 32 | #[serde(default)] 33 | keepalive: u32, 34 | endpoint: Endpoint, 35 | } 36 | 37 | impl From for ServerRepr { 38 | #[inline] 39 | fn from(v: Server) -> Self { 40 | let Server { peer, endpoint } = v; 41 | let Peer { 42 | public_key, 43 | ipv4, 44 | ipv6, 45 | keepalive, 46 | } = peer; 47 | Self { 48 | public_key, 49 | ipv4, 50 | ipv6, 51 | endpoint, 52 | keepalive, 53 | } 54 | } 55 | } 56 | 57 | impl From for Server { 58 | #[inline] 59 | fn from(v: ServerRepr) -> Self { 60 | let ServerRepr { 61 | public_key, 62 | ipv4, 63 | ipv6, 64 | keepalive, 65 | endpoint, 66 | } = v; 67 | Self { 68 | peer: Peer { 69 | public_key, 70 | ipv4, 71 | ipv6, 72 | keepalive, 73 | }, 74 | endpoint, 75 | } 76 | } 77 | } 78 | 79 | #[derive(serde_derive::Serialize, serde_derive::Deserialize, Clone, PartialEq, Eq, Debug)] 80 | #[serde(from = "RoadWarriorRepr", into = "RoadWarriorRepr")] 81 | pub struct RoadWarrior { 82 | pub peer: Peer, 83 | pub base: Key, 84 | } 85 | 86 | #[derive(serde_derive::Serialize, serde_derive::Deserialize, Clone, PartialEq, Eq, Debug)] 87 | #[serde(deny_unknown_fields)] 88 | pub struct RoadWarriorRepr { 89 | public_key: Key, 90 | #[serde(default)] 91 | ipv4: Vec, 92 | #[serde(default)] 93 | ipv6: Vec, 94 | #[serde(default)] 95 | keepalive: u32, 96 | base: Key, 97 | } 98 | 99 | impl From for RoadWarriorRepr { 100 | #[inline] 101 | fn from(v: RoadWarrior) -> Self { 102 | let RoadWarrior { peer, base } = v; 103 | let Peer { 104 | public_key, 105 | ipv4, 106 | ipv6, 107 | keepalive, 108 | } = peer; 109 | Self { 110 | public_key, 111 | ipv4, 112 | ipv6, 113 | keepalive, 114 | base, 115 | } 116 | } 117 | } 118 | 119 | impl From for RoadWarrior { 120 | #[inline] 121 | fn from(v: RoadWarriorRepr) -> Self { 122 | let RoadWarriorRepr { 123 | public_key, 124 | ipv4, 125 | ipv6, 126 | keepalive, 127 | base, 128 | } = v; 129 | Self { 130 | peer: Peer { 131 | public_key, 132 | ipv4, 133 | ipv6, 134 | keepalive, 135 | }, 136 | base, 137 | } 138 | } 139 | } 140 | 141 | #[derive(Clone, PartialEq, Eq, Debug)] 142 | pub struct SourceConfig { 143 | pub servers: Vec, 144 | pub road_warriors: Vec, 145 | } 146 | 147 | #[derive(serde_derive::Serialize, serde_derive::Deserialize, Clone, PartialEq, Eq, Debug)] 148 | #[serde(from = "SourceRepr", into = "SourceRepr")] 149 | pub struct Source { 150 | pub config: SourceConfig, 151 | pub next: Option<(SystemTime, SourceConfig)>, 152 | } 153 | 154 | impl Source { 155 | pub fn empty() -> Self { 156 | Self { 157 | config: SourceConfig { 158 | servers: vec![], 159 | road_warriors: vec![], 160 | }, 161 | next: None, 162 | } 163 | } 164 | } 165 | 166 | #[derive(serde_derive::Serialize, serde_derive::Deserialize)] 167 | struct SourceNextRepr { 168 | #[serde(default)] 169 | servers: Vec, 170 | #[serde(default)] 171 | road_warriors: Vec, 172 | #[serde(with = "serde_utc")] 173 | update_at: SystemTime, 174 | } 175 | 176 | #[derive(serde_derive::Serialize, serde_derive::Deserialize)] 177 | struct SourceRepr { 178 | #[serde(default)] 179 | servers: Vec, 180 | #[serde(default)] 181 | road_warriors: Vec, 182 | next: Option, 183 | } 184 | 185 | impl From for SourceRepr { 186 | #[inline] 187 | fn from(v: Source) -> Self { 188 | let Source { config, next } = v; 189 | let SourceConfig { 190 | servers, 191 | road_warriors, 192 | } = config; 193 | Self { 194 | servers, 195 | road_warriors, 196 | next: next.map( 197 | #[inline] 198 | |next| { 199 | let (update_at, next) = next; 200 | SourceNextRepr { 201 | servers: next.servers, 202 | road_warriors: next.road_warriors, 203 | update_at, 204 | } 205 | }, 206 | ), 207 | } 208 | } 209 | } 210 | 211 | impl From for Source { 212 | #[inline] 213 | fn from(v: SourceRepr) -> Self { 214 | let SourceRepr { 215 | servers, 216 | road_warriors, 217 | next, 218 | } = v; 219 | Self { 220 | config: SourceConfig { 221 | servers, 222 | road_warriors, 223 | }, 224 | next: next.map( 225 | #[inline] 226 | |next| { 227 | let SourceNextRepr { 228 | servers, 229 | road_warriors, 230 | update_at, 231 | } = next; 232 | ( 233 | update_at, 234 | SourceConfig { 235 | servers, 236 | road_warriors, 237 | }, 238 | ) 239 | }, 240 | ), 241 | } 242 | } 243 | } 244 | 245 | mod serde_utc { 246 | use chrono::{DateTime, SecondsFormat, TimeZone, Utc}; 247 | use serde::*; 248 | use std::fmt; 249 | use std::time::SystemTime; 250 | 251 | pub fn serialize(t: &SystemTime, ser: S) -> Result { 252 | let t = DateTime::::from(*t); 253 | if ser.is_human_readable() { 254 | ser.serialize_str(&t.to_rfc3339_opts(SecondsFormat::Nanos, true)) 255 | } else { 256 | let mut buf = [0_u8; 12]; 257 | // FIXME: arrayref needs to silence this per-expression 258 | #[allow(clippy::eval_order_dependence)] 259 | let (buf_secs, buf_nanos) = mut_array_refs![&mut buf, 8, 4]; 260 | *buf_secs = t.timestamp().to_be_bytes(); 261 | *buf_nanos = t.timestamp_subsec_nanos().to_be_bytes(); 262 | ser.serialize_bytes(&buf) 263 | } 264 | } 265 | 266 | pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result { 267 | if de.is_human_readable() { 268 | struct RFC3339Visitor; 269 | impl<'de> serde::de::Visitor<'de> for RFC3339Visitor { 270 | type Value = SystemTime; 271 | 272 | fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 273 | f.write_str("RFC3339 time") 274 | } 275 | 276 | fn visit_str(self, s: &str) -> Result { 277 | DateTime::parse_from_rfc3339(s) 278 | .map_err(de::Error::custom) 279 | .map(SystemTime::from) 280 | } 281 | } 282 | de.deserialize_str(RFC3339Visitor) 283 | } else { 284 | let mut buf = <[u8; 12]>::deserialize(de)?; 285 | // FIXME: arrayref needs to silence this per-expression 286 | #[allow(clippy::eval_order_dependence)] 287 | let (buf_secs, buf_nanos) = array_refs![&mut buf, 8, 4]; 288 | let secs = i64::from_be_bytes(*buf_secs); 289 | let nanos = u32::from_be_bytes(*buf_nanos); 290 | Ok(Utc.timestamp(secs, nanos).into()) 291 | } 292 | } 293 | } 294 | -------------------------------------------------------------------------------- /src/wg.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-3.0-or-later 2 | // 3 | // Copyright 2019 Hristo Venev 4 | 5 | use crate::{fileutil, model}; 6 | use std::ffi::{OsStr, OsString}; 7 | use std::path::PathBuf; 8 | use std::process::{Command, Stdio}; 9 | use std::{env, fmt, io}; 10 | 11 | pub struct Device { 12 | ifname: OsString, 13 | tmpdir: PathBuf, 14 | } 15 | 16 | impl Device { 17 | #[inline] 18 | pub fn open(ifname: OsString, tmpdir: PathBuf) -> io::Result { 19 | let dev = Self { ifname, tmpdir }; 20 | let _ = dev.get_public_key()?; 21 | Ok(dev) 22 | } 23 | 24 | fn wg_command() -> Command { 25 | let wg = match env::var_os("WG") { 26 | None => OsString::new(), 27 | Some(v) => v, 28 | }; 29 | 30 | Command::new(if wg.is_empty() { 31 | OsStr::new("wg") 32 | } else { 33 | wg.as_os_str() 34 | }) 35 | } 36 | 37 | pub fn get_public_key(&self) -> io::Result { 38 | let mut proc = Self::wg_command(); 39 | proc.stdin(Stdio::null()); 40 | proc.stdout(Stdio::piped()); 41 | proc.arg("show"); 42 | proc.arg(&self.ifname); 43 | proc.arg("public-key"); 44 | 45 | let r = proc.output()?; 46 | if !r.status.success() { 47 | return Err(io::Error::new(io::ErrorKind::Other, "child process failed")); 48 | } 49 | 50 | let mut out = r.stdout; 51 | if out.last().copied() == Some(b'\n') { 52 | out.pop(); 53 | } 54 | model::Key::from_base64(&out) 55 | .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid public key")) 56 | } 57 | 58 | pub fn apply_diff(&mut self, old: &model::Config, new: &model::Config) -> io::Result<()> { 59 | let mut config = String::new(); 60 | 61 | for (pubkey, conf) in &new.peers { 62 | let old_endpoint; 63 | let old_psk; 64 | if let Some(old_peer) = old.peers.get(pubkey) { 65 | if *old_peer == *conf { 66 | continue; 67 | } 68 | old_endpoint = old_peer.endpoint; 69 | old_psk = old_peer.psk.as_ref(); 70 | } else { 71 | old_endpoint = None; 72 | old_psk = None; 73 | } 74 | 75 | use fmt::Write; 76 | write!( 77 | config, 78 | "[Peer]\nPublicKey={}\nPersistentKeepalive={}\nAllowedIPs", 79 | pubkey, conf.keepalive 80 | ) 81 | .unwrap(); 82 | let mut delim = '='; 83 | for ip in &conf.ipv4 { 84 | config.push(delim); 85 | delim = ','; 86 | write!(config, "{}", ip).unwrap(); 87 | } 88 | for ip in &conf.ipv6 { 89 | config.push(delim); 90 | delim = ','; 91 | write!(config, "{}", ip).unwrap(); 92 | } 93 | config.push('\n'); 94 | 95 | if old_endpoint != conf.endpoint { 96 | if let Some(ref endpoint) = conf.endpoint { 97 | write!(config, "Endpoint={}\n", endpoint).unwrap(); 98 | } 99 | } 100 | 101 | if old_psk != conf.psk.as_ref() { 102 | config.push_str("PresharedKey="); 103 | if let Some(psk) = conf.psk.as_ref() { 104 | writeln!(config, "{}", psk).unwrap(); 105 | config.push('\n'); 106 | } else { 107 | config.push_str("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\n"); 108 | } 109 | } 110 | } 111 | 112 | { 113 | let mut config_file = fileutil::Writer::new_in(&self.tmpdir)?; 114 | io::Write::write_all(config_file.file(), config.as_bytes())?; 115 | let config_file = config_file.done(); 116 | 117 | let mut proc = Self::wg_command(); 118 | proc.stdin(Stdio::null()); 119 | proc.stdout(Stdio::null()); 120 | proc.arg("addconf"); 121 | proc.arg(&self.ifname); 122 | proc.arg(config_file.path()); 123 | 124 | let r = proc.status()?; 125 | if !r.success() { 126 | return Err(io::Error::new( 127 | io::ErrorKind::Other, 128 | "`wg setconf' process failed", 129 | )); 130 | } 131 | } 132 | 133 | let mut proc = Self::wg_command(); 134 | let mut any_removed = false; 135 | proc.stdin(Stdio::null()); 136 | proc.stdout(Stdio::null()); 137 | proc.arg("set"); 138 | proc.arg(&self.ifname); 139 | 140 | for pubkey in old.peers.keys() { 141 | if new.peers.contains_key(pubkey) { 142 | continue; 143 | } 144 | any_removed = true; 145 | proc.arg("peer"); 146 | proc.arg(pubkey.to_string()); 147 | proc.arg("remove"); 148 | } 149 | 150 | if any_removed { 151 | let r = proc.status()?; 152 | if !r.success() { 153 | return Err(io::Error::new( 154 | io::ErrorKind::Other, 155 | "`wg set' process failed", 156 | )); 157 | } 158 | } 159 | 160 | Ok(()) 161 | } 162 | } 163 | --------------------------------------------------------------------------------