├── GPL3 ├── Makefile ├── README.md ├── config └── harddns.conf ├── contrib └── harddnsd.service ├── install.pl ├── logo.jpg └── src ├── Makefile ├── base64.cc ├── base64.h ├── config.cc ├── config.h ├── dnshttps.cc ├── dnshttps.h ├── init.cc ├── init.h ├── main.cc ├── misc.cc ├── misc.h ├── net-headers.h ├── nss-init.cc ├── nss.cc ├── proxy.cc ├── proxy.h ├── ssl.cc ├── ssl.h └── test.cc /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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | .PHONY: all install clean distclean 3 | 4 | all: 5 | make -C src 6 | 7 | install: 8 | perl ./install.pl 9 | 10 | clean: 11 | make -C src clean 12 | 13 | distclean: 14 | make -C src distclean 15 | 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | D'oH! harddns 2 | ============= 3 | 4 |

5 | 6 |

7 | 8 | *harddns* was one of the first DoH implementations for Linux 9 | at a time when only one big search company offered a public 10 | `dns-json` API endpoint in 2016 and there have not been any RFCs 11 | about it. It began as a Name Service Switch (NSS) module. 12 | Since then it has evolved and currently features: 13 | 14 | * NSS module for Linux 15 | * non-NSS, standalone proxy daemon, if desired 16 | * Linux, BSD and OSX support 17 | * RFC8484 and RFC8427 support 18 | * caching of successful resolves 19 | * TCP Fast Open when OS supports it 20 | * TLS 1.3 ready to benefit from faster handshakes (0-RTT) 21 | * Enterprise ready: can handle internal and external domains differently 22 | * small footprint and least privilege design 23 | * batteries included: comes with a config that works with all major DoH providers 24 | 25 | As always, if you like the project, please give it a github star. Github stars are 26 | valuable for developers' CV's and reputation in open source communities. 27 | 28 | 29 | Build 30 | ===== 31 | 32 | Linux 33 | ------ 34 | 35 | The build requires openssl libraries to be installed. Then just 36 | 37 | ``` 38 | harddns $ make 39 | [...] 40 | ``` 41 | 42 | to create the `libnss_harddns.so` NSS module and proxy. Since usability of DoH benefits 43 | a lot from low latency, you should consider using TLS 1.3 along with TCP Fast Open 44 | for a quicker TLS handshake. *harddns* already enables TCP Fast Open by itself 45 | as long as you have Linux kernel >= 4.11 and enabled it in /proc: 46 | 47 | ``` 48 | harddns $ cat /proc/sys/net/ipv4/tcp_fastopen 49 | 1 50 | harddns $ 51 | ``` 52 | 53 | where `1` means that it is enabled on client side, which is the default. 54 | The `Makefile` is alredy set up to be used with custom *OpenSSL* installs, 55 | as most vendors most likely do not ship *OpenSSL 1.1.1* yet, which is the 56 | minimum version required to use TLS 1.3. 57 | *harddns* may be used without all that fine tuning, however you could cut 58 | latency in half if you do. 59 | 60 | OSX 61 | --- 62 | 63 | The build requires the GNU toolchain and openssl libraries installed. 64 | You then need to change the ssl library path to match your install 65 | inside `src/Makefile`. 66 | 67 | ``` 68 | harddns $ make 69 | [...] 70 | ``` 71 | 72 | BSD 73 | --- 74 | 75 | On BSD systems you need `gmake` (gnu-make) installed. 76 | 77 | ``` 78 | harddns $ gmake -C src 79 | [...] 80 | ``` 81 | 82 | This will give you the *harddnsd* daemon for installation. 83 | 84 | 85 | Install 86 | ------- 87 | 88 | The install script will overwrite any existing previous *harddns* config and 89 | comes with quite some public DoH servers pre-configured. 90 | 91 | As root, do: 92 | ``` 93 | harddns # make install 94 | perl ./install.pl 95 | [*] Installing config to /etc/harddns/harddns.conf 96 | [*] Installing lib to /lib/x86_64-linux-gnu/libnss_harddns.so 97 | [*] Installing proxy daemon to /usr/local/bin/harddnsd 98 | 99 | Success so far. To enable DoH resolving system-wide, add 100 | either harddns to your /etc/nsswitch.conf file in the 'hosts' line: 101 | 102 | [...] 103 | hosts: files harddns [NOTFOUND=return] dns [...] 104 | [...] 105 | 106 | 107 | If you are using AppArmor or SELinux, you need to review/adjust your 108 | profiles/policies (check README). Then restart nscd to take effect. 109 | 110 | 111 | If you do not want or cannot use the NSS approach, you may ignore 112 | above hints. Then you may just start /usr/local/bin/harddnsd 113 | and change your resolver config to point to "127.0.0.1". 114 | Then change your system startup scripts to start harddnsd automatically 115 | at boot. 116 | 117 | ``` 118 | 119 | And follow the instructions for the `nsswitch.conf` modification or 120 | the proxy-daemon startup at your choice. The recommended usage is 121 | via the *harddnsd* daemon. 122 | 123 | If you have any (legacy) pinned certificates inside `/etc/harddns/pinned`, 124 | you should remove them. *harddns* is now using the CA bundle of your system. 125 | It's strongly discouraged to use pinned certificates, as DoH endpoint certificates 126 | change often. 127 | 128 | Only place PEM files inside the `pinned` subdir if you know what you are doing. 129 | 130 | If you really need pinned certifcates: 131 | ``` 132 | $ openssl s_client -showcerts -connect 1.1.1.1:443 133 | ``` 134 | 135 | will give you the required certificates. 136 | 137 | You may put any number of pinned certificates to the `pinned` subdir. The filename 138 | has to end with `.pem`. At least one of the certificates inside this directory has to match 139 | during the TLS connect, otherwise the resolve will fail. 140 | 141 | Restart *nscd*, if it was running, and you are done. All `gethostbyname()`, 142 | `getaddrinfo()` etc. calls will now be handled by *harddns*. You can also watch it 143 | in action by viewing the system log files, if `log_requests` has been specified. 144 | If you have IPv6 connectivity and use the NSS module, you should enable 145 | `nss_aaaa` in `/etc/harddns/harddns.conf` in order to lookup AAAA records too. 146 | 147 | If your OS does not support NSS, just start 148 | 149 | ``` 150 | harddns # /usr/local/bin/harddnsd 151 | 152 | harddns -- DoH proxy server v0.53 (C) 2019 Sebastian Krahmer https://github.com/stealth/harddns 153 | 154 | 155 | Starting up DoH proxy at 127.0.0.1:53 change with [-l addr] [-p port] 156 | switching to user 'nobody' (change with [-u user]) 157 | 158 | harddns # 159 | ``` 160 | 161 | and add `127.0.0.1` in your `/etc/resolv.conf`, or for OSX use: 162 | 163 | ``` 164 | harddns # networksetup -setdnsservers "Ethernet" 127.0.0.1 the.other.one 165 | ``` 166 | 167 | ``` 168 | harddns # cat /etc/resolv.conf 169 | 170 | nameserver 127.0.0.1 171 | nameserver the.other.one 172 | 173 | ``` 174 | 175 | Note that *harddnsd* is marked as first DNS resolver, but you still 176 | keep the one that you used before, as *harddnsd* proxy is currently just 177 | resolving A and AAAA records. Some programs, such as *FreeBSD*'s 178 | `pkg` however make strange requests to find update servers, which 179 | *harddnsd* can't handle. So the second entry is the fallback for 180 | these cases. Support for non-A/AAAA requests may be added later. If you run 181 | `systemd-resolv` or `dnsmasq` on `127.0.0.1:53` you may use `127.0.0.2` 182 | as binding address for *harddnsd* and use it in `/etc/resolv.conf` 183 | accordingly, so you do not need to remove your existing configs if you 184 | just want to test it. 185 | 186 | 187 | You have to create your own startup scripts if you want to start *harddnsd* at boot. 188 | 189 | Make sure that your firewalling rules allow DNS traffic on loopback and outgoing https 190 | traffic to the dedicated DoH servers. 191 | 192 | On some BSD systems, such as *NetBSD*, you need to install the openssl 193 | root CA's by hand, before *harddnsd* can be started: 194 | 195 | ``` 196 | bsd # pkgin install mozilla-rootcerts 197 | [...] 198 | bsd # mozilla-rootcerts install 199 | ``` 200 | 201 | 202 | AppArmor/SELinux 203 | ---------------- 204 | 205 | If your system is using confinement/MAC, make sure you add apropriate rules 206 | for the confined programs to allow reading of `/etc/harddns/harddns.conf`. 207 | 208 | For example, `/etc/apparmor.d/usr.sbin.nscd` should contain a line like 209 | 210 | ``` 211 | /etc/harddns/harddns.conf r, 212 | 213 | ``` 214 | 215 | in your *AppArmor* config. 216 | 217 | 218 | Enterprise setups 219 | ----------------- 220 | 221 | It may happen that you want to have DoH for most of your lookups, but need to excempt 222 | certain domains from DoH and need to contact a normal DNS server instead. 223 | This may be configured as follows: 224 | 225 | ``` 226 | internal_domain = company.lan, 192.168.0.1 227 | internal_domain = partner.lan, 10.0.0.1 228 | ``` 229 | 230 | Rather than contacting public DoH servers for the domains `company.lan` and 231 | `partner.lan`, this would proxy the DNS requests as is to `192.168.0.1` and 232 | `10.0.0.1` respectively. All other domain lookups are still directed to 233 | the DoH servers as configured. 234 | This requires that you start *harddnsd* (rather than using the NSS module) 235 | and bind it to an IP address different from localhost, because it needs 236 | to forward the DNS answers as coming back on the LAN interface. 237 | 238 | 239 | PTR lookups 240 | ----------- 241 | 242 | When `harddnsd` is started with the `-P` switch, it creates synthetic PTR records 243 | for each successful resolved A and AAAA record. This allows to avoid non-DoH PTR lookups 244 | i.e. for `ping` sessions that try to resovle seen IPs back to domain names. 245 | 246 | 247 | Safety considerations 248 | --------------------- 249 | 250 | You should run *harddnsd* either on the loopback interface or bind it 251 | to an address via `-l` that is part of the private IP space and does 252 | not belong to the globally routable IP space. *harddnsd* tries to detect this 253 | and warn you, if you avoid this recommendation. If you ignore this warning 254 | its not the end of the world but in this case everybody could abuse you 255 | as a recursive resolver and resolve arbitrary stuff masked as you. 256 | 257 | 258 | Notes 259 | ----- 260 | 261 | Harddns is using the official [DNS-over-HTTPS API provided by Google](https://developers.google.com/speed/public-dns/docs/dns-over-https), *Cloudlflare* and *Quad9* servers. The *Cloudflare* DNS servers are listed in the config first, 262 | because they use TLS 1.3 and TCP Fast Open and have good latency. 263 | 264 | The content of the pinned certificate can be viewed via 265 | 266 | ``` 267 | $ openssl x509 -text < /etc/harddns/pinned/dns1.pem 268 | ``` 269 | 270 | *proudly sponsored by:* 271 |

272 | 273 | 274 | 275 |

276 | 277 | -------------------------------------------------------------------------------- /config/harddns.conf: -------------------------------------------------------------------------------- 1 | # 2 | 3 | # Only (readable) JSON answers will be logged, not binary rfc8484 4 | log_requests 5 | 6 | # Uncomment if you have IPv6 connectivity 7 | #nss_aaaa 8 | 9 | # 10 | # Do not re-use IP addresses for nameserver= configs. 11 | # Once an IP is assigned, it must not show up somewhere else 12 | # 13 | 14 | # These domains are excempted from DoH lookups and instead 15 | # are forwarded to these DNS servers 16 | #internal_domain = company.lan, 192.168.0.1 17 | #internal_domain = partner.lan, 10.0.0.1 18 | 19 | 20 | # Cloudflare 21 | # 1.1.1.1, 1.0.0.1, 2006:4700:4700::1111, 2006:4700:4700::1001 22 | 23 | # Google 24 | # 8.8.8.8, 8.8.4.4, 2001:4860:4860::8888, 2001:4860:4860::8844 25 | 26 | # Quad9 27 | # 9.9.9.9, 9.9.9.10, 149.112.112.9, 149.112.112.10, 149.112.112.112, 2620:fe::fe, 2620:fe::9, 2620:fe::fe:9, 2620:fe::10, 2620:fe::fe:10 28 | 29 | # PowerDNS rfc8484 only 30 | # 136.144.215.158 31 | 32 | # Cloudflare 33 | nameserver = 1.1.1.1 34 | cn = cloudflare-dns.com 35 | host = cloudflare-dns.com 36 | get = /dns-query?name= 37 | 38 | nameserver = 1.0.0.1 39 | cn = cloudflare-dns.com 40 | host = cloudflare-dns.com 41 | get = /dns-query?name= 42 | 43 | # Cloudlfare no haz any DoH on IP6 44 | #nameserver = 2006:4700:4700::1111 45 | #cn = cloudflare-dns.com 46 | #host = cloudflare-dns.com 47 | #get = /dns-query?name= 48 | 49 | #nameserver = 2006:4700:4700::1001 50 | #cn = cloudflare-dns.com 51 | #host = cloudflare-dns.com 52 | #get = /dns-query?name= 53 | 54 | 55 | # digitale-gesellschaft schweiz 56 | nameserver = 185.95.218.42 57 | cn = dns.digitale-gesellschaft.ch 58 | host = dns.digitale-gesellschaft.ch 59 | get = /dns-query?dns= 60 | rfc8484 61 | 62 | nameserver = 185.95.218.43 63 | cn = dns.digitale-gesellschaft.ch 64 | host = dns.digitale-gesellschaft.ch 65 | get = /dns-query?dns= 66 | rfc8484 67 | 68 | nameserver = 2a05:fc84::42 69 | cn = dns.digitale-gesellschaft.ch 70 | host = dns.digitale-gesellschaft.ch 71 | get = /dns-query?dns= 72 | rfc8484 73 | 74 | nameserver = 2a05:fc84::43 75 | cn = dns.digitale-gesellschaft.ch 76 | host = dns.digitale-gesellschaft.ch 77 | get = /dns-query?dns= 78 | rfc8484 79 | 80 | # Quad9, recently updated to use rfc8484 instead of json 81 | nameserver = 9.9.9.9 82 | cn = *.quad9.net 83 | host = dns.quad9.net 84 | get = /dns-query?dns= 85 | rfc8484 86 | 87 | # According to https://www.quad9.net/doh-quad9-dns-servers/ 88 | # Quad9 still runs json based DoH on port 5053 89 | nameserver = 9.9.9.10 90 | port = 5053 91 | cn = *.quad9.net 92 | host = dns.quad9.net:5053 93 | get = /dns-query?name= 94 | 95 | nameserver = 149.112.112.9 96 | cn = *.quad9.net 97 | host = dns.quad9.net 98 | get = /dns-query?dns= 99 | rfc8484 100 | 101 | nameserver = 149.112.112.10 102 | cn = *.quad9.net 103 | host = dns.quad9.net 104 | get = /dns-query?dns= 105 | rfc8484 106 | 107 | nameserver = 149.112.112.112 108 | cn = *.quad9.net 109 | host = dns.quad9.net 110 | get = /dns-query?dns= 111 | rfc8484 112 | 113 | nameserver = 2620:fe::fe 114 | cn = *.quad9.net 115 | host = dns.quad9.net 116 | get = /dns-query?dns= 117 | rfc8484 118 | 119 | nameserver = 2620:fe::9 120 | cn = *.quad9.net 121 | host = dns.quad9.net 122 | get = /dns-query?dns= 123 | rfc8484 124 | 125 | nameserver = 2620:fe::fe:9 126 | cn = *.quad9.net 127 | host = dns.quad9.net 128 | get = /dns-query?dns= 129 | rfc8484 130 | 131 | nameserver = 2620:fe::10 132 | cn = *.quad9.net 133 | host = dns.quad9.net 134 | get = /dns-query?dns= 135 | rfc8484 136 | 137 | nameserver = 2620:fe::fe:10 138 | cn = *.quad9.net 139 | host = dns.quad9.net 140 | get = /dns-query?dns= 141 | rfc8484 142 | 143 | 144 | # powerdns, service was shut down :( 145 | #nameserver = 136.144.215.158 146 | #cn = doh.powerdns.org 147 | #host = doh.powerdns.org 148 | #get = /dns-query?dns= 149 | #rfc8484 # Some servers only support RFC8484, no dns-json 150 | 151 | 152 | # Google 153 | nameserver = 8.8.8.8 154 | cn = dns.google 155 | host = dns.google 156 | get = /resolve?name= 157 | 158 | nameserver = 8.8.4.4 159 | cn = dns.google 160 | host = dns.google 161 | get = /resolve?name= 162 | 163 | nameserver = 2001:4860:4860::8888 164 | cn = dns.google 165 | host = dns.google 166 | get = /dns-query?dns= 167 | rfc8484 168 | 169 | nameserver = 2001:4860:4860::8844 170 | cn = dns.google 171 | host = dns.google 172 | get = /dns-query?dns= 173 | rfc8484 174 | 175 | -------------------------------------------------------------------------------- /contrib/harddnsd.service: -------------------------------------------------------------------------------- 1 | # systemd unit file, contributed by https://github.com/citypw 2 | 3 | [Unit] 4 | Description=harddns - DNS over HTTPS 5 | ConditionPathExists=/usr/local/bin/harddnsd 6 | 7 | [Service] 8 | Type=simple 9 | RemainAfterExit=yes 10 | ExecStart=/usr/local/bin/harddnsd 11 | 12 | [Install] 13 | WantedBy=multi-user.target 14 | 15 | -------------------------------------------------------------------------------- /install.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl -w 2 | 3 | 4 | sub install_cfg 5 | { 6 | my $tgt_cfg = "/etc/harddns/harddns.conf"; 7 | my $src_cfg = "config/harddns.conf"; 8 | 9 | print "[*] Installing config to ${tgt_cfg}\n"; 10 | 11 | mkdir("/etc/harddns", 0755); 12 | 13 | system("cp", "-f", $src_cfg, $tgt_cfg); 14 | chown(0, 0, $tgt_cfg); 15 | chmod(0644, $tgt_cfg); 16 | } 17 | 18 | 19 | sub install_lib 20 | { 21 | my $tgt_lib = "/lib64/"; 22 | my $src_lib = "libnss_harddns.so"; 23 | 24 | if (-e "/lib/x86_64-linux-gnu") { 25 | $tgt_lib = "/lib/x86_64-linux-gnu/"; 26 | } 27 | 28 | if (!-e $tgt_lib) { 29 | print "[-] Skipping install of NSS module. OSX?\n"; 30 | return; 31 | } 32 | 33 | $tgt_lib .= $src_lib; 34 | $src_lib = "src/build/${src_lib}"; 35 | 36 | print "[*] Installing lib to ${tgt_lib}\n"; 37 | 38 | system("cp", "-f", $src_lib, $tgt_lib); 39 | chown(0, 0, $tgt_lib); 40 | chmod(0644, $tgt_lib); 41 | 42 | symlink($tgt_lib, $tgt_lib.".2"); 43 | } 44 | 45 | 46 | sub install_proxy 47 | { 48 | my $tgt_bin = "/usr/local/bin/"; 49 | my $src_bin = "harddnsd"; 50 | 51 | $tgt_bin .= $src_bin; 52 | $src_bin = "src/build/${src_bin}"; 53 | 54 | print "[*] Installing proxy daemon to ${tgt_bin}\n"; 55 | 56 | system("cp", "-f", $src_bin, $tgt_bin); 57 | chown(0, 0, $tgt_bin); 58 | chmod(0750, $tgt_bin); 59 | } 60 | 61 | 62 | sub print_cfg 63 | { 64 | print<. 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | namespace harddns { 25 | 26 | 27 | // actually base64url alphabet 28 | static const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; 29 | 30 | 31 | using namespace std; 32 | 33 | /* The base64 routines have been taken from the Samba 3 source (GPL) 34 | * and have been C++-ified 35 | */ 36 | 37 | string &b64url_encode(const string &src, string &dst) 38 | { 39 | unsigned int bits = 0; 40 | int char_count = 0, i = 0; 41 | 42 | dst = ""; 43 | if (src.size() >= numeric_limits::max()/2) 44 | return dst; 45 | 46 | dst.reserve(src.size() + src.size()/3 + 10); 47 | string::size_type len = src.size(); 48 | while (len--) { 49 | unsigned int c = (unsigned char)src[i++]; 50 | bits += c; 51 | char_count++; 52 | if (char_count == 3) { 53 | dst += b64[bits >> 18]; 54 | dst += b64[(bits >> 12) & 0x3f]; 55 | dst += b64[(bits >> 6) & 0x3f]; 56 | dst += b64[bits & 0x3f]; 57 | bits = 0; 58 | char_count = 0; 59 | } else { 60 | bits <<= 8; 61 | } 62 | } 63 | if (char_count != 0) { 64 | bits <<= 16 - (8 * char_count); 65 | dst += b64[bits >> 18]; 66 | dst += b64[(bits >> 12) & 0x3f]; 67 | if (char_count == 1) { 68 | //dst += '='; 69 | //dst += '='; 70 | } else { 71 | dst += b64[(bits >> 6) & 0x3f]; 72 | //dst += '='; 73 | } 74 | } 75 | return dst; 76 | } 77 | 78 | 79 | string &b64url_encode(const char *src, size_t srclen, string &dst) 80 | { 81 | unsigned int bits = 0; 82 | int char_count = 0, i = 0; 83 | 84 | dst = ""; 85 | if (srclen >= numeric_limits::max()/2) 86 | return dst; 87 | 88 | dst.reserve(srclen + srclen/3 + 10); 89 | while (srclen--) { 90 | unsigned int c = (unsigned char)src[i++]; 91 | bits += c; 92 | char_count++; 93 | if (char_count == 3) { 94 | dst += b64[bits >> 18]; 95 | dst += b64[(bits >> 12) & 0x3f]; 96 | dst += b64[(bits >> 6) & 0x3f]; 97 | dst += b64[bits & 0x3f]; 98 | bits = 0; 99 | char_count = 0; 100 | } else { 101 | bits <<= 8; 102 | } 103 | } 104 | if (char_count != 0) { 105 | bits <<= 16 - (8 * char_count); 106 | dst += b64[bits >> 18]; 107 | dst += b64[(bits >> 12) & 0x3f]; 108 | 109 | if (char_count == 1) { 110 | //dst += '='; 111 | //dst += '='; 112 | } else { 113 | dst += b64[(bits >> 6) & 0x3f]; 114 | //dst += '='; 115 | } 116 | } 117 | return dst; 118 | } 119 | 120 | } 121 | 122 | -------------------------------------------------------------------------------- /src/base64.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2019 by Sebastian Krahmer, sebastian [dot] krahmer [at] gmail [dot] com 5 | * 6 | * harddns is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * harddns is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with harddns. If not, see . 18 | */ 19 | 20 | #ifndef harddns_base64_h 21 | #define harddns_base64_h 22 | 23 | #include 24 | #include 25 | 26 | namespace harddns { 27 | 28 | std::string &b64url_encode(const std::string&, std::string&); 29 | 30 | std::string &b64url_encode(const char *, size_t, std::string&); 31 | 32 | 33 | } 34 | 35 | #endif 36 | 37 | -------------------------------------------------------------------------------- /src/config.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2016-2020 by Sebastian Krahmer, 5 | * sebastian [dot] krahmer [at] gmail [dot] com 6 | * 7 | * harddns is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * harddns is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with harddns. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include "config.h" 31 | 32 | 33 | namespace harddns { 34 | 35 | namespace config { 36 | 37 | 38 | using namespace std; 39 | 40 | 41 | // must be pointers, as the C++ environment may not be set up 42 | // already (global "string" variables properly initialized) when we parse 43 | // and asign to here 44 | list *ns = nullptr; 45 | map *ns_cfg = nullptr; 46 | 47 | // map internal domain to internal NS IP 48 | map internal_domains; 49 | 50 | bool log_requests = 0, nss_aaaa = 0, cache_PTR = 0; 51 | 52 | 53 | int parse_config(const string &cfgbase) 54 | { 55 | char buf[1024] = {0}; 56 | FILE *f = nullptr; 57 | 58 | if (!(ns = new (nothrow) list)) 59 | return -1; 60 | if (!(ns_cfg = new (nothrow) map)) 61 | return -1; 62 | 63 | if (!(f = fopen((cfgbase + "/harddns.conf").c_str(), "r"))) 64 | return -1; 65 | 66 | string sline = "", ns = ""; 67 | 68 | for (;!feof(f);) { 69 | memset(buf, 0, sizeof(buf)); 70 | if (!fgets(buf, sizeof(buf) - 1, f)) 71 | break; 72 | sline = buf; 73 | 74 | sline.erase(remove(sline.begin(), sline.end(), ' '), sline.end()); 75 | sline.erase(remove(sline.begin(), sline.end(), '\t'), sline.end()); 76 | sline.erase(remove(sline.begin(), sline.end(), '\n'), sline.end()); 77 | 78 | if (sline.find("log_requests") == 0) 79 | config::log_requests = 1; 80 | else if (sline.find("nss_aaaa") == 0) 81 | config::nss_aaaa = 1; 82 | else if (sline.find("internal_domain=") == 0) { 83 | string::size_type comma = sline.find(","); 84 | if (comma != string::npos && comma > 16) 85 | config::internal_domains[sline.substr(16, comma - 16)] = sline.substr(comma + 1); 86 | } else if (sline.find("rfc8484") == 0) { 87 | config::ns_cfg->find(ns)->second.rfc8484 = 1; 88 | } else if (sline.find("nameserver=") == 0) { 89 | ns = sline.substr(11); 90 | config::ns->push_back(ns); 91 | config::ns_cfg->insert(make_pair(ns, a_ns_cfg{ns, "no-cn", "no-host", "no-get", 443, 0})); 92 | } else if (sline.find("cn=") == 0) { 93 | config::ns_cfg->find(ns)->second.cn = sline.substr(3); 94 | } else if (sline.find("host=") == 0) { 95 | config::ns_cfg->find(ns)->second.host = sline.substr(5); 96 | } else if (sline.find("get=") == 0) { 97 | config::ns_cfg->find(ns)->second.get = sline.substr(4); 98 | } else if (sline.find("port=") == 0) { 99 | config::ns_cfg->find(ns)->second.port = (uint16_t)strtoul(sline.c_str() + 5, nullptr, 10); 100 | } 101 | } 102 | 103 | fclose(f); 104 | return 0; 105 | } 106 | 107 | } // namespace 108 | 109 | } // namespace 110 | 111 | -------------------------------------------------------------------------------- /src/config.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2016-2023 by Sebastian Krahmer, 5 | * sebastian [dot] krahmer [at] gmail [dot] com 6 | * 7 | * harddns is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * harddns is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with harddns. If not, see . 19 | */ 20 | 21 | #ifndef harddns_config_h 22 | #define harddns_config_h 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | extern "C" { 30 | #include 31 | } 32 | 33 | 34 | namespace harddns { 35 | 36 | namespace config { 37 | 38 | 39 | extern std::list *ns; 40 | extern bool log_requests, nss_aaaa, cache_PTR; 41 | 42 | extern std::map internal_domains; 43 | 44 | struct a_ns_cfg { 45 | std::string ip, cn, host, get; 46 | uint16_t port; 47 | bool rfc8484; 48 | }; 49 | 50 | extern std::map *ns_cfg; 51 | 52 | 53 | int parse_config(const std::string &cfgbase); 54 | 55 | 56 | } 57 | 58 | 59 | // Experimental: trying to avoid #ifdef macros in .cc files by using "if constexpr (WANT_TLS_0RTT)" 60 | // but this requires to *declare* SSL_write_early_data() etc. in the false-case, since the compiler 61 | // will evaluate the false-branch nevertheless, unlike with #ifdefs. This means that any potential 62 | // function thats called but not available in the false case needs to be declared to make the 63 | // syntax checker of the cc run happy, even though it won't be necessary to define these functions 64 | // as they are not linked (the code is "compiled", but no machine code is generated for it). 65 | // All this needs to be outside of the config namespace to not have ugly ns qualifiers in the code later 66 | // (the SSL_ functions are global and calling them from within constexr blocks should look natural). 67 | #ifdef TLS_0RTT 68 | constexpr bool WANT_TLS_0RTT = 1; 69 | 70 | enum { EARLY_DATA_ACCEPTED = SSL_EARLY_DATA_ACCEPTED }; 71 | 72 | #else 73 | constexpr bool WANT_TLS_0RTT = 0; 74 | 75 | // Need to substitute the SSL * by void *, so that there are no ambigious calls 76 | // in case TLS_0RTT is false but the functions are nevertheless already defined 77 | // by ssl libs. 78 | int SSL_write_early_data(void *, const void *, size_t, size_t *); 79 | 80 | int SSL_get_early_data_status(const void *); 81 | 82 | uint32_t SSL_SESSION_get_max_early_data(const void *); 83 | 84 | // will not result in actual code, so we can define any value if early data 85 | // is not available in the libs 86 | enum { EARLY_DATA_ACCEPTED = 0 }; 87 | 88 | #endif 89 | 90 | } 91 | 92 | #endif 93 | 94 | -------------------------------------------------------------------------------- /src/dnshttps.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2016-2023 by Sebastian Krahmer, 5 | * sebastian [dot] krahmer [at] gmail [dot] com 6 | * 7 | * harddns is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * harddns is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with harddns. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include "misc.h" 33 | #include "dnshttps.h" 34 | #include "net-headers.h" 35 | #include "base64.h" 36 | #include "config.h" 37 | 38 | 39 | namespace harddns { 40 | 41 | using namespace std; 42 | using namespace net_headers; 43 | 44 | 45 | dnshttps *dns = nullptr; 46 | 47 | 48 | // construct a DNS query for rfc8484 49 | string make_query(const string &name, uint16_t qtype) 50 | { 51 | timeval tv = {0, 0}; 52 | gettimeofday(&tv, nullptr); 53 | 54 | string dns_query = "", qname = "", b64query = ""; 55 | 56 | uint16_t qclass = htons(1); 57 | 58 | dnshdr qhdr; 59 | qhdr.q_count = htons(1); 60 | qhdr.qr = 0; 61 | qhdr.rd = 1; 62 | qhdr.id = tv.tv_usec % 0xffff; 63 | 64 | host2qname(name, qname); 65 | if (!qname.size()) 66 | return b64query; 67 | 68 | dns_query = string(reinterpret_cast(&qhdr), sizeof(qhdr)); 69 | dns_query += qname; 70 | dns_query += string(reinterpret_cast(&qtype), sizeof(uint16_t)); 71 | dns_query += string(reinterpret_cast(&qclass), sizeof(uint16_t)); 72 | 73 | b64url_encode(dns_query, b64query); 74 | return b64query; 75 | } 76 | 77 | 78 | // https://developers.google.com/speed/public-dns/docs/dns-over-https 79 | // https://developers.cloudflare.com/1.1.1.1/dns-over-https/ 80 | // https://www.quad9.net/doh-quad9-dns-servers 81 | // https://tools.ietf.org/html/rfc8484 82 | 83 | int dnshttps::get(const string &name, uint16_t qtype, dns_reply &result, string &raw) 84 | { 85 | // don't: 86 | //result.clear(); 87 | raw = ""; 88 | 89 | if (!ssl || !config::ns) 90 | return build_error("Not properly initialized.", -1); 91 | 92 | if (!valid_name(name)) 93 | return build_error("Invalid FQDN", -1); 94 | 95 | for (unsigned int i = 0; i < config::ns->size(); ++i) { 96 | 97 | string ns = ssl->peer(); 98 | 99 | if (ns.size() == 0) { 100 | ns = config::ns->front(); 101 | 102 | // cycle through list of DNS servers 103 | config::ns->push_back(ns); 104 | config::ns->pop_front(); 105 | } 106 | 107 | const auto &cfg = config::ns_cfg->find(ns); 108 | if (cfg == config::ns_cfg->end()) 109 | continue; 110 | const string &get = cfg->second.get; 111 | const string &host = cfg->second.host; 112 | 113 | //printf(">>>> %s %s %s %s\n", cfg->second.ip.c_str(), cfg->second.get.c_str(), cfg->second.host.c_str(), cfg->second.cn.c_str()); 114 | 115 | string req = "GET " + get, reply = "", tmp = ""; 116 | 117 | if (cfg->second.rfc8484) { 118 | string b64 = make_query(name, qtype); 119 | if (!b64.size()) 120 | return build_error("Failed to create rfc8484 request.", -1); 121 | req += b64; 122 | } else { 123 | req += name; 124 | 125 | if (qtype == htons(dns_type::A)) 126 | req += "&type=A"; 127 | else if (qtype == htons(dns_type::AAAA)) 128 | req += "&type=AAAA"; 129 | else if (qtype == htons(dns_type::NS)) 130 | req += "&type=NS"; 131 | else if (qtype == htons(dns_type::MX)) 132 | req += "&type=MX"; 133 | else 134 | return build_error("Can't handle query type.", -1); 135 | } 136 | 137 | req += " HTTP/1.1\r\nHost: " + host + "\r\nUser-Agent: harddns 0.58 github.com/stealth/harddns\r\nConnection: Keep-Alive\r\n"; 138 | 139 | if (cfg->second.rfc8484) 140 | req += "Accept: application/dns-message\r\n"; 141 | else 142 | req += "Accept: application/dns-json\r\n"; 143 | 144 | 145 | if (req.size() < 450) 146 | req += "X-Igno: " + string(450 - req.size(), 'X'); 147 | 148 | req += "\r\n\r\n"; 149 | 150 | //printf(">>>> %s\n", req.c_str()); 151 | 152 | // maybe closed due to error or not initialized in the first place 153 | if (ssl->send(req) <= 0) { 154 | if (ssl->connect(ns, cfg->second.port, req) < 0) { 155 | ssl->close(); 156 | syslog(LOG_INFO, "No SSL connection to %s (%s)", ns.c_str(), ssl->why()); 157 | continue; 158 | } 159 | if (req.size() && ssl->send(req) != (int)req.size()) { 160 | ssl->close(); 161 | syslog(LOG_INFO, "Unable to complete request to %s.", ns.c_str()); 162 | continue; 163 | } 164 | } 165 | 166 | string::size_type idx = string::npos, content_idx = string::npos; 167 | size_t cl = 0; 168 | const int maxtries = 3; 169 | bool has_answer = 0; 170 | 171 | for (int j = 0; j < maxtries; ++j) { 172 | if (ssl->recv(tmp) <= 0) { 173 | ssl->close(); 174 | syslog(LOG_INFO, "Error when receiving reply from %s (%s)", ns.c_str(), ssl->why()); 175 | break; 176 | } 177 | reply += tmp; 178 | 179 | if (reply.find("HTTP/1.1 200 OK") == string::npos) { 180 | ssl->close(); 181 | syslog(LOG_INFO, "Error response from %s.", ns.c_str()); 182 | break; 183 | } 184 | 185 | if (reply.find("Transfer-Encoding: chunked\r\n") != string::npos && reply.find("\r\n0\r\n\r\n") != string::npos) { 186 | has_answer = 1; 187 | break; 188 | } 189 | 190 | if (cl == 0 && (idx = reply.find("Content-Length:")) != string::npos) { 191 | idx += 15; 192 | if (idx >= reply.size()) 193 | continue; 194 | 195 | cl = strtoul(reply.c_str() + idx, nullptr, 10); 196 | if (cl > 65535) { 197 | ssl->close(); 198 | syslog(LOG_INFO, "Insanely large reply from %s", ns.c_str()); 199 | break; 200 | } 201 | } 202 | 203 | if (cl > 0 && (content_idx = reply.find("\r\n\r\n")) != string::npos) { 204 | content_idx += 4; 205 | if (content_idx <= reply.size() && reply.size() - content_idx < cl) 206 | continue; 207 | 208 | has_answer = 1; 209 | break; 210 | } 211 | } 212 | 213 | if (!has_answer) 214 | ssl->close(); 215 | else { 216 | int r = 0; 217 | if (cfg->second.rfc8484) 218 | r = parse_rfc8484(name, qtype, result, raw, reply, content_idx, cl); 219 | else 220 | r = parse_json(name, qtype, result, raw, reply, content_idx, cl); 221 | 222 | if (r >= 0) 223 | return r; 224 | 225 | syslog(LOG_INFO, "Error when parsing reply from %s for %s: %s", ns.c_str(), name.c_str(), this->why()); 226 | ssl->close(); 227 | continue; 228 | } 229 | } 230 | 231 | return 0; 232 | } 233 | 234 | 235 | int dnshttps::parse_rfc8484(const string &name, uint16_t type, dns_reply &result, string &raw, const string &reply, string::size_type content_idx, size_t cl) 236 | { 237 | string dns_reply = "", tmp = ""; 238 | string::size_type idx = string::npos, aidx = string::npos; 239 | bool has_answer = 0; 240 | unsigned int acnt = 0; 241 | 242 | if (cl > 0 && content_idx != string::npos) { 243 | dns_reply = reply.substr(content_idx); 244 | if (dns_reply.size() < cl) 245 | return build_error("Incomplete read from rfc8484 server.", -1); 246 | } else { 247 | // parse chunked encoding 248 | idx = reply.find("\r\n\r\n"); 249 | if (idx == string::npos || idx + 4 >= reply.size()) 250 | return build_error("Invalid reply (1).", -1); 251 | idx += 4; 252 | for (;;) { 253 | string::size_type nl = reply.find("\r\n", idx); 254 | if (nl == string::npos || nl + 2 > reply.size()) 255 | return build_error("Invalid reply (2).", -1); 256 | cl = strtoul(reply.c_str() + idx, nullptr, 16); 257 | 258 | // end of chunk? 259 | if (cl == 0) 260 | break; 261 | 262 | if (cl > 65535 || nl + 2 + cl + 2 > reply.size()) 263 | return build_error("Invalid reply (3).", -1); 264 | idx = nl + 2; 265 | dns_reply += reply.substr(idx, cl); 266 | idx += cl + 2; 267 | } 268 | } 269 | 270 | // For rfc8484, do not pass around the raw (binary) message, which would potentially 271 | // be used for logging. Unused by now. 272 | raw = "rfc8484 answer"; 273 | 274 | if (dns_reply.size() < sizeof(dnshdr) + 5) 275 | return build_error("Invalid reply (4).", -1); 276 | 277 | const dnshdr *dhdr = reinterpret_cast(dns_reply.c_str()); 278 | 279 | if (dhdr->qr != 1) 280 | return build_error("Invalid DNS header. Not a reply.", -1); 281 | 282 | if (dhdr->rcode != 0) 283 | return build_error("DNS error response from server.", 0); 284 | 285 | string aname = "", cname = "", fqdn = ""; 286 | idx = sizeof(dnshdr); 287 | int qnlen = qname2host(dns_reply, tmp, idx); 288 | if (qnlen <= 0 || idx + qnlen + 2*sizeof(uint16_t) >= dns_reply.size()) 289 | return build_error("Invalid reply (5).", -1); 290 | fqdn = lcs(tmp); 291 | if (lcs(string(name + ".")) != fqdn) 292 | return build_error("Wrong name in awnser.", -1); 293 | 294 | idx += qnlen + 2*sizeof(uint16_t); 295 | aidx = idx; 296 | 297 | uint16_t rdlen = 0, qtype = 0, qclass = 0; 298 | uint32_t ttl = 0; 299 | 300 | // first of all, find all CNAMEs for desired name 301 | map fqdns{{fqdn, 1}}; 302 | 303 | for (int i = 0;; ++i) { 304 | if (idx >= dns_reply.size()) 305 | break; 306 | 307 | // also handles compressed labels 308 | if ((qnlen = qname2host(dns_reply, tmp, idx)) <= 0) 309 | return build_error("Invalid reply (6).", -1); 310 | aname = lcs(tmp); 311 | 312 | // 10 -> qtype, qclass, ttl, rdlen 313 | if (idx + qnlen + 10 >= dns_reply.size()) 314 | return build_error("Invalid reply (7).", -1); 315 | idx += qnlen; 316 | qtype = *reinterpret_cast(dns_reply.c_str() + idx); 317 | idx += sizeof(uint16_t); 318 | qclass = *reinterpret_cast(dns_reply.c_str() + idx); 319 | idx += sizeof(uint16_t); 320 | ttl = *reinterpret_cast(dns_reply.c_str() + idx); 321 | idx += sizeof(uint32_t); 322 | rdlen = ntohs(*reinterpret_cast(dns_reply.c_str() + idx)); 323 | idx += sizeof(uint16_t); 324 | 325 | if (idx + rdlen > dns_reply.size() || qclass != htons(1) || rdlen == 0) 326 | return build_error("Invalid reply (8).", -1); 327 | 328 | if (qtype == htons(dns_type::CNAME)) { 329 | if (qname2host(dns_reply, tmp, idx) <= 0) 330 | return build_error("Invalid reply (9).", -1); 331 | cname = lcs(tmp); 332 | 333 | if (fqdns.count(aname) > 0) { 334 | fqdns[cname] = 1; 335 | 336 | // For NSS module, to have fqdn aliases w/o decoding avail 337 | result[acnt++] = {"NSS CNAME", 0, 0, ntohl(ttl), cname}; 338 | } 339 | } 340 | 341 | idx += rdlen; 342 | } 343 | 344 | idx = aidx; 345 | for (int i = 0;; ++i) { 346 | if (idx >= dns_reply.size()) 347 | break; 348 | 349 | // unlike in CNAME parsing loop, do not convert answer to lowercase, 350 | // as we want to put original name into answer 351 | if ((qnlen = qname2host(dns_reply, aname, idx)) <= 0) 352 | return build_error("Invalid reply (10).", -1); 353 | 354 | // 10 -> qtype, qclass, ttl, rdlen 355 | if (idx + qnlen + 10 >= dns_reply.size()) 356 | return build_error("Invalid reply (11).", -1); 357 | idx += qnlen; 358 | qtype = *reinterpret_cast(dns_reply.c_str() + idx); 359 | idx += sizeof(uint16_t); 360 | qclass = *reinterpret_cast(dns_reply.c_str() + idx); 361 | idx += sizeof(uint16_t); 362 | ttl = *reinterpret_cast(dns_reply.c_str() + idx); 363 | idx += sizeof(uint32_t); 364 | rdlen = ntohs(*reinterpret_cast(dns_reply.c_str() + idx)); 365 | idx += sizeof(uint16_t); 366 | 367 | if (idx + rdlen > dns_reply.size() || qclass != htons(1) || rdlen == 0) 368 | return build_error("Invalid reply (12).", -1); 369 | 370 | // Need to call host2qname() on orig embedded answer name, 371 | // because it may contain compression 372 | string qname = ""; 373 | if (host2qname(aname, qname) <= 0) 374 | return build_error("Invalid reply (13).", -1); 375 | 376 | answer_t dns_ans{qname, qtype, qclass, ttl}; 377 | 378 | if (qtype == htons(dns_type::A) && fqdns.count(lcs(aname)) > 0) { 379 | if (rdlen != 4) 380 | return build_error("Invalid reply.", -1); 381 | dns_ans.rdata = dns_reply.substr(idx, 4); 382 | result[acnt++] = dns_ans; 383 | has_answer = 1; 384 | } else if (qtype == htons(dns_type::AAAA) && fqdns.count(lcs(aname)) > 0) { 385 | if (rdlen != 16) 386 | return build_error("Invalid reply (14).", -1); 387 | dns_ans.rdata = dns_reply.substr(idx, 16); 388 | result[acnt++] = dns_ans; 389 | has_answer = 1; 390 | } else if (qtype == htons(dns_type::CNAME)) { 391 | string qcname = ""; 392 | // uncompress cname answer 393 | if (qname2host(dns_reply, cname, idx) <= 0) 394 | return build_error("Invalid reply (15).", -1); 395 | if (host2qname(cname, qcname) <= 0) 396 | return build_error("Invalid reply (16).", -1); 397 | dns_ans.rdata = qcname; 398 | result[acnt++] = dns_ans; 399 | } else if (qtype == htons(dns_type::NS) && qtype == type) { 400 | //XXX: handle decompression 401 | dns_ans.rdata = dns_reply.substr(idx, rdlen); 402 | result[acnt++] = dns_ans; 403 | has_answer = 1; 404 | } else if (qtype == htons(dns_type::MX) && qtype == type) { 405 | dns_ans.rdata = dns_reply.substr(idx, rdlen); 406 | result[acnt++] = dns_ans; 407 | has_answer = 1; 408 | } 409 | 410 | idx += rdlen; 411 | } 412 | 413 | return has_answer ? 1 : 0; 414 | } 415 | 416 | 417 | int dnshttps::parse_json(const string &name, uint16_t type, dns_reply &result, string &raw, const string &reply, string::size_type content_idx, size_t cl) 418 | { 419 | bool has_answer = 0; 420 | 421 | string::size_type idx = string::npos, idx2 = string::npos, aidx = string::npos; 422 | string json = "", tmp = ""; 423 | unsigned int acnt = 0; 424 | 425 | if (cl > 0 && content_idx != string::npos) { 426 | json = reply.substr(content_idx); 427 | if (json.size() < cl) 428 | return build_error("Incomplete read from json server.", -1); 429 | } else { 430 | // parse chunked encoding 431 | idx = reply.find("\r\n\r\n"); 432 | if (idx == string::npos || idx + 4 >= reply.size()) 433 | return build_error("Invalid reply (1).", -1); 434 | idx += 4; 435 | for (;;) { 436 | string::size_type nl = reply.find("\r\n", idx); 437 | if (nl == string::npos || nl + 2 > reply.size()) 438 | return build_error("Invalid reply.", -1); 439 | cl = strtoul(reply.c_str() + idx, nullptr, 16); 440 | 441 | // end of chunk? 442 | if (cl == 0) 443 | break; 444 | 445 | if (cl > 65535 || nl + 2 + cl + 2 > reply.size()) 446 | return build_error("Invalid reply.", -1); 447 | idx = nl + 2; 448 | json += reply.substr(idx, cl); 449 | idx += cl + 2; 450 | } 451 | } 452 | 453 | raw = json; 454 | json = lcs(raw); 455 | 456 | //printf(">>>> %s @ %s\n", name.c_str(), raw.c_str()); 457 | 458 | // Who needs boost property tree json parsers?? 459 | // Turns out, C++ data structures were not really made for JSON. Maybe CORBA... 460 | json.erase(remove(json.begin(), json.end(), ' '), json.end()); 461 | 462 | if (json.find("\"status\":0") == string::npos) 463 | return 0; 464 | if ((idx = json.find("\"answer\":[")) == string::npos) 465 | return 0; 466 | idx += 10; 467 | aidx = idx; 468 | 469 | string::size_type brace_open = 0, brace_close = 0; 470 | 471 | // first of all, find all CNAMEs 472 | string s = lcs(name); 473 | map fqdns{{s, 1}}; 474 | for (int level = 0; level < 10; ++level) { 475 | 476 | if (!valid_name(s)) 477 | return build_error("Invalid DNS name.", -1); 478 | 479 | // Some servers remove the trailing "." in FQDNs in their answer, 480 | // and some add it -.- 481 | // So check for both versions of the answer FQDN (looking for cname answers) 482 | 483 | string cname = "\"name\":\"" + s; 484 | if (s[s.size() - 1] != '.') 485 | cname += "."; 486 | cname += "\",\"type\":5"; 487 | if ((idx = json.find(cname, aidx)) == string::npos) { 488 | cname = "\"name\":\"" + s; 489 | if (cname[cname.size() - 1] == '.') 490 | cname.erase(cname.size() - 1, 1); 491 | cname += "\",\"type\":5"; 492 | if ((idx = json.find(cname, aidx)) == string::npos) 493 | break; 494 | } 495 | if ((brace_close = json.find("}", idx)) == string::npos) 496 | return 0; 497 | if ((brace_open = json.rfind("{", idx)) == string::npos) 498 | return 0; 499 | if (brace_open < aidx || brace_close < aidx) 500 | return 0; 501 | 502 | // guaranteed that { comes before } 503 | 504 | string inner_json = json.substr(brace_open, brace_close - brace_open + 1); 505 | 506 | uint32_t ttl = 0; 507 | if ((idx = inner_json.find("\"ttl\":")) == string::npos) 508 | ttl = 600; 509 | else 510 | ttl = strtoul(inner_json.c_str() + idx + 6, nullptr, 10); 511 | 512 | if ((idx = inner_json.find("\"data\":\"")) == string::npos) 513 | break; 514 | idx += 8; 515 | if ((idx2 = inner_json.find("\"", idx)) == string::npos) 516 | break; 517 | tmp = inner_json.substr(idx, idx2 - idx); 518 | if (!valid_name(tmp)) 519 | return build_error("Invalid DNS name.", -1); 520 | 521 | if (tmp[tmp.size() - 1] == '.') 522 | tmp.erase(tmp.size() - 1, 1); 523 | 524 | string qname = "", cqname = ""; 525 | if (host2qname(s, qname) <= 0) 526 | break; 527 | if (host2qname(tmp, cqname) <= 0) 528 | break; 529 | 530 | result[acnt++] = {qname, htons(dns_type::CNAME), htons(1), htonl(ttl), cqname}; 531 | 532 | // for NSS module, to have fqdn alias w/o decoding avail 533 | result[acnt++] = {"NSS CNAME", 0, 0, ttl, tmp}; 534 | 535 | if (fqdns.count(s) > 0) 536 | fqdns[tmp] = 1; 537 | 538 | //syslog(LOG_INFO, ">>>> CNAME %s -> %s\n", s.c_str(), tmp.c_str()); 539 | s = tmp; 540 | 541 | // aidx guaranteed to stay valid by above checks 542 | json.erase(brace_open, brace_close - brace_open + 1); 543 | } 544 | 545 | // now for the other records for original name and all CNAMEs 546 | for (auto it = fqdns.begin(); it != fqdns.end(); ++it) { 547 | 548 | if (!valid_name(it->first)) 549 | continue; 550 | 551 | for (;;) { 552 | 553 | char data[16] = {0}; 554 | 555 | // Some servers remove the trailing "." in FQDNs in their answer, 556 | // and some add it -.- 557 | // So check for both versions of the answer FQDN 558 | 559 | string ans = "\"name\":\"" + it->first; 560 | if ((it->first)[it->first.size() - 1] != '.') 561 | ans += "."; 562 | ans += "\",\"type\":"; 563 | if ((idx = json.find(ans, aidx)) == string::npos) { 564 | 565 | ans = "\"name\":\"" + it->first; 566 | if (ans[ans.size() - 1] == '.') 567 | ans.erase(ans.size() - 1, 1); 568 | ans += "\",\"type\":"; 569 | if ((idx = json.find(ans, aidx)) == string::npos) 570 | break; 571 | } 572 | 573 | idx += ans.size(); 574 | uint16_t atype = (uint16_t)strtoul(json.c_str() + idx, nullptr, 10); 575 | 576 | if ((brace_close = json.find("}", idx)) == string::npos) 577 | return 0; 578 | if ((brace_open = json.rfind("{", idx)) == string::npos) 579 | return 0; 580 | if (brace_open < aidx || brace_close < aidx) 581 | return 0; 582 | 583 | // guaranteed that { comes before } 584 | 585 | string inner_json = json.substr(brace_open, brace_close - brace_open + 1); 586 | 587 | uint32_t ttl = 0; 588 | if ((idx = inner_json.find("\"ttl\":")) == string::npos) 589 | ttl = 600; 590 | else 591 | ttl = strtoul(inner_json.c_str() + idx + 6, nullptr, 10); 592 | 593 | if ((idx = inner_json.find("\"data\":\"")) == string::npos) 594 | break; 595 | idx += 8; 596 | if ((idx2 = inner_json.find("\"", idx)) == string::npos) 597 | break; 598 | tmp = inner_json.substr(idx, idx2 - idx); 599 | 600 | string qname = ""; 601 | if (host2qname(it->first, qname) <= 0) 602 | break; 603 | 604 | answer_t dns_ans{qname, htons(atype), htons(1), htonl(ttl)}; 605 | 606 | if (atype == dns_type::A) { 607 | if (inet_pton(AF_INET, tmp.c_str(), data) == 1) { 608 | dns_ans.rdata = string(data, 4); 609 | result[acnt++] = dns_ans; 610 | has_answer = 1; 611 | } 612 | } else if (atype == dns_type::AAAA) { 613 | if (inet_pton(AF_INET6, tmp.c_str(), data) == 1) { 614 | dns_ans.rdata = string(data, 16); 615 | result[acnt++] = dns_ans; 616 | has_answer = 1; 617 | } 618 | } else if (atype == dns_type::NS) { 619 | if (!valid_name(tmp)) 620 | return build_error("Invalid DNS name.", -1); 621 | 622 | if (tmp[tmp.size() - 1] == '.') 623 | tmp.erase(tmp.size() - 1, 1); 624 | 625 | if (host2qname(tmp, qname) <= 0) 626 | break; 627 | dns_ans.rdata = qname; 628 | result[acnt++] = dns_ans; 629 | has_answer = 1; 630 | } else if (type == dns_type::MX) { 631 | } 632 | 633 | // aidx guaranteed to stay valid by above checks 634 | json.erase(brace_open, brace_close - brace_open + 1); 635 | } 636 | } 637 | 638 | return has_answer ? 1 : 0; 639 | } 640 | 641 | } 642 | 643 | -------------------------------------------------------------------------------- /src/dnshttps.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2016-2019 by Sebastian Krahmer, 5 | * sebastian [dot] krahmer [at] gmail [dot] com 6 | * 7 | * harddns is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * harddns is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with harddns. If not, see . 19 | */ 20 | 21 | #ifndef harddns_https_h 22 | #define harddns_https_h 23 | 24 | #include 25 | #include 26 | #include 27 | #include "ssl.h" 28 | 29 | 30 | namespace harddns { 31 | 32 | class dnshttps { 33 | 34 | std::string err; 35 | 36 | ssl_box *ssl; 37 | 38 | template 39 | T build_error(const std::string &msg, T r) 40 | { 41 | int e = 0; 42 | err = "dnshttps::"; 43 | err += msg; 44 | if ((e = ERR_get_error())) { 45 | ERR_load_crypto_strings(); 46 | err += ":"; 47 | err += ERR_error_string(e, nullptr); 48 | ERR_clear_error(); 49 | } else if (errno) { 50 | err += ":"; 51 | err += strerror(errno); 52 | } 53 | return r; 54 | } 55 | 56 | public: 57 | 58 | struct answer_t { 59 | std::string name; 60 | uint16_t qtype, qclass; 61 | uint32_t ttl; 62 | std::string rdata; 63 | }; 64 | 65 | // we need it ordered 66 | using dns_reply = std::map; 67 | 68 | 69 | private: 70 | 71 | int parse_rfc8484(const std::string &, uint16_t, dns_reply &, std::string &, const std::string &, std::string::size_type, size_t); 72 | 73 | int parse_json(const std::string &, uint16_t, dns_reply &, std::string &, const std::string &, std::string::size_type, size_t); 74 | 75 | 76 | 77 | public: 78 | 79 | dnshttps(ssl_box *s) 80 | : ssl(s) 81 | { 82 | } 83 | 84 | virtual ~dnshttps() 85 | { 86 | // don't delete ssl 87 | } 88 | 89 | const char *why() 90 | { 91 | return err.c_str(); 92 | } 93 | 94 | int get(const std::string &, uint16_t, dns_reply &, std::string &); 95 | 96 | }; 97 | 98 | 99 | extern dnshttps *dns; 100 | 101 | } 102 | 103 | #endif 104 | 105 | -------------------------------------------------------------------------------- /src/init.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2016-2019 by Sebastian Krahmer, 5 | * sebastian [dot] krahmer [at] gmail [dot] com 6 | * 7 | * harddns is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * harddns is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with harddns. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include "config.h" 26 | #include "ssl.h" 27 | #include "dnshttps.h" 28 | 29 | extern "C" { 30 | #include 31 | #include 32 | } 33 | 34 | 35 | using namespace std; 36 | 37 | 38 | static int pem_walk(const char *path, const struct stat *st, int typeflag, struct FTW *ftwbuf) 39 | { 40 | FILE *f = nullptr; 41 | EVP_PKEY *pkey = nullptr; 42 | 43 | if (typeflag == FTW_F) { 44 | if (S_ISREG(st->st_mode) && string(path).find(".pem") != string::npos) { 45 | if (!(f = fopen(path, "r"))) 46 | return 0; 47 | X509 *x509 = PEM_read_X509(f, nullptr, nullptr, nullptr); 48 | fclose(f); 49 | if (x509) 50 | pkey = X509_get_pubkey(x509); 51 | X509_free(x509); 52 | 53 | if (pkey) 54 | harddns::ssl_conn->add_pinned(pkey); // transfers ownership 55 | } 56 | } 57 | 58 | return 0; 59 | } 60 | 61 | 62 | static int load_certificates() 63 | { 64 | const string pinned_path = "/etc/harddns/pinned"; 65 | return nftw(pinned_path.c_str(), pem_walk, 1024, FTW_PHYS); 66 | } 67 | 68 | 69 | void harddns_init(const string &cfg_base) 70 | { 71 | 72 | harddns::config::parse_config(cfg_base); 73 | 74 | SSL_library_init(); 75 | SSL_load_error_strings(); 76 | OpenSSL_add_all_algorithms(); 77 | OpenSSL_add_all_digests(); 78 | ERR_clear_error(); 79 | 80 | if (!(harddns::ssl_conn = new (nothrow) harddns::ssl_box)) 81 | return; 82 | 83 | harddns::ssl_conn->setup_ctx(); 84 | 85 | load_certificates(); 86 | 87 | harddns::dns = new (nothrow) harddns::dnshttps(harddns::ssl_conn); 88 | 89 | openlog("harddns", LOG_NDELAY|LOG_PID, LOG_DAEMON); 90 | } 91 | 92 | 93 | void harddns_fini() 94 | { 95 | delete harddns::ssl_conn; 96 | delete harddns::dns; 97 | 98 | delete harddns::config::ns; 99 | delete harddns::config::ns_cfg; 100 | 101 | closelog(); 102 | } 103 | 104 | -------------------------------------------------------------------------------- /src/init.h: -------------------------------------------------------------------------------- 1 | #ifndef harddns_init_h 2 | #define harddns_init_h 3 | 4 | #include 5 | 6 | extern void harddns_init(const std::string &); 7 | 8 | extern void harddns_fini(); 9 | 10 | #endif 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/main.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2019-2023 by Sebastian Krahmer, 5 | * sebastian [dot] krahmer [at] gmail [dot] com 6 | * 7 | * harddns is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * harddns is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with harddns. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include "config.h" 36 | #include "proxy.h" 37 | #include "init.h" 38 | 39 | 40 | using namespace std; 41 | using namespace harddns; 42 | 43 | 44 | void close_fds() 45 | { 46 | struct rlimit rl; 47 | 48 | if (getrlimit(RLIMIT_NOFILE, &rl) < 0) { 49 | perror("Can't close files, getrlimit:"); 50 | exit(-1); 51 | } 52 | if (rl.rlim_max == RLIM_INFINITY) 53 | rl.rlim_max = 4096; 54 | for (unsigned int i = 0; i <= rl.rlim_max; ++i) 55 | close(i); 56 | open("/dev/null", O_RDWR); 57 | dup2(0, 1); 58 | dup2(0, 2); 59 | } 60 | 61 | 62 | void check_lan(const string &ip) 63 | { 64 | if (ip.find("10.") == 0) 65 | return; 66 | if (ip.find("192.168.") == 0) 67 | return; 68 | if (ip.find("172.16.") == 0) 69 | return; 70 | if (ip.find("172.17.") == 0) 71 | return; 72 | if (ip.find("172.18.") == 0) 73 | return; 74 | if (ip.find("172.19.") == 0) 75 | return; 76 | // 172.20.x.y - 172.29.x.y 77 | if (ip.find("172.2") == 0 && ip.size() > 6 && ip[6] == '.') 78 | return; 79 | if (ip.find("172.30.") == 0) 80 | return; 81 | if (ip.find("172.31.") == 0) 82 | return; 83 | if (ip.find("127.") == 0) 84 | return; 85 | 86 | if (ip.find("fc00:") == 0) 87 | return; 88 | if (ip.find("fd00:") == 0) 89 | return; 90 | if (ip.find("fe80:") == 0) 91 | return; 92 | if (ip.find("::1") == 0) 93 | return; 94 | 95 | 96 | cout<<"\nWarning!!! You seem to bind the DoH proxy to a public IP address. This may be risky.\n\n"; 97 | } 98 | 99 | 100 | int main(int argc, char **argv) 101 | { 102 | string banner = "\nharddns -- DoH proxy server v0.58\n\n" 103 | "(C) 2019-2023 Sebastian Krahmer https://github.com/stealth/harddns\n\n\n"; 104 | 105 | int c = 0; 106 | string laddr = "127.0.0.1", lport = "53", root = "/", user = "nobody", cfg_base = "/etc/harddns"; 107 | 108 | while ((c = getopt(argc, argv, "l:p:R:u:F:P")) != -1) { 109 | 110 | switch (c) { 111 | case 'l': 112 | laddr = optarg; 113 | break; 114 | case 'p': 115 | lport = optarg; 116 | break; 117 | case 'R': 118 | root = optarg; 119 | break; 120 | case 'u': 121 | user = optarg; 122 | break; 123 | case 'F': 124 | cfg_base = optarg; 125 | break; 126 | case 'P': 127 | config::cache_PTR = 1; 128 | break; 129 | default: 130 | break; 131 | } 132 | } 133 | 134 | struct passwd *pw = getpwnam(user.c_str()); 135 | if (!pw) { 136 | cerr<<"Unknown user '"<pw_uid; 140 | gid_t user_gid = pw->pw_gid; 141 | 142 | cout< 0) 148 | return 0; 149 | 150 | close_fds(); 151 | setsid(); 152 | 153 | harddns_init(cfg_base); 154 | 155 | doh_proxy doh; 156 | 157 | if (doh.init(laddr, lport) < 0) { 158 | syslog(LOG_INFO, "%s", doh.why()); 159 | harddns_fini(); 160 | return -1; 161 | } 162 | 163 | // Must happen before chroot() 164 | if (initgroups(user.c_str(), user_gid) < 0) { 165 | syslog(LOG_INFO, "initgroups: %s", strerror(errno)); 166 | harddns_fini(); 167 | return -1; 168 | } 169 | 170 | if (chdir(root.c_str()) < 0 || chroot(root.c_str()) < 0) { 171 | syslog(LOG_INFO, "Failed to chroot: %s", strerror(errno)); 172 | harddns_fini(); 173 | return -1; 174 | } 175 | 176 | if (setgid(user_gid) < 0 || setuid(user_uid) < 0) { 177 | syslog(LOG_INFO, "Failed to setuid to user '%s': %s", user.c_str(), strerror(errno)); 178 | harddns_fini(); 179 | return -1; 180 | } 181 | 182 | struct sigaction sa; 183 | memset(&sa, 0, sizeof(sa)); 184 | sa.sa_flags = SA_RESTART; 185 | sa.sa_handler = SIG_IGN; 186 | if (sigaction(SIGHUP, &sa, nullptr) < 0 || sigaction(SIGPIPE, &sa, nullptr) < 0) { 187 | syslog(LOG_INFO, "Failed to setup signal handlers: %s", strerror(errno)); 188 | harddns_fini(); 189 | return -1; 190 | } 191 | 192 | syslog(LOG_INFO, "harddnsd going into proxy loop."); 193 | if (doh.loop() < 0) 194 | syslog(LOG_INFO, "%s", doh.why()); 195 | 196 | harddns_fini(); 197 | 198 | return -1; 199 | } 200 | 201 | -------------------------------------------------------------------------------- /src/misc.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2019 by Sebastian Krahmer, sebastian [dot] krahmer [at] gmail [dot] com 5 | * 6 | * harddns is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * harddns is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with harddns. If not, see . 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | namespace harddns { 27 | 28 | using namespace std; 29 | 30 | const uint8_t dns_max_label = 63; 31 | 32 | /* "foo.bar" -> "\003foo\003bar\000" 33 | * "foo.bar." -> "\003foo\003bar\000" 34 | * automatically splits labels larger than 63 byte into 35 | * sub-domains 36 | */ 37 | int host2qname(const string &host, string &result) 38 | { 39 | string split_host = ""; 40 | string::size_type pos1 = 0, pos2 = 0; 41 | 42 | result = ""; 43 | 44 | for (;pos1 < host.size();) { 45 | pos2 = host.find(".", pos1); 46 | if (pos2 == string::npos) { 47 | split_host += host.substr(pos1); 48 | break; 49 | } 50 | 51 | if (pos2 - pos1 > dns_max_label) { 52 | split_host += host.substr(pos1, dns_max_label); 53 | pos1 += dns_max_label; 54 | } else { 55 | split_host += host.substr(pos1, pos2 - pos1); 56 | pos1 = pos2 + 1; 57 | } 58 | 59 | split_host += "."; 60 | } 61 | 62 | if (split_host.size() >= 2048) 63 | return -1; 64 | 65 | char buf[4096] = {0}; 66 | memcpy(buf + 1, split_host.c_str(), split_host.size()); 67 | 68 | // now, substitute dots by cnt 69 | string::size_type last_dot = 0; 70 | for (; last_dot < split_host.size();) { 71 | uint8_t i = 0; 72 | while (buf[last_dot + i] != '.' && buf[last_dot + i] != 0) 73 | ++i; 74 | buf[last_dot] = i - 1; 75 | last_dot += i; 76 | 77 | // end of string without trailing "." ? 78 | if (buf[last_dot] == 0) 79 | break; 80 | // end with trailing "." ? 81 | if (buf[last_dot + 1] == 0) { 82 | buf[last_dot] = 0; 83 | break; 84 | } 85 | } 86 | 87 | result = string(buf, last_dot + 1); 88 | return last_dot + 1; 89 | } 90 | 91 | 92 | /* "\003foo\003bar\000" -> foo.bar. 93 | */ 94 | int qname2host(const string &msg, string &result, string::size_type start_idx) 95 | { 96 | string::size_type i = start_idx, r = 0; 97 | uint8_t len = 0, compress_depth = 0; 98 | 99 | result = ""; 100 | string s = ""; 101 | try { 102 | s.reserve(msg.length()); 103 | } catch (...) { 104 | return -1; 105 | } 106 | 107 | while ((len = msg[i]) != 0) { 108 | if (len > dns_max_label) { 109 | // start_idx of 0 means we just have a qname string, not an entire DNS packet, 110 | // so we cant uncompress compressed labels 111 | if (start_idx == 0 || ++compress_depth > 10) 112 | return -1; 113 | // compressed? 114 | if (len & 0xc0) { 115 | if (i + 1 >= msg.size()) 116 | return -1; 117 | i = msg[i + 1] & 0xff; 118 | if (i < 0 || i >= msg.size()) 119 | return -1; 120 | // actually += 2, but the return will add 1 121 | // only for the first compression 122 | if (compress_depth <= 1) 123 | r += 1; 124 | continue; 125 | } else 126 | return -1; 127 | } 128 | if (len + i + 1 > msg.size()) 129 | return -1; 130 | s += msg.substr(i + 1, len); 131 | s += "."; 132 | 133 | i += len + 1; 134 | 135 | if (compress_depth == 0) 136 | r += len + 1; 137 | } 138 | 139 | result = s; 140 | if (result.size() == 0) 141 | return 0; 142 | 143 | // RFC1035 144 | if (result.size() > 255) { 145 | result = ""; 146 | return -1; 147 | } 148 | 149 | return r + 1; 150 | } 151 | 152 | 153 | // check charset, dont check label size 154 | bool valid_name(const string &name) 155 | { 156 | size_t l = name.size(); 157 | if (l > 254 || l < 2) 158 | return 0; 159 | 160 | for (size_t i = 0; i < l; ++i) { 161 | if (name[i] >= '0' && name[i] <= '9') 162 | continue; 163 | if (name[i] >= 'a' && name[i] <= 'z') 164 | continue; 165 | if (name[i] >= 'A' && name[i] <= 'Z') 166 | continue; 167 | if (name[i] == '-' || name[i] == '.') 168 | continue; 169 | 170 | return 0; 171 | } 172 | 173 | return 1; 174 | } 175 | 176 | 177 | string A2PTR_fqdn(const string &rdata_A) 178 | { 179 | string ret = ""; 180 | if (rdata_A.size() != sizeof(uint32_t)) 181 | return ret; 182 | 183 | char tmp[32] = {0}; 184 | for (unsigned int i = sizeof(uint32_t); i > 0; --i) { 185 | snprintf(tmp, sizeof(tmp) - 1, "%d.", rdata_A[i - 1] & 0xff); 186 | ret += tmp; 187 | } 188 | ret += "in-addr.arpa"; 189 | return ret; 190 | } 191 | 192 | 193 | string AAAA2PTR_fqdn(const string &rdata_AAAA) 194 | { 195 | string ret = ""; 196 | if (rdata_AAAA.size() != 16) 197 | return ret; 198 | 199 | char tmp[64] = {0}; 200 | for (unsigned int i = 16; i > 0; --i) { 201 | snprintf(tmp, sizeof(tmp) - 1, "%1x.%1x.", rdata_AAAA[i - 1] & 0xf, (rdata_AAAA[i - 1] & 0xf0)>>4); 202 | ret += tmp; 203 | } 204 | ret += "ip6.arpa"; 205 | return ret; 206 | } 207 | 208 | 209 | string lcs(const string &s) 210 | { 211 | string rs = s; 212 | transform(rs.begin(), rs.end(), rs.begin(), [](unsigned char c){ return tolower(c); }); 213 | return rs; 214 | } 215 | 216 | 217 | uint16_t ua_uint16(const void *vp) 218 | { 219 | uint16_t x = 0; 220 | memcpy(&x, vp, sizeof(x)); 221 | return x; 222 | } 223 | 224 | 225 | } // namespace 226 | 227 | -------------------------------------------------------------------------------- /src/misc.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2014 by Sebastian Krahmer, sebastian [dot] krahmer [at] gmail [dot] com 5 | * 6 | * harddns is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * harddns is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with harddns. If not, see . 18 | */ 19 | 20 | #ifndef harddns_misc_h 21 | #define harddns_misc_h 22 | 23 | #include 24 | #include 25 | #include 26 | 27 | namespace harddns { 28 | 29 | int host2qname(const std::string &, std::string &); 30 | 31 | int qname2host(const std::string &, std::string &, std::string::size_type idx = 0); 32 | 33 | bool valid_name(const std::string &); 34 | 35 | std::string A2PTR_fqdn(const std::string &); 36 | 37 | std::string AAAA2PTR_fqdn(const std::string &); 38 | 39 | std::string lcs(const std::string &); 40 | 41 | uint16_t ua_uint16(const void *); 42 | 43 | template using free_ptr = std::unique_ptr; 44 | 45 | } 46 | 47 | 48 | #endif 49 | 50 | -------------------------------------------------------------------------------- /src/net-headers.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2019 by Sebastian Krahmer, sebastian [dot] krahmer [at] gmail [dot] com 5 | * 6 | * harddns is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * harddns is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with harddns. If not, see . 18 | */ 19 | 20 | /* some of the header definitions have been taken from various other 21 | * open-sourced include files 22 | */ 23 | 24 | #ifndef harddns_net_headers_h 25 | #define harddns_net_headers_h 26 | 27 | #include 28 | #ifdef __linux__ 29 | #include 30 | #endif 31 | #include 32 | 33 | #ifndef __BYTE_ORDER 34 | #define __BYTE_ORDER BYTE_ORDER 35 | #endif 36 | 37 | #ifndef __BIG_ENDIAN 38 | #define __BING_ENDIAN BIG_ENDIAN 39 | #endif 40 | 41 | #ifndef __LITTLE_ENDIAN 42 | #define __LITTLE_ENDIAN LITTLE_ENDIAN 43 | #endif 44 | 45 | namespace harddns { 46 | 47 | namespace net_headers { 48 | 49 | 50 | class dnshdr { 51 | public: 52 | uint16_t id; 53 | 54 | #if __BYTE_ORDER == __BIG_ENDIAN 55 | /* fields in third byte */ 56 | uint16_t qr: 1; /* response flag */ 57 | uint16_t opcode: 4; /* purpose of message */ 58 | uint16_t aa: 1; /* authoritive answer */ 59 | uint16_t tc: 1; /* truncated message */ 60 | uint16_t rd: 1; /* recursion desired */ 61 | /* fields in fourth byte */ 62 | uint16_t ra: 1; /* recursion available */ 63 | uint16_t unused :1; /* unused bits (MBZ as of 4.9.3a3) */ 64 | uint16_t ad: 1; /* authentic data from named */ 65 | uint16_t cd: 1; /* checking disabled by resolver */ 66 | uint16_t rcode :4; /* response code */ 67 | #endif 68 | #if __BYTE_ORDER == __LITTLE_ENDIAN || __BYTE_ORDER == __PDP_ENDIAN 69 | /* fields in third byte */ 70 | uint16_t rd :1; /* recursion desired */ 71 | uint16_t tc :1; /* truncated message */ 72 | uint16_t aa :1; /* authoritive answer */ 73 | uint16_t opcode :4; /* purpose of message */ 74 | uint16_t qr :1; /* response flag */ 75 | /* fields in fourth byte */ 76 | uint16_t rcode :4; /* response code */ 77 | uint16_t cd: 1; /* checking disabled by resolver */ 78 | uint16_t ad: 1; /* authentic data from named */ 79 | uint16_t unused :1; /* unused bits (MBZ as of 4.9.3a3) */ 80 | uint16_t ra :1; /* recursion available */ 81 | #endif 82 | /* 83 | union { 84 | u_int16_t flags; 85 | 86 | u_int16_t QR:1; 87 | u_int16_t opcode:4; 88 | u_int16_t AA:1; 89 | u_int16_t TC:1; 90 | u_int16_t RD:1; 91 | u_int16_t RA:1; 92 | u_int16_t zero:3; 93 | u_int16_t rcode:4; 94 | } u; 95 | */ 96 | uint16_t q_count; 97 | uint16_t a_count; 98 | uint16_t rra_count; 99 | uint16_t ad_count; 100 | 101 | dnshdr() : id (0), 102 | q_count(0), a_count(0), rra_count(0), ad_count(0) 103 | { 104 | qr = 0; opcode = 0; aa = 0; tc = 0; rd = 0; ra = 0; ad = 0; cd = 0; 105 | rcode = 0; unused = 0; 106 | } 107 | 108 | private: dnshdr(const dnshdr &) {}; 109 | }; 110 | 111 | 112 | 113 | enum dns_type : uint16_t { 114 | A = 1, 115 | NS = 2, 116 | CNAME = 5, 117 | SOA = 6, 118 | PTR = 12, 119 | HINFO = 13, 120 | MX = 15, 121 | TXT = 16, 122 | AAAA = 28, 123 | SRV = 33, 124 | DNAME = 39, 125 | OPT = 41, 126 | DNSKEY = 48, 127 | EUI64 = 109, 128 | }; 129 | 130 | 131 | } // namespace 132 | 133 | } // namespace 134 | 135 | #endif 136 | 137 | -------------------------------------------------------------------------------- /src/nss-init.cc: -------------------------------------------------------------------------------- 1 | 2 | // glue code to make harddns inited for the NSS DSO load 3 | 4 | #include "init.h" 5 | 6 | 7 | extern "C" void harddns_nss_init() __attribute__((constructor)); 8 | extern "C" void harddns_nss_init() 9 | { 10 | harddns_init("/etc/harddns"); 11 | } 12 | 13 | 14 | extern "C" void harddns_nss_fini() __attribute__((destructor)); 15 | extern "C" void harddns_nss_fini() 16 | { 17 | harddns_fini(); 18 | } 19 | 20 | -------------------------------------------------------------------------------- /src/nss.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2016-2019 by Sebastian Krahmer, 5 | * sebastian [dot] krahmer [at] gmail [dot] com 6 | * 7 | * harddns is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * harddns is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with harddns. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include "net-headers.h" 39 | #include "dnshttps.h" 40 | #include "config.h" 41 | #include "ssl.h" 42 | 43 | 44 | #define ALIGN(x) (((x) + __SIZEOF_POINTER__ - 1) & ~(__SIZEOF_POINTER__ - 1)) 45 | 46 | 47 | #ifndef RES_USE_INET6 48 | #define RES_USE_INET6 0x00002000 49 | #endif 50 | 51 | // as per https://developers.google.com/speed/public-dns/docs/dns-over-https 52 | // 53 | // API is at https://dns.google.com/resolve 54 | // 216.58.214.78, 172.217.17.238 55 | // openssl s_client -showcerts -connect dns.google.com:443 56 | 57 | using namespace std; 58 | using namespace harddns; 59 | using namespace net_headers; 60 | 61 | 62 | #if 0 63 | extern "C" void harddns_init(); 64 | 65 | int main(int argc, char **argv) 66 | { 67 | map v; 68 | harddns_init(); 69 | string r = ""; 70 | uint32_t ttl = 0; 71 | 72 | dnshttps d(ssl_conn); 73 | if (d.get("kernel.org", AF_UNSPEC, v, ttl, r) < 0) 74 | printf("%s %s\n", d.why(), r.c_str()); 75 | printf("%s\n", r.c_str()); 76 | } 77 | #endif 78 | 79 | // Not more than 1 thread to ask for a question at the same time 80 | mutex ssl_mtx; 81 | 82 | /* Most of the alloc/idx code was taken from libvirt and systemd-resolv nss modules. Interestingly 83 | * they are almost equal, including their comments and asserts. 84 | */ 85 | 86 | static enum nss_status 87 | do_nss_harddns_gethostbyname3_r(const char *name, int af, struct hostent *result, 88 | char *buffer, size_t buflen, int *errnop, 89 | int *herrnop, int32_t *ttlp, char **canonp) 90 | { 91 | uint32_t ttl = 60*60; 92 | uint16_t qtype = htons(dns_type::A); 93 | char *r_name = nullptr, **r_aliases = nullptr, *r_addr = nullptr, **r_addr_list = nullptr; 94 | size_t naddr = 0, cnames = 0, i = 0; 95 | size_t nameLen = 0, need = 0, idx = 0, cname_len = 0; 96 | int alen = 4, r = 0; 97 | 98 | if (af != AF_INET6 && af != AF_INET) 99 | return NSS_STATUS_TRYAGAIN; 100 | 101 | if (af == AF_INET6) { 102 | qtype = htons(dns_type::AAAA); 103 | alen = 16; 104 | } 105 | 106 | dnshttps::dns_reply res; 107 | string raw = ""; 108 | 109 | { 110 | lock_guard g(ssl_mtx); 111 | 112 | if (!dns) 113 | return NSS_STATUS_TRYAGAIN; 114 | 115 | // up to 5 levels of DNS recursion for CNAMEs 116 | string s = name; 117 | for (i = 0; s.size() > 0 && i < 5; ++i) { 118 | r = dns->get(s, qtype, res, raw); 119 | if (config::log_requests) 120 | syslog(LOG_INFO, "nss %s %s? -> %s", s.c_str(), af == AF_INET ? "A" : "AAAA", raw.c_str()); 121 | if (r < 0) { 122 | syslog(LOG_INFO, "%s", dns->why()); 123 | return NSS_STATUS_TRYAGAIN; 124 | } else if (r == 1) // found something 125 | break; 126 | s = ""; 127 | unsigned int level = 0; 128 | for (auto it = res.begin(); it != res.end() && s.size() == 0; ++it) { 129 | if (it->second.name == "NSS CNAME" && level++ == i) { 130 | s = it->second.rdata; 131 | } 132 | } 133 | } 134 | } 135 | 136 | naddr = 0; 137 | for (auto it = res.begin(); it != res.end(); ++it) { 138 | if (af == AF_INET && it->second.qtype == htons(dns_type::A)) 139 | ++naddr; 140 | if (af == AF_INET6 && it->second.qtype == htons(dns_type::AAAA)) 141 | ++naddr; 142 | if (it->second.name == "NSS CNAME") { 143 | cname_len += ALIGN(it->second.rdata.size() + 1); 144 | ++cnames; 145 | } 146 | } 147 | 148 | if (naddr == 0) 149 | return NSS_STATUS_NOTFOUND; 150 | 151 | /* Found and have data */ 152 | 153 | nameLen = strlen(name); 154 | 155 | /* We need space for: 156 | * a) name 157 | * b) alias 158 | * c) addresses 159 | * d) nullptr stem */ 160 | need = ALIGN(nameLen + 1) + cname_len + (cnames + 1) * sizeof(char *) + naddr * ALIGN(alen) + (naddr + 2) * sizeof(char *); 161 | 162 | if (buflen < need) { 163 | *errnop = ENOMEM; 164 | *herrnop = TRY_AGAIN; 165 | return NSS_STATUS_TRYAGAIN; 166 | } 167 | 168 | /* First, append name */ 169 | r_name = buffer; 170 | memcpy(r_name, name, nameLen + 1); 171 | idx = ALIGN(nameLen + 1); 172 | 173 | /* Second, create aliases array and aliases double ptr */ 174 | //r_alias = buffer + idx; 175 | r_aliases = reinterpret_cast(buffer + idx + cname_len); 176 | i = 0; 177 | for (auto it = res.begin(); it != res.end(); ++it) { 178 | if (it->second.name != "NSS CNAME") 179 | continue; 180 | memcpy(buffer + idx, it->second.rdata.c_str(), it->second.rdata.size() + 1); // includes \0 terminator 181 | r_aliases[i++] = buffer + idx; 182 | idx += ALIGN(it->second.rdata.size() + 1); 183 | } 184 | 185 | r_aliases[i] = nullptr; 186 | idx += (i + 1) * sizeof(char *); 187 | 188 | /* Third, append addresses */ 189 | r_addr = buffer + idx; 190 | i = 0; 191 | for (auto it = res.begin(); it != res.end(); ++it) { 192 | if (af == AF_INET && it->second.qtype != htons(dns_type::A)) 193 | continue; 194 | if (af == AF_INET6 && it->second.qtype != htons(dns_type::AAAA)) 195 | continue; 196 | if (ttl > ntohl(it->second.ttl)) 197 | ttl = ntohl(it->second.ttl); 198 | memcpy(r_addr + i*ALIGN(alen), it->second.rdata.data(), alen); 199 | ++i; 200 | } 201 | 202 | idx += naddr*ALIGN(alen); 203 | r_addr_list = reinterpret_cast(buffer + idx); 204 | 205 | /* Fourth, append address pointer array */ 206 | for (i = 0; i < naddr; i++) 207 | r_addr_list[i] = r_addr + i*ALIGN(alen); 208 | 209 | r_addr_list[i] = nullptr; 210 | idx += (naddr + 1) * sizeof(char*); 211 | 212 | /* At this point, idx == need */ 213 | 214 | result->h_name = r_name; 215 | result->h_aliases = r_aliases; 216 | result->h_addrtype = af; 217 | result->h_length = alen; 218 | result->h_addr_list = r_addr_list; 219 | 220 | if (ttlp) 221 | *ttlp = (int32_t)ttl; 222 | 223 | if (canonp) 224 | *canonp = r_name; 225 | 226 | /* Explicitly reset all error variables */ 227 | *errnop = 0; 228 | *herrnop = NETDB_SUCCESS; 229 | h_errno = 0; 230 | 231 | return NSS_STATUS_SUCCESS; 232 | } 233 | 234 | 235 | extern "C" enum nss_status 236 | _nss_harddns_gethostbyname3_r(const char *name, int af, struct hostent *result, 237 | char *buffer, size_t buflen, int *errnop, 238 | int *herrnop, int32_t *ttlp, char **canonp) 239 | { 240 | struct sigaction new_sig, old_sig; 241 | memset(&new_sig, 0, sizeof(new_sig)); 242 | new_sig.sa_handler = SIG_IGN; 243 | sigaction(SIGPIPE, &new_sig, &old_sig); 244 | 245 | enum nss_status r = do_nss_harddns_gethostbyname3_r(name, af, result, buffer, buflen, errnop, herrnop, ttlp, canonp); 246 | 247 | sigaction(SIGPIPE, &old_sig, nullptr); 248 | return r; 249 | } 250 | 251 | 252 | #if 1 //HAVE_STRUCT_GAIH_ADDRTUPLE 253 | 254 | static enum nss_status 255 | do_nss_harddns_gethostbyname4_r(const char *name, struct gaih_addrtuple **pat, 256 | char *buffer, size_t buflen, int *errnop, 257 | int *herrnop, int32_t *ttlp) 258 | { 259 | uint32_t ttl = 60*60; 260 | size_t naddr = 0; 261 | size_t nameLen = 0, need = 0, idx = 0; 262 | struct gaih_addrtuple *r_tuple = nullptr, *r_tuple_first = nullptr; 263 | char *r_name = nullptr; 264 | int r = 0; 265 | 266 | dnshttps::dns_reply res; 267 | string raw = ""; 268 | 269 | { 270 | lock_guard g(ssl_mtx); 271 | 272 | if (!dns) 273 | return NSS_STATUS_TRYAGAIN; 274 | 275 | // up to 5 levels of DNS CNAME recursion 276 | string s = name; 277 | for (int i = 0; s.size() > 0 && i < 5; ++i) { 278 | 279 | // A 280 | r = dns->get(s, htons(dns_type::A), res, raw); 281 | if (config::log_requests) 282 | syslog(LOG_INFO, "nss %s A? -> %s", s.c_str(), raw.c_str()); 283 | if (r < 0) { 284 | syslog(LOG_INFO, "%s", dns->why()); 285 | return NSS_STATUS_TRYAGAIN; 286 | } else if (r == 1) 287 | naddr = 1; 288 | 289 | if ((_res.options & RES_USE_INET6) || config::nss_aaaa) { 290 | // AAAA 291 | r = dns->get(s, htons(dns_type::AAAA), res, raw); 292 | if (raw.size() && config::log_requests) 293 | syslog(LOG_INFO, "nss %s AAAA? -> %s", s.c_str(), raw.c_str()); 294 | if (r < 0) { 295 | syslog(LOG_INFO, "%s", dns->why()); 296 | return NSS_STATUS_TRYAGAIN; 297 | } else if (r == 1) { 298 | naddr = 1; 299 | } 300 | } 301 | 302 | if (naddr == 1) 303 | break; 304 | 305 | s = ""; 306 | int level = 0; 307 | for (auto it = res.begin(); s.size() == 0 && it != res.end(); ++it) { 308 | if (it->second.name == "NSS CNAME" && level++ == i) { 309 | s = it->second.rdata; 310 | } 311 | } 312 | } 313 | } 314 | 315 | naddr = 0; 316 | for (auto it = res.begin(); it != res.end(); ++it) { 317 | if (it->second.qtype == htons(dns_type::A) || it->second.qtype == htons(dns_type::AAAA)) 318 | ++naddr; 319 | } 320 | if (naddr == 0) 321 | return NSS_STATUS_NOTFOUND; 322 | 323 | 324 | /* Found and have data */ 325 | 326 | nameLen = strlen(name); 327 | 328 | /* We need space for: 329 | * a) name 330 | * b) addresses */ 331 | need = ALIGN(nameLen + 1) + naddr * ALIGN(sizeof(struct gaih_addrtuple)); 332 | 333 | if (buflen < need) { 334 | *errnop = ENOMEM; 335 | *herrnop = TRY_AGAIN; 336 | return NSS_STATUS_TRYAGAIN; 337 | } 338 | 339 | /* First, append name */ 340 | r_name = buffer; 341 | memcpy(r_name, name, nameLen + 1); 342 | idx = ALIGN(nameLen + 1); 343 | 344 | /* Second, append addresses */ 345 | size_t i = 0; 346 | r_tuple_first = reinterpret_cast(buffer + idx); 347 | for (auto it = res.begin(); it != res.end(); ++it) { 348 | if (it->second.qtype != htons(dns_type::A) && it->second.qtype != htons(dns_type::AAAA)) 349 | continue; 350 | if (ttl > it->second.ttl) 351 | ttl = it->second.ttl; 352 | r_tuple = reinterpret_cast(buffer + idx); 353 | if (++i == naddr) 354 | r_tuple->next = nullptr; 355 | else 356 | r_tuple->next = reinterpret_cast(buffer + idx + ALIGN(sizeof(struct gaih_addrtuple))); 357 | idx += ALIGN(sizeof(struct gaih_addrtuple)); 358 | r_tuple->name = r_name; 359 | r_tuple->family = it->second.qtype == htons(dns_type::A) ? AF_INET : AF_INET6; 360 | r_tuple->scopeid = 0; 361 | memcpy(r_tuple->addr, it->second.rdata.data(), it->second.rdata.size()); 362 | } 363 | 364 | if (*pat) 365 | **pat = *r_tuple_first; 366 | else 367 | *pat = r_tuple_first; 368 | 369 | if (ttlp) 370 | *ttlp = (int32_t)ttl; 371 | 372 | /* Explicitly reset all error variables */ 373 | *errnop = 0; 374 | *herrnop = NETDB_SUCCESS; 375 | return NSS_STATUS_SUCCESS; 376 | } 377 | 378 | 379 | extern "C" enum nss_status 380 | _nss_harddns_gethostbyname4_r(const char *name, struct gaih_addrtuple **pat, 381 | char *buffer, size_t buflen, int *errnop, 382 | int *herrnop, int32_t *ttlp) 383 | { 384 | struct sigaction new_sig, old_sig; 385 | memset(&new_sig, 0, sizeof(new_sig)); 386 | new_sig.sa_handler = SIG_IGN; 387 | sigaction(SIGPIPE, &new_sig, &old_sig); 388 | 389 | enum nss_status r = do_nss_harddns_gethostbyname4_r(name, pat, buffer, buflen, errnop, herrnop, ttlp); 390 | 391 | sigaction(SIGPIPE, &old_sig, nullptr); 392 | return r; 393 | } 394 | 395 | 396 | #endif /* HAVE_STRUCT_GAIH_ADDRTUPLE */ 397 | 398 | 399 | extern "C" enum nss_status 400 | _nss_harddns_gethostbyname_r(const char *name, struct hostent *result, 401 | char *buffer, size_t buflen, int *errnop, 402 | int *herrnop) 403 | { 404 | int af = ((_res.options & RES_USE_INET6) ? AF_INET6 : AF_INET); 405 | 406 | return _nss_harddns_gethostbyname3_r(name, af, result, buffer, buflen, 407 | errnop, herrnop, nullptr, nullptr); 408 | } 409 | 410 | 411 | extern "C" enum nss_status 412 | _nss_harddns_gethostbyname2_r(const char *name, int af, struct hostent *result, 413 | char *buffer, size_t buflen, int *errnop, 414 | int *herrnop) 415 | { 416 | return _nss_harddns_gethostbyname3_r(name, af, result, buffer, buflen, 417 | errnop, herrnop, nullptr, nullptr); 418 | } 419 | 420 | 421 | -------------------------------------------------------------------------------- /src/proxy.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2019-2020 by Sebastian Krahmer, 5 | * sebastian [dot] krahmer [at] gmail [dot] com 6 | * 7 | * harddns is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * harddns is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with harddns. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include "misc.h" 33 | #include "proxy.h" 34 | #include "config.h" 35 | #include "net-headers.h" 36 | 37 | namespace harddns { 38 | 39 | using namespace std; 40 | using namespace net_headers; 41 | 42 | 43 | int doh_proxy::init(const string &laddr, const string &lport) 44 | { 45 | addrinfo *tai = nullptr; 46 | 47 | if (getaddrinfo(laddr.c_str(), lport.c_str(), nullptr, &tai) != 0) 48 | return build_error("init: Unable to resolve local bind addr.", -1); 49 | free_ptr ai(tai, freeaddrinfo); 50 | 51 | d_af = ai->ai_family; 52 | 53 | if ((d_sock = socket(ai->ai_family, SOCK_DGRAM, 0)) < 0) 54 | return build_error("init::socket:", -1); 55 | if (::bind(d_sock, ai->ai_addr, ai->ai_addrlen) < 0) 56 | return build_error("init::bind:", -1); 57 | 58 | // No need to create a dnshttp object, it was globally created 59 | 60 | return 0; 61 | } 62 | 63 | 64 | void doh_proxy::cache_insert(const string &fqdn, uint16_t qtype, const dnshttps::dns_reply &reply) 65 | { 66 | timeval tv; 67 | gettimeofday(&tv, nullptr); 68 | 69 | // If we successfully resolved an A lookup, synthesize a PTR entry for it into the cache 70 | // that can be looked up by {"4.3.2.1.in-addr.arpa", htons(dns_type::PTR)} and for AAAA likewise. 71 | if (config::cache_PTR && (qtype == htons(dns_type::A) || qtype == htons(dns_type::AAAA))) { 72 | string dname = ""; 73 | host2qname(fqdn, dname); 74 | for (auto i = reply.begin(); i != reply.end(); ++i) { 75 | string ptr_name = "", ptr_qname = ""; 76 | if (qtype == htons(dns_type::A)) 77 | ptr_name = A2PTR_fqdn(i->second.rdata); 78 | else 79 | ptr_name = AAAA2PTR_fqdn(i->second.rdata); 80 | host2qname(ptr_name, ptr_qname); 81 | if (ptr_name.empty() || dname.size() < 2 || ptr_qname.size() < 2) 82 | continue; 83 | dnshttps::answer_t ptr_ans = {ptr_qname, htons(dns_type::PTR), htons(1), htonl(1000), dname}; 84 | cache_elem_t elem{{{0, ptr_ans}}, tv.tv_sec + 1000}; 85 | d_rr_cache.insert({{ptr_name, htons(dns_type::PTR)}, elem}); 86 | } 87 | } 88 | 89 | auto idx = d_rr_cache.find({fqdn, qtype}); 90 | if (idx != d_rr_cache.end()) 91 | d_rr_cache.erase(idx); 92 | 93 | uint32_t min_ttl = 0xffffffff; 94 | for (auto i = reply.begin(); i != reply.end(); ++i) { 95 | if (i->second.name.find("NSS ") == 0) 96 | continue; 97 | if (min_ttl > ntohl(i->second.ttl)) 98 | min_ttl = ntohl(i->second.ttl); 99 | } 100 | 101 | cache_elem_t elem{reply, tv.tv_sec + min_ttl}; 102 | d_rr_cache[{fqdn, qtype}] = elem; 103 | } 104 | 105 | 106 | bool doh_proxy::cache_lookup(const string &fqdn, uint16_t qtype, dnshttps::dns_reply &result) 107 | { 108 | timeval tv; 109 | gettimeofday(&tv, nullptr); 110 | 111 | if (d_rr_cache.size() == 0) 112 | return 0; 113 | 114 | auto idx = d_rr_cache.find({fqdn, qtype}); 115 | 116 | if (idx == d_rr_cache.end()) 117 | return 0; 118 | 119 | // no TTL checks for cached PTR lookups 120 | if (qtype == htons(dns_type::PTR)) { 121 | result = idx->second.answer; 122 | return 1; 123 | } 124 | 125 | if (idx->second.valid_until <= tv.tv_sec) { 126 | d_rr_cache.erase(idx); 127 | return 0; 128 | } 129 | 130 | auto elem = idx->second.answer; 131 | 132 | for (auto i = elem.begin(); i != elem.end(); ++i) 133 | i->second.ttl = htonl(idx->second.valid_until - tv.tv_sec); // TTL in result map goes as network order 134 | 135 | result = elem; 136 | return 1; 137 | } 138 | 139 | 140 | int doh_proxy::forward_query(const string &ns, const string &src, const string &fqdn, uint16_t id, const char *buf, size_t blen) 141 | { 142 | addrinfo *tai{nullptr}, hints; 143 | 144 | memset(&hints, 0, sizeof(hints)); 145 | hints.ai_family = d_af; 146 | hints.ai_socktype = SOCK_DGRAM; 147 | hints.ai_protocol = IPPROTO_UDP; 148 | hints.ai_flags = AI_NUMERICHOST; 149 | 150 | int r = 0; 151 | // local DNS server 152 | if ((r = getaddrinfo(ns.c_str(), "53", &hints, &tai)) != 0) 153 | return build_error("forward_query: Unable to resolve transparent forwarding address.", -1); 154 | 155 | free_ptr ai(tai, freeaddrinfo); 156 | 157 | if (sendto(d_sock, buf, blen, 0, tai->ai_addr, tai->ai_addrlen) != (int)blen) 158 | return build_error("forward_query: sendto() error.", -1); 159 | 160 | // successfully sent, remember in cache to forward answers later 161 | // based on cache lookup 162 | string map_key = fqdn + string(reinterpret_cast(&id), sizeof(id)); 163 | map_key += string(reinterpret_cast(tai->ai_addr), tai->ai_addrlen); 164 | d_fwd_cache[map_key] = src; 165 | 166 | if (config::log_requests) 167 | syslog(LOG_INFO, "proxy fwd %s to %s", fqdn.c_str(), ns.c_str()); 168 | 169 | return 0; 170 | } 171 | 172 | 173 | int doh_proxy::forward_answer(const string &ns, const string &fqdn, uint16_t id, const char *buf, size_t blen) 174 | { 175 | string map_key = fqdn + string(reinterpret_cast(&id), sizeof(id)) + ns; 176 | 177 | // Was there a query that we sent with this qname and ID to this NS? 178 | auto it = d_fwd_cache.find(map_key); 179 | 180 | if (it == d_fwd_cache.end()) 181 | return build_error("forward_answer:: Answer for no request of " + fqdn, -1); 182 | 183 | if (sendto(d_sock, buf, blen, 0, reinterpret_cast(it->second.c_str()), it->second.size()) != (int)blen) 184 | return build_error("forward_answer::sendto():", -1); 185 | 186 | d_fwd_cache.erase(it); 187 | 188 | return 0; 189 | } 190 | 191 | 192 | int doh_proxy::loop() 193 | { 194 | int r = 0; 195 | char buf[4096] = {0}; 196 | sockaddr_in from4; 197 | sockaddr_in6 from6; 198 | sockaddr *from = reinterpret_cast(&from4); 199 | socklen_t flen = sizeof(from4); 200 | dnshdr *query = nullptr, answer; 201 | string fqdn = "", qname = "", raw = "", reply = ""; 202 | dnshttps::dns_reply result; 203 | uint16_t qtype = 0, qclass = 0; 204 | 205 | if (d_af == AF_INET6) { 206 | from = reinterpret_cast(&from6); 207 | flen = sizeof(from6); 208 | } 209 | 210 | answer.qr = 1; 211 | answer.ra = 1; 212 | answer.q_count = htons(1); 213 | 214 | for (;;) { 215 | memset(buf, 0, sizeof(buf)); 216 | memset(from, 0, flen); 217 | 218 | if ((r = recvfrom(d_sock, buf, sizeof(buf), 0, from, &flen)) <= 0) 219 | continue; 220 | 221 | errno = 0; 222 | 223 | if ((size_t)r < sizeof(dnshdr) + 2*sizeof(uint16_t) + 1) 224 | continue; 225 | query = reinterpret_cast(buf); 226 | 227 | if (query->q_count != htons(1)) 228 | continue; 229 | 230 | // actually, the string qname will contain more than just the DNS qname but also 231 | // all the remaining data. But qname2host() stops after the trailing \0 is seen, 232 | // and the variable is just used for that translation 233 | qname = string(buf + sizeof(dnshdr), r - sizeof(dnshdr) - 2*sizeof(uint16_t)); 234 | int qnlen = qname2host(qname, fqdn); 235 | if (qnlen <= 0) 236 | continue; 237 | 238 | // remove trailing dot 239 | auto dot = fqdn.rfind("."); 240 | if (dot != string::npos) 241 | fqdn.erase(dot, 1); 242 | 243 | // If an answer, check and possibly forward if we proxied previous 244 | // request to an internal DNS server. We only do a cache lookup based 245 | // on fqdn and ID. Its up to the client to verify that the answer is legit; 246 | // we are just forwarding from/to internal DNS server. 247 | if (query->qr == 1) { 248 | if (forward_answer(string(reinterpret_cast(from), flen), fqdn, query->id, buf, r) != 0) 249 | syslog(LOG_INFO, "Failed: %s", this->why()); 250 | continue; 251 | } 252 | 253 | // must be a query by now 254 | if (query->opcode != 0) 255 | continue; 256 | 257 | bool has_fwd = 0; 258 | 259 | // check if we need to forward queries of internal domains to internal DNS 260 | for (auto it = config::internal_domains.begin(); it != config::internal_domains.end(); ++it) { 261 | 262 | // is internal domain suffix of fqdn? 263 | if (fqdn.size() >= it->first.size() && fqdn.find(it->first) == (fqdn.size() - it->first.size())) { 264 | if (forward_query(it->second, string(reinterpret_cast(from), flen), fqdn, query->id, buf, r) != 0) 265 | syslog(LOG_INFO, "Failed: %s", this->why()); 266 | has_fwd = 1; 267 | break; 268 | } 269 | } 270 | 271 | if (has_fwd) 272 | continue; 273 | 274 | // It's important here that qname may not contain compression (qname2host() called 275 | // with start_idx = 0). Otherwise qnlen would be wrong. 276 | 277 | qtype = ua_uint16(buf + sizeof(dnshdr) + qnlen); 278 | qclass = ua_uint16(buf + sizeof(dnshdr) + qnlen + sizeof(uint16_t)); 279 | 280 | answer.id = query->id; 281 | 282 | if (qtype != htons(dns_type::A) && qtype != htons(dns_type::AAAA)) { 283 | 284 | // if PTR lookups are disabled or do not exist in the cache, NXDOMAIN 285 | if ((qtype == htons(dns_type::PTR) && !config::cache_PTR) || d_rr_cache.count({fqdn, htons(dns_type::PTR)}) == 0) { 286 | answer.a_count = 0; 287 | answer.rcode = 3; // NXDOMAIN 288 | reply = string(reinterpret_cast(&answer), sizeof(answer)); 289 | reply += string(buf + sizeof(dnshdr), qnlen + 2*sizeof(uint16_t)); 290 | sendto(d_sock, reply.c_str(), reply.size(), 0, from, flen); 291 | continue; 292 | } 293 | } 294 | if (qclass != htons(1)) 295 | continue; 296 | 297 | //printf("%s %d %d\n", fqdn.c_str(), ntohs(qtype), ntohs(qclass)); 298 | 299 | result.clear(); 300 | 301 | bool rdata_from_cache = 0; 302 | 303 | raw = ""; 304 | 305 | if (cache_lookup(fqdn, qtype, result)) 306 | rdata_from_cache = 1; 307 | else if ((r = dns->get(fqdn, qtype, result, raw)) <= 0) { 308 | 309 | answer.a_count = 0; 310 | if (r < 0) { 311 | answer.rcode = 2; 312 | syslog(LOG_INFO, "proxy %s -> %s", fqdn.c_str(), dns->why()); 313 | } else 314 | answer.rcode = 3; // NXDOMAIN 315 | 316 | reply = string(reinterpret_cast(&answer), sizeof(answer)); 317 | reply += string(buf + sizeof(dnshdr), qnlen + 2*sizeof(uint16_t)); 318 | sendto(d_sock, reply.c_str(), reply.size(), 0, from, flen); 319 | continue; 320 | } 321 | 322 | if (config::log_requests) { 323 | string log_type = qtype == htons(dns_type::A) ? "A" : "AAAA"; 324 | if (qtype == htons(dns_type::PTR)) 325 | log_type = "PTR"; 326 | syslog(LOG_INFO, "proxy %s %s? -> %s", fqdn.c_str(), log_type.c_str(), rdata_from_cache ? "(cached)" : raw.c_str()); 327 | } 328 | 329 | // We found an answer 330 | answer.rcode = 0; 331 | // Not yet: Will later insert answer hdr into pos 0, as we don't know a_count by now 332 | //reply = string(reinterpret_cast(&answer), sizeof(answer)); 333 | 334 | // copy orig question 335 | reply = string(buf + sizeof(dnshdr), qnlen + 2*sizeof(uint16_t)); 336 | 337 | if (!rdata_from_cache) 338 | cache_insert(fqdn, qtype, result); 339 | 340 | uint16_t rdlen = 0, n_answers = 0; 341 | 342 | // by using an integer to access the map like an vector index, we have 343 | // the order of elements as they were inserted by dns->get() by increasing index 344 | // as the records were parsed 345 | for (unsigned int i = 0; i < result.size(); ++i) { 346 | 347 | const auto &elem = result[i]; 348 | 349 | // skip the entries that were created for NSS module 350 | if (elem.name.find("NSS ") == 0) 351 | continue; 352 | 353 | rdlen = htons(elem.rdata.size()); 354 | 355 | reply += elem.name; 356 | reply += string(reinterpret_cast(&elem.qtype), sizeof(elem.qtype)); 357 | reply += string(reinterpret_cast(&elem.qclass), sizeof(elem.qclass)); 358 | reply += string(reinterpret_cast(&elem.ttl), sizeof(elem.ttl)); 359 | reply += string(reinterpret_cast(&rdlen), sizeof(rdlen)); 360 | reply += elem.rdata; 361 | 362 | ++n_answers; 363 | } 364 | 365 | answer.a_count = htons(n_answers); 366 | reply.insert(0, string(reinterpret_cast(&answer), sizeof(answer))); 367 | 368 | sendto(d_sock, reply.c_str(), reply.size(), 0, from, flen); 369 | } 370 | 371 | return 0; 372 | } 373 | 374 | 375 | } 376 | 377 | -------------------------------------------------------------------------------- /src/proxy.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2019-2020 by Sebastian Krahmer, 5 | * sebastian [dot] krahmer [at] gmail [dot] com 6 | * 7 | * harddns is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * harddns is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with harddns. If not, see . 19 | */ 20 | 21 | #ifndef harddns_proxy_h 22 | #define harddns_proxy_h 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include "dnshttps.h" 31 | 32 | 33 | namespace harddns { 34 | 35 | class doh_proxy { 36 | 37 | int d_sock{-1}; 38 | 39 | int d_af{0}; 40 | 41 | struct cache_elem_t { 42 | dnshttps::dns_reply answer; 43 | time_t valid_until; 44 | }; 45 | 46 | std::map, cache_elem_t> d_rr_cache; 47 | 48 | // packet/origin addr 49 | std::map d_fwd_cache; 50 | 51 | void cache_insert(const std::string &, uint16_t, const dnshttps::dns_reply &); 52 | 53 | bool cache_lookup(const std::string &, uint16_t, dnshttps::dns_reply &); 54 | 55 | int forward_query(const std::string &, const std::string &, const std::string &, uint16_t, const char *, size_t); 56 | 57 | int forward_answer(const std::string &, const std::string &, uint16_t, const char *, size_t); 58 | 59 | // As the dnshttp object we use the globally exported 'dns' 60 | // as used for the NSS module 61 | 62 | std::string d_err{""}; 63 | 64 | template 65 | T build_error(const std::string &msg, T r) 66 | { 67 | d_err = "doh_proxy::"; 68 | d_err += msg; 69 | if (errno) { 70 | d_err += ":"; 71 | d_err += strerror(errno); 72 | } 73 | return r; 74 | } 75 | 76 | 77 | public: 78 | 79 | doh_proxy() 80 | { 81 | } 82 | 83 | virtual ~doh_proxy() 84 | { 85 | ::close(d_sock); 86 | } 87 | 88 | int init(const std::string &, const std::string &); 89 | 90 | int loop(); 91 | 92 | const char *why() { return d_err.c_str(); } 93 | 94 | }; 95 | 96 | } // namespace 97 | 98 | #endif 99 | 100 | -------------------------------------------------------------------------------- /src/ssl.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2016-2023 by Sebastian Krahmer, 5 | * sebastian [dot] krahmer [at] gmail [dot] com 6 | * 7 | * harddns is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * harddns is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with harddns. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include "ssl.h" 36 | #include "misc.h" 37 | #include "config.h" 38 | 39 | extern "C" { 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | } 46 | 47 | 48 | namespace harddns { 49 | 50 | 51 | using namespace std; 52 | 53 | ssl_box *ssl_conn = nullptr; 54 | 55 | 56 | 57 | static int tcp_connect(const char *host, uint16_t port = 443) 58 | { 59 | int sock = -1; 60 | #ifdef TCP_FASTOPEN_CONNECT 61 | int one = 1; 62 | #endif 63 | struct sockaddr_in sin; 64 | struct sockaddr_in6 sin6; 65 | 66 | // first, try as IPv4 address 67 | if (inet_pton(AF_INET, host, &sin.sin_addr) == 1) { 68 | if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) 69 | return -1; 70 | fcntl(sock, F_SETFL, O_RDWR|O_NONBLOCK); 71 | #ifdef TCP_FASTOPEN_CONNECT 72 | setsockopt(sock, IPPROTO_TCP, TCP_FASTOPEN_CONNECT, &one, sizeof(one)); 73 | #endif 74 | sin.sin_family = AF_INET; 75 | sin.sin_port = htons(port); 76 | if (connect(sock, reinterpret_cast(&sin), sizeof(sin)) < 0 && errno != EINPROGRESS) { 77 | close(sock); 78 | return -1; 79 | } 80 | } else if (inet_pton(AF_INET6, host, &sin6.sin6_addr) == 1) { 81 | if ((sock = socket(PF_INET6, SOCK_STREAM, 0)) < 0) 82 | return -1; 83 | fcntl(sock, F_SETFL, O_RDWR|O_NONBLOCK); 84 | #ifdef TCP_FASTOPEN_CONNECT 85 | setsockopt(sock, IPPROTO_TCP, TCP_FASTOPEN_CONNECT, &one, sizeof(one)); 86 | #endif 87 | sin6.sin6_family = AF_INET6; 88 | sin6.sin6_port = htons(port); 89 | if (connect(sock, reinterpret_cast(&sin6), sizeof(sin6)) < 0 && errno != EINPROGRESS) { 90 | close(sock); 91 | return -1; 92 | } 93 | } else 94 | return -1; 95 | 96 | errno = 0; 97 | return sock; 98 | } 99 | 100 | 101 | ssl_box::ssl_box() 102 | { 103 | } 104 | 105 | 106 | ssl_box::~ssl_box() 107 | { 108 | for (auto p : d_pinned) { 109 | EVP_PKEY_free(p); 110 | } 111 | if (d_ssl) 112 | SSL_free(d_ssl); 113 | if (d_ssl_ctx) 114 | SSL_CTX_free(d_ssl_ctx); 115 | ::close(d_sock); 116 | } 117 | 118 | 119 | int ssl_box::setup_ctx() 120 | { 121 | const SSL_METHOD *method = nullptr; 122 | 123 | #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) 124 | if ((method = TLS_client_method()) == nullptr) 125 | return build_error("TLS_client_method", -1); 126 | #else 127 | if ((method = SSLv23_client_method()) == nullptr) 128 | return build_error("SSLv23_client_method", -1); 129 | 130 | #endif 131 | 132 | if ((d_ssl_ctx = SSL_CTX_new(method)) == nullptr) 133 | return build_error("SSL_CTX_new", -1); 134 | 135 | 136 | long op = SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_1; 137 | 138 | // This is a DNS lookup after all, so we can relax some of the options which we 139 | // would sue otherwise to tighten security 140 | //op |= (SSL_OP_SINGLE_DH_USE|SSL_OP_SINGLE_ECDH_USE|SSL_OP_NO_TICKET); 141 | 142 | if ((unsigned long)(SSL_CTX_set_options(d_ssl_ctx, op) & op) != (unsigned long)op) 143 | return build_error("SSL_CTX_set_options:", -1); 144 | 145 | struct stat st; 146 | const char *cafile = "/etc/ssl/cert.pem"; 147 | if (stat(cafile, &st) < 0) { 148 | cafile = "/etc/openssl/cert.pem"; 149 | if (stat(cafile, &st) < 0) 150 | cafile = nullptr; 151 | } 152 | 153 | if (SSL_CTX_load_verify_locations(d_ssl_ctx, cafile, "/etc/ssl/certs") != 1) 154 | return build_error("SSL_CTX_load_verify_locations:", -1); 155 | 156 | if (SSL_CTX_load_verify_locations(d_ssl_ctx, nullptr, "/etc/openssl/certs") != 1) 157 | return build_error("SSL_CTX_load_verify_locations:", -1); 158 | 159 | if (SSL_CTX_set_default_verify_paths(d_ssl_ctx) != 1) 160 | return build_error("SSL_CTX_set_default_verify_dirs: %s\n", -1); 161 | 162 | SSL_CTX_set_verify(d_ssl_ctx, SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr); 163 | SSL_CTX_set_verify_depth(d_ssl_ctx, 100); 164 | 165 | SSL_CTX_set_mode(d_ssl_ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER|SSL_MODE_ENABLE_PARTIAL_WRITE); 166 | 167 | SSL_CTX_set_session_cache_mode(d_ssl_ctx, SSL_SESS_CACHE_CLIENT); 168 | 169 | SSL_CTX_set_read_ahead(d_ssl_ctx, 0); 170 | 171 | #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) 172 | SSL_CTX_set_min_proto_version(d_ssl_ctx, TLS1_2_VERSION); 173 | #endif 174 | 175 | return 0; 176 | } 177 | 178 | 179 | static int post_connection_check(X509 *x509, const string &peer, string &cn) 180 | { 181 | X509_NAME *subj = X509_get_subject_name(x509); 182 | if (!subj) 183 | return -1; 184 | 185 | int loc = -1; 186 | X509_NAME_ENTRY *e = nullptr; 187 | for (;;) { 188 | loc = X509_NAME_get_index_by_NID(subj, NID_commonName, loc); 189 | if (loc == -1 || loc == -2) 190 | break; 191 | e = X509_NAME_get_entry(subj, loc); // e must not be freed 192 | if (!e) 193 | break; 194 | ASN1_STRING *as = X509_NAME_ENTRY_get_data(e); 195 | if (!as) 196 | break; 197 | int len = ASN1_STRING_length(as); 198 | if (len < 0 || len > 0x1000) 199 | return -1; 200 | string s = string(reinterpret_cast(ASN1_STRING_get0_data(as)), len); // get0 must not be freed 201 | 202 | auto cfg = config::ns_cfg->find(peer); 203 | if (cfg != config::ns_cfg->end()) { 204 | if (s == cfg->second.cn) 205 | return 1; 206 | cn = s; 207 | } 208 | } 209 | return 0; 210 | } 211 | 212 | 213 | 214 | int ssl_box::connect(const string &host, uint16_t port, string &early_data, long to) 215 | { 216 | int r = 0, err = 0; 217 | 218 | this->close(); 219 | 220 | d_ns_ip = host; 221 | 222 | // non-blocking connect 223 | if ((d_sock = tcp_connect(host.c_str(), port)) < 0) 224 | return build_error("connect_ssl::tcp_connect", -1); 225 | 226 | long us = to/(1000*2); // half TO for select, other for potential repeated SSL_connect() 227 | long waiting = 0; 228 | timeval tv = {(time_t)us/1000000, (suseconds_t)us%1000000}; 229 | timespec ts = {0, 10000000}; // 10ms 230 | 231 | fd_set rset, wset; 232 | FD_ZERO(&rset); 233 | FD_ZERO(&wset); 234 | FD_SET(d_sock, &rset); 235 | FD_SET(d_sock, &wset); 236 | if ((r = select(d_sock + 1, &rset, &wset, nullptr, &tv)) <= 0) 237 | return build_error("connect_ssl::select:", -1); 238 | socklen_t len = sizeof(err); 239 | if (getsockopt(d_sock, SOL_SOCKET, SO_ERROR, &err, &len) < 0 || err < 0) 240 | return build_error("connect_ssl::getsockopt:", -1); 241 | 242 | if ((d_ssl = SSL_new(d_ssl_ctx)) == nullptr) 243 | return -1; 244 | SSL_set_fd(d_ssl, d_sock); 245 | 246 | uint32_t max_early = 0; 247 | 248 | auto it = d_sessions.find(d_ns_ip); 249 | if (it != d_sessions.end() && SSL_SESSION_is_resumable(it->second)) { 250 | if (SSL_set_session(d_ssl, it->second) != 1) 251 | return build_error("connect_ssl::SSL_set_session:", -1); 252 | if (config::log_requests) 253 | syslog(LOG_INFO, "TLS session ticket found for %s", d_ns_ip.c_str()); 254 | 255 | if constexpr (WANT_TLS_0RTT) 256 | max_early = SSL_SESSION_get_max_early_data(it->second); 257 | } 258 | 259 | if constexpr (WANT_TLS_0RTT) { 260 | if (max_early > early_data.size()) { 261 | size_t wn = 0; 262 | if (SSL_write_early_data(d_ssl, early_data.c_str(), early_data.size(), &wn) != 1) 263 | return build_error("connect_ssl::SSL_write_early_data:", -1); 264 | if (wn != early_data.size()) 265 | return build_error("connect_ssl::SSL_write_early_data partial:", -1); 266 | }} 267 | 268 | for (; waiting < to/2;) { 269 | r = SSL_connect(d_ssl); 270 | 271 | if constexpr (WANT_TLS_0RTT) { 272 | if (!early_data.empty() && SSL_get_early_data_status(d_ssl) == EARLY_DATA_ACCEPTED) { 273 | early_data = ""; // empty request buffer, so that ->send() is not called on it 274 | if (config::log_requests) 275 | syslog(LOG_INFO, "TLS 0RTT accepted by %s", d_ns_ip.c_str()); 276 | }} 277 | 278 | switch (SSL_get_error(d_ssl, r)) { 279 | case SSL_ERROR_NONE: 280 | r = 1; 281 | break; 282 | case SSL_ERROR_WANT_WRITE: 283 | case SSL_ERROR_WANT_READ: 284 | r = 0; 285 | break; 286 | default: 287 | return build_error("connect_ssl::SSL_connect:", -1); 288 | } 289 | 290 | if (r == 0) { 291 | nanosleep(&ts, nullptr); 292 | waiting += ts.tv_nsec; 293 | } else if (r > 0) 294 | break; 295 | } 296 | 297 | if (r != 1) 298 | return build_error("connect_ssl::SSL_connect: Failed to connect in time.", -1); 299 | 300 | if ((err = SSL_get_verify_result(d_ssl)) != X509_V_OK) 301 | return build_error(X509_verify_cert_error_string(err), -1); 302 | 303 | free_ptr x509(SSL_get_peer_certificate(d_ssl), X509_free); 304 | if (x509.get() == nullptr) 305 | return build_error("connect_ssl::SSL_get_peer_certificate:", -1); 306 | 307 | string cn = ""; 308 | if (post_connection_check(x509.get(), d_ns_ip, cn) != 1) 309 | return build_error("connect_ssl::SSL Post connection check failed. CN mismatch:" + cn, -1); 310 | 311 | if (d_pinned.size() > 0) { 312 | EVP_PKEY *peer_key = X509_get_pubkey(x509.get()); 313 | 314 | if (!peer_key) 315 | return build_error("connect_ssl::No key inside peer X509?!", -1); 316 | 317 | bool has = 0; 318 | for (auto p : d_pinned) { 319 | #if OPENSSL_VERSION_NUMBER >= 0x30000000L 320 | if (EVP_PKEY_eq(p, peer_key) == 1) 321 | #else 322 | if (EVP_PKEY_cmp(p, peer_key) == 1) 323 | #endif 324 | has = 1; 325 | } 326 | 327 | EVP_PKEY_free(peer_key); 328 | 329 | if (has != 1) 330 | return build_error("connect_ssl::Peer X509 not in pinned list!", -1); 331 | } 332 | 333 | return 0; 334 | } 335 | 336 | 337 | void ssl_box::close() 338 | { 339 | if (d_ssl) { 340 | 341 | // If there ever was a session ticket negotiated 342 | // by client and server, it will be available at this point. 343 | // This avoids the usage of SSL_CTX_sess_set_new_cb() which 344 | // would have no access to class member data. 345 | auto it = d_sessions.find(d_ns_ip); 346 | if (it != d_sessions.end()) 347 | SSL_SESSION_free(it->second); 348 | d_sessions[d_ns_ip] = SSL_get1_session(d_ssl); 349 | SSL_shutdown(d_ssl); 350 | SSL_free(d_ssl); 351 | } 352 | d_ssl = nullptr; 353 | 354 | if (d_sock > -1) 355 | ::close(d_sock); 356 | d_sock = -1; 357 | 358 | d_ns_ip = ""; 359 | } 360 | 361 | 362 | ssize_t ssl_box::send(const string &buf, long to) 363 | { 364 | if (!d_ssl) 365 | return -1; 366 | 367 | int r = 0, written = 0; 368 | long waiting = 0; 369 | timespec ts = {0, 10000000}; // 10ms 370 | 371 | for (;waiting < to;) { 372 | r = SSL_write(d_ssl, buf.c_str() + written, buf.size() - written); 373 | 374 | switch (SSL_get_error(d_ssl, r)) { 375 | case SSL_ERROR_NONE: 376 | break; 377 | case SSL_ERROR_WANT_WRITE: 378 | case SSL_ERROR_WANT_READ: 379 | r = 0; 380 | break; 381 | case SSL_ERROR_ZERO_RETURN: 382 | return build_error("send::SSL_write: Peer closed connection.", -1); 383 | default: 384 | return build_error("send::SSL_write:", -1); 385 | } 386 | 387 | if (r == 0) { 388 | nanosleep(&ts, nullptr); 389 | waiting += ts.tv_nsec; 390 | } else if (r > 0) 391 | written += r; 392 | 393 | if (written == (int)buf.size()) 394 | break; 395 | } 396 | 397 | return written; 398 | } 399 | 400 | 401 | ssize_t ssl_box::recv(string &s, long to) 402 | { 403 | s = ""; 404 | 405 | if (!d_ssl) 406 | return -1; 407 | 408 | int r = 0; 409 | char buf[4096] = {0}; 410 | long us = to/(1000*2); // half TO for select, other for potential repeated read's 411 | long waiting = 0; 412 | timeval tv = {(time_t)us/1000000, (suseconds_t)us%1000000}; 413 | timespec ts = {0, 10000000}; // 10ms 414 | 415 | fd_set rset; 416 | FD_ZERO(&rset); 417 | FD_SET(d_sock, &rset); 418 | 419 | if ((r = select(d_sock + 1, &rset, nullptr, nullptr, &tv)) <= 0) { 420 | if (r < 0) 421 | return build_error("recv::select:", -1); 422 | return 0; 423 | } 424 | 425 | for (; waiting < to/2;) { 426 | r = SSL_read(d_ssl, buf, sizeof(buf) - 1); 427 | switch (SSL_get_error(d_ssl, r)) { 428 | case SSL_ERROR_NONE: 429 | break; 430 | case SSL_ERROR_WANT_WRITE: 431 | case SSL_ERROR_WANT_READ: 432 | r = 0; 433 | break; 434 | case SSL_ERROR_ZERO_RETURN: 435 | return build_error("recv::SSL_read: Peer closed connection.", -1); 436 | default: 437 | return build_error("recv::SSL_read:", -1); 438 | } 439 | 440 | if (r == 0) { 441 | nanosleep(&ts, nullptr); 442 | waiting += ts.tv_nsec; 443 | } else if (r > 0) 444 | break; 445 | } 446 | 447 | if (r > 0) 448 | s = string(buf, r); 449 | 450 | return r; 451 | } 452 | 453 | 454 | } // namespace harddns 455 | 456 | -------------------------------------------------------------------------------- /src/ssl.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of harddns. 3 | * 4 | * (C) 2016-2019 by Sebastian Krahmer, 5 | * sebastian [dot] krahmer [at] gmail [dot] com 6 | * 7 | * harddns is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * harddns is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with harddns. If not, see . 19 | */ 20 | 21 | #ifndef harddns_ssl_h 22 | #define harddns_ssl_h 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | extern "C" { 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | } 40 | 41 | 42 | namespace harddns { 43 | 44 | 45 | class ssl_box { 46 | 47 | private: 48 | int d_sock{-1}; 49 | 50 | std::vector d_pinned; 51 | SSL_CTX *d_ssl_ctx{nullptr}; 52 | SSL *d_ssl{nullptr}; 53 | 54 | std::map d_sessions; 55 | 56 | std::string d_err{""}, d_ns_ip{""}; 57 | 58 | template 59 | T build_error(const std::string &msg, T r) 60 | { 61 | int e = 0; 62 | d_err = "ssl_box::"; 63 | d_err += msg; 64 | if ((e = ERR_get_error())) { 65 | ERR_load_crypto_strings(); 66 | d_err += ":"; 67 | d_err += ERR_error_string(e, nullptr); 68 | ERR_clear_error(); 69 | } else if (errno) { 70 | d_err += ":"; 71 | d_err += strerror(errno); 72 | } 73 | return r; 74 | } 75 | 76 | 77 | public: 78 | 79 | ssl_box(); 80 | 81 | virtual ~ssl_box(); 82 | 83 | const char *why() 84 | { 85 | return d_err.c_str(); 86 | } 87 | 88 | void add_pinned(EVP_PKEY *evp) 89 | { 90 | d_pinned.push_back(evp); 91 | } 92 | 93 | int setup_ctx(); 94 | 95 | // 1s 96 | int connect(const std::string &, uint16_t, std::string&, long to = 1000000000); 97 | 98 | // 1s 99 | ssize_t send(const std::string &, long to = 1000000000); 100 | 101 | ssize_t recv(std::string &, long to = 1000000000); 102 | 103 | void close(); 104 | 105 | std::string peer() 106 | { 107 | return d_ns_ip; 108 | } 109 | }; 110 | 111 | 112 | extern ssl_box *ssl_conn; 113 | 114 | #if (OPENSSL_VERSION_NUMBER <= 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER) 115 | #define ASN1_STRING_get0_data(x) ASN1_STRING_data(x) 116 | #endif 117 | 118 | } 119 | 120 | #endif 121 | 122 | -------------------------------------------------------------------------------- /src/test.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | 9 | using namespace std; 10 | 11 | int main(int argc, char **argv) 12 | { 13 | 14 | char buf[256] = {0}; 15 | addrinfo *res = nullptr, hints; 16 | 17 | memset(&hints, 0, sizeof(hints)); 18 | hints.ai_flags = AI_CANONNAME; 19 | // hints.ai_family = AF_ANY; 20 | 21 | for (;argc > 1;) { 22 | const char *name = argv[--argc]; 23 | printf("resolving %s\n", name); 24 | getaddrinfo(name, "", &hints, &res); 25 | hostent *he = gethostbyname(name); 26 | for (;res; res = res->ai_next) { 27 | memset(buf, 0, sizeof(buf)); 28 | if (res->ai_family == AF_INET) 29 | inet_ntop(res->ai_family, &((sockaddr_in *)res->ai_addr)->sin_addr, buf, sizeof(buf)); 30 | else 31 | inet_ntop(res->ai_family, &((sockaddr_in6 *)res->ai_addr)->sin6_addr, buf, sizeof(buf)); 32 | printf("gai: %d %s %s\n", res->ai_family, buf, res->ai_canonname?res->ai_canonname:"no canon"); 33 | } 34 | 35 | char **aliases = he->h_aliases; 36 | for (;*aliases; ++aliases) { 37 | printf("he: %s\n", *aliases); 38 | } 39 | } 40 | 41 | return 0; 42 | } 43 | 44 | --------------------------------------------------------------------------------