pax_global_header00006660000000000000000000000064137041571070014517gustar00rootroot0000000000000052 comment=939855e235360c6bda81ff187d9f919416aa1d1e nss-tls-1.1/000077500000000000000000000000001370415710700127635ustar00rootroot00000000000000nss-tls-1.1/.travis.yml000066400000000000000000000002401370415710700150700ustar00rootroot00000000000000language: minimal services: - docker script: - docker run --cap-add SYS_PTRACE -e CI -w /root/nss-tls -v `pwd`:/root/nss-tls dimkr/nss-tls:latest ./ci.sh nss-tls-1.1/AUTHORS000066400000000000000000000001031370415710700140250ustar00rootroot00000000000000Dima Krasner (dima@dimakrasner.com) Kan-Ru Chen (koster@debian.org)nss-tls-1.1/COPYING000066400000000000000000000636421370415710700140310ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! nss-tls-1.1/Dockerfile000066400000000000000000000022361370415710700147600ustar00rootroot00000000000000# This file is part of nss-tls. # # Copyright (C) 2018, 2019, 2020 Dima Krasner # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA FROM dimkr/c-dev:clang RUN apt-get -qq update && apt-get -y --no-install-recommends install pkg-config libglib2.0-dev libsoup2.4-dev systemd firefox && apt-get autoremove --purge && apt-get autoclean RUN pip3 install selenium RUN wget -O- https://github.com/mozilla/geckodriver/releases/download/v0.26.0/geckodriver-v0.26.0-linux64.tar.gz | tar -xzf- -C /usr/local/bin nss-tls-1.1/README.md000066400000000000000000000225741370415710700142540ustar00rootroot00000000000000``` _ _ _ __ ___ ___ | |_| |___ | '_ \/ __/ __|_____| __| / __| | | | \__ \__ \_____| |_| \__ \ |_| |_|___/___/ \__|_|___/ ``` [![Build Status](https://travis-ci.org/dimkr/nss-tls.svg?branch=master)](https://travis-ci.org/dimkr/nss-tls) ## Motivation Unlike most web browser traffic, which is encrypted thanks to HTTPS, the resolving of domain names to internet addresses still happens through DNS, an old, unencrypted protocol. This benefits analytics companies, advertisers, internet providers and attackers, but not the end-user, who seeks online privacy and security. ## Overview nss-tls is an alternative, encrypted name resolving library for [Linux](http://www.kernel.org/) distributions with [glibc](https://www.gnu.org/software/libc/), which uses [DNS-over-HTTPS (DoH)](https://tools.ietf.org/html/rfc8484). The glibc name resolver can be configured through nsswitch.conf(5) to use nss-tls instead of the DNS resolver, or fall back to DNS when nss-tls fails. This way, all applications that use the standard resolver API (getaddrinfo(), gethostbyname(), etc'), are transparently migrated from DNS to encrypted means of name resolving, with zero application-side changes and minimal resource consumption footprint. However, nss-tls does not deal with applications that use their own, built-in DNS resolver. ## Architecture nss-tls consists of three parts: * nss-tlsd runs in the background, receives name resolving requests over a Unix socket and replies with resolved addresses. * libnss_tls.so is a tiny client library, which delegates the resolving work to nss-tlsd through the Unix socket and passes the results back to the application, without dependencies other than libc. This way, applications that resolve through nss-tls are not affected by the complexity and resource consumption of runtime libraries (e.g. libstdc++) and dependency libraries used by nss-tlsd, or the constraints they impose on applications that load them (like signal or thread safety issues). * tlslookup is equivalent to nslookup(1), but uses libnss_tls.so instead of DNS. ## Security and Privacy An unprivileged user can start a private, unprivileged instance of nss-tlsd and libnss-tls.so will automatically use that one, instead of the system-wide instance of nss-tlsd. Each user's nss-tlsd instance holds its own cache of lookup results, to speed up resolving. Because the cache is not shared with other users, it remains "hot" even if other users resolve many names. Users who don't have such a private instance will continue to use the system-wide instance. which does not perform caching by default, to prevent a user from extracting the browsing history of another user, using timing-based methods. In addition, nss-tlsd drops its privileges to greatly reduce its attack surface. Also, nss-tlsd is capable of using multiple DoH servers, with a deterministic algorithm that chooses which server to use to resolve a domain. This way, no DoH server can track the user's entire browsing history. To avoid bloat, duplicate effort and potential remotely-exploitable vulnerabilities, nss-tlsd uses the libc API for building DNS queries and parsing responses, instead of implementing its own parser. ## Dependencies nss-tls depends on: * [glibc](https://www.gnu.org/software/libc/) * [GLib](https://wiki.gnome.org/Projects/GLib) * [libsoup](https://wiki.gnome.org/Projects/libsoup) If [systemd](https://www.freedesktop.org/wiki/Software/systemd/) is present, the installation of nss-tls includes unit files for nss-tlsd, and nss-tlsd may co-exist with [systemd-resolved](https://www.freedesktop.org/software/systemd/man/systemd-resolved.service.html). However, nss-tls does not depend on [systemd](https://www.freedesktop.org/wiki/Software/systemd/). When [systemd](https://www.freedesktop.org/wiki/Software/systemd/) is not present, other means of running a nss-tlsd instance for each user (e.g. xinitrc) and root (e.g. an init script) should be used. nss-tls uses [Meson](http://mesonbuild.com/) as its build system. On [Debian](http://www.debian.org/) and derivatives, these dependencies can be obtained using: apt install libglib2.0-dev libsoup2.4-dev ninja-build python3-pip pip3 install meson ## Usage Assuming your system runs [systemd](https://www.freedesktop.org/wiki/Software/systemd/): meson --prefix=/usr --buildtype=release -Dstrip=true build ninja -C build install systemctl daemon-reload systemctl enable nss-tlsd systemctl start nss-tlsd systemctl --user --global enable nss-tlsd systemctl --user start nss-tlsd ldconfig Then, add "tls" to the "hosts" entry in /etc/nsswitch.conf, before "[resolve](https://www.freedesktop.org/software/systemd/man/nss-resolve.html)", "dns" or anything else that contains "dns". This will enable a system nss-tlsd instance for all non-interactive processes (which runs as an unprivileged user) and a private instance of nss-tlsd for each user. Name resolving will happen through nss-tls and DNS will be attempted only if nss-tls fails. ## Choosing a DoH Server By default, nss-tls uses the DNS servers specified in /etc/resolv.conf, assuming they support DoH. To use a different DoH server, change the "resolvers" key of nss-tls.conf: [global] resolvers=https://9.9.9.9/dns-query nss-tlsd looks for nss-tls.conf in user's home directory (only when running as an unprivileged user; usually under .config) and the system configuration file directory (usually /etc). If both files exist, nss-tlsd prefers the user's one. nss-tlsd monitors the chosen configuration file and /etc/resolv.conf for changes and deletion, so changes are applied without having to restart nss-tlsd. If /etc/resolv.conf is a symlink and specifies a stub DNS resolver, because of [systemd-resolved](https://www.freedesktop.org/software/systemd/man/systemd-resolved.service.html), nss-tlsd tries to guess where the real resolv.conf is (usually /run/systemd/resolve/resolv.conf). If the "resolvers" key is missing or empty, nss-tlsd falls back to using the DNS servers specified in /etc/resolv.conf. To change the server selection in the default configuration file created at build time, use the "resolvers" build option: meson configure -Dresolvers=cloudflare-dns.com/dns-query ## Using Multiple DoH Servers It is also possible to use multiple DoH servers: [global] resolvers=https://dns9.quad9.net/dns-query,https://cloudflare-dns.com/dns-query When nss-tls is configured like this, it pseudo-randomly chooses one of the servers, for each name lookup. The choice of the server is consistent: if the same domain is resolved twice (e.g. for its IPv4 and IPv6 addresses, respectively), nss-tlsd will use the same DoH server for both queries. If nss-tlsd is restarted, it will keep using the same DoH server to resolve that domain. This contributes to privacy, since every DoH server sees only a portion of the user's browsing history. ## Choosing the HTTP Method A standard DoH server should support both GET and POST requests. By default, nss-tlsd sends POST requests, beause they are faster to craft and tend to be smaller. However, one might wish to use GET requests if this makes a specific DoH server respond faster (for example, if the server does not cache responses to POST requests). This can be done by adding "+get" after the server URL: [global] resolvers=https://dns.google/dns-query+get ## DoH Without Fallback to DNS If the DoH servers used by nss-tls are specified using their domain names, nss-tls needs a way to resolve the address of each DoH server and it cannot resolve it through itself. To build nss-tls without dependency on other resolving methods (like DNS), specify the DoH servers using their addresses, e.g.: [global] resolvers=https://9.9.9.9/dns-query,https://1.1.1.1/dns-query Alternatively, the DoH server addresses can be hardcoded using /etc/hosts, e.g: echo "8.8.8.8 dns.google" >> /etc/hosts Then, the DoH server can be specified by its domain name: [global] resolvers=https://dns.google/dns-query To disable DNS and use nss-tls exclusively, remove all DNS resolvers from the "hosts" entry in /etc/nsswitch.conf (but keep "tls"). ## Performance On paper, DNS over HTTPS is much slower than DNS, due to the overhead of TCP and TLS. Therefore, each nss-tls instance keeps established HTTPS connections open and reuses them. Also, if running with the -c option, each user's nss-tls instance maintains an internal cache of lookup results. In this cache, IPv4 and IPv6 addresses are stored in separate hash tables, to make the cache faster to iterate over. Therefore, in reality, DNS over HTTPS using nss-tls may be much faster than DNS. One may wish to use a system-wide cache that also covers DNS, instead of the internal cache of nss-tls; nscd(8) can do that. To enable system-wide cache on [Debian](http://www.debian.org/) and derivatives: apt install unscd Then, set "enable-cache" for "hosts" to "yes" in /etc/nscd.conf. Then: systemctl enable unscd systemctl start unscd ## Legal Information nss-tls is free and unencumbered software released under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version license. nss-tls is not affiliated with [Quad9](https://www.quad9.net/), [Cloudflare](https://www.cloudflare.com/) or [Google](https://www.google.com/). The ASCII art logo at the top was made using [FIGlet](http://www.figlet.org/). nss-tls-1.1/ci.py000077500000000000000000000034321370415710700137350ustar00rootroot00000000000000#!/usr/bin/python3 # # This file is part of nss-tls. # # Copyright (C) 2018, 2019 Dima Krasner # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from selenium.webdriver.firefox.options import Options import os import unittest import sys opts = Options() if os.getenv("CI"): opts.headless = True # use the native resolver (https://wiki.mozilla.org/Trusted_Recursive_Resolver) prof = webdriver.FirefoxProfile() prof.set_preference("network.trr.mode", 5) driver = webdriver.Firefox(firefox_binary=FirefoxBinary(sys.argv[1]), options=opts, firefox_profile=prof) class FirefoxTest(unittest.TestCase): def test_sanity(self): for d in sys.argv[2:]: url = "https://" + d driver.get(url) assert d in driver.current_url if __name__ == "__main__": suite = unittest.TestLoader().loadTestsFromTestCase(FirefoxTest) result = unittest.TextTestRunner(verbosity=2).run(suite) driver.quit() sys.exit(not result.wasSuccessful()) nss-tls-1.1/ci.sh000077500000000000000000000100331370415710700137120ustar00rootroot00000000000000#!/bin/sh -xe # This file is part of nss-tls. # # Copyright (C) 2018, 2019, 2020 Dima Krasner # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA DOMAINS=" ipv4.google.com google.com youtube.com facebook.com baidu.com wikipedia.org taobao.com amazon.com twitter.com instagram.com reddit.com yandex.ru netflix.com aliexpress.com ebay.com bing.com github.com " # at least some Travis and AWS CodeBuild machines don't have an IPv6 route, so # we only resolve these IPV6_ONLY_DOMAINS=" ipv6.google.com " meson --prefix=/usr --buildtype=release -Dstrip=true build ninja -C build install # make sure automatic DNS to DoH upgrade works cat << EOF > /etc/resolv.conf nameserver 1.1.1.1 nameserver 9.9.9.9 EOF ./build/nss-tlsd & pid=$! sleep 1 tlslookup google.com # pick 3 random domains domains=`echo $DOMAINS | tr ' ' \\\n | shuf | head -n 3` for d in $domains do tlslookup $d done kill -9 $pid sleep 1 # make sure explicit choice of DoH servers works echo -n > /etc/resolv.conf meson configure build -Dresolvers=https://9.9.9.9/dns-query+random,https://dns.google/dns-query+random,https://1.1.1.1/dns-query+random ninja -C build install CC=clang meson --prefix=/usr -Db_sanitize=address build-asan ninja -C build-asan nss-tlsd ldconfig echo "8.8.8.8 dns.google" >> /etc/hosts cp -f /etc/nsswitch.conf /tmp/ sed 's/hosts:.*/hosts: files tls/' -i /etc/nsswitch.conf ./build-asan/nss-tlsd -r | tee /tmp/nss-tlsd.log & pid=$! sleep 1 for i in a b c do for d in $domains $IPV6_ONLY_DOMAINS do valgrind --leak-check=full --track-fds=yes --error-exitcode=1 --errors-for-leak-kinds=all tlslookup $d done for d in $domains $IPV6_ONLY_DOMAINS do getent hosts $d done done # resolving the domain of a DoH server should always fail tlslookup dns.google && exit 1 # resolving domains suffixed by the local domain should fail too and change of # the local domain should take effect immediately echo "search ci" >> /etc/resolv.conf tlslookup google.com.ci && exit 1 # before 9169a0, the canonical name was an alias (instead of being the name, # with the non-canonical domain being the alias), so handshakes failed if the # certificate specified only the non-canonical name for d in $domains do wget -T 5 -t 2 -O /dev/null https://$d done # test against Firefox Nightly [ -f firefox/firefox ] || wget -O- "https://download.mozilla.org/?product=firefox-nightly-latest-ssl&os=linux64&lang=en-US" | tar -xjf- ./ci.py firefox/firefox $domains # before 963b0b, 8.8.8.8 responded with 400 if the dns= parameter contained URL # unsafe characters [ -n "`grep '^< HTTP/' /tmp/nss-tlsd.log | grep -v 200`" ] && exit 1 sed -i s/^resolvers=.*/resolvers=/ /etc/nss-tls.conf # if resolving fails, we should try the next NSS module echo "nameserver 185.228.168.168" > /etc/resolv.conf kill -9 $pid sleep 1 ./build/nss-tlsd & pid=$! sleep 1 getent hosts google.com && exit 1 sed 's/hosts:.*/hosts: tls dns/' -i /etc/nsswitch.conf getent hosts google.com # if we have zero DoH servers, we should try the next NSS module echo > /etc/resolv.conf kill -9 $pid sleep 1 ./build/nss-tlsd & pid=$! sleep 1 echo "nameserver 9.9.9.9" > /etc/resolv.conf tlslookup google.com && exit 1 getent hosts google.com # if nss-tlsd is down, we should try the next NSS module kill -9 $pid sleep 1 tlslookup google.com && exit 1 getent hosts google.com exit 0 nss-tls-1.1/debian/000077500000000000000000000000001370415710700142055ustar00rootroot00000000000000nss-tls-1.1/debian/README.Debian000066400000000000000000000004011370415710700162410ustar00rootroot00000000000000nss-tls for Debian ----------------- The nss-tlsd is preconfigured with three DNS-over-HTTPS resolvers. You can review and update the resolvers in file `/etc/nss-tls.conf'. -- Kan-Ru Chen (陳侃如) , Sun, 24 May 2020 08:35:16 +0900 nss-tls-1.1/debian/README.source000066400000000000000000000004751370415710700163720ustar00rootroot00000000000000nss-tls for Debian ----------------- Since the upstream does not have tarball release yet, the source tarball is generated with command: git archive --prefix nss-tls/ --format tar HEAD | xz > ../nss-tls_0~git`%Y%m%d`.orig.tar.xz -- Kan-Ru Chen (陳侃如) , Sun, 24 May 2020 08:26:57 +0900 nss-tls-1.1/debian/changelog000066400000000000000000000002541370415710700160600ustar00rootroot00000000000000nss-tls (0~git20200523-1) unstable; urgency=medium * Initial release (Closes: #958710) -- Kan-Ru Chen (陳侃如) Sat, 23 May 2020 22:01:40 +0900 nss-tls-1.1/debian/control000066400000000000000000000064451370415710700156210ustar00rootroot00000000000000Source: nss-tls Priority: optional Maintainer: Kan-Ru Chen (陳侃如) Build-Depends: debhelper-compat (= 12), libglib2.0-dev (>= 2.44), libsoup2.4-dev, systemd, ninja-build, python3-pip, meson Standards-Version: 4.5.0 Section: net Rules-Requires-Root: no Homepage: https://github.com/dimkr/nss-tls #Vcs-Browser: https://salsa.debian.org/debian/nss-tls #Vcs-Git: https://salsa.debian.org/debian/nss-tls.git Package: nss-tlsd Architecture: any Multi-Arch: foreign Depends: ${shlibs:Depends}, ${misc:Depends} Description: encrypted DNS name resolution daemon nss-tls is an alternative, encrypted name resolving library to use with glibc, which uses DNS-over-HTTPS (DoH). . The glibc name resolver can be configured through nsswitch.conf(5) to use nss-tls instead of the DNS resolver, or fall back to DNS when nss-tls fails. . This way, all applications that use the standard resolver API (getaddrinfo(), gethostbyname(), etc'), are transparently migrated from DNS to encrypted means of name resolving, with zero application-side changes and minimal resource consumption footprint. However, nss-tls does not deal with applications that use their own, built-in DNS resolver. . This package contains the daemon to be used in conjunction with the libnss-tls NSS module. The daemon runs in the background, receives name resolving requests over a Unix socket and replies with resolved addresses. Package: libnss-tls Architecture: any Multi-Arch: same Depends: nss-tlsd (>=${source:Upstream-Version}), ${shlibs:Depends}, ${misc:Depends} Description: NSS module for encrypted DNS name resolution nss-tls is an alternative, encrypted name resolving library to use with glibc, which uses DNS-over-HTTPS (DoH). . The glibc name resolver can be configured through nsswitch.conf(5) to use nss-tls instead of the DNS resolver, or fall back to DNS when nss-tls fails. . This way, all applications that use the standard resolver API (getaddrinfo(), gethostbyname(), etc'), are transparently migrated from DNS to encrypted means of name resolving, with zero application-side changes and minimal resource consumption footprint. However, nss-tls does not deal with applications that use their own, built-in DNS resolver. . This package contains the NSS module, a tiny client library, which delegates the resolving work to nss-tlsd through the Unix socket and passes the results back to the application, without dependencies other than libc. Package: tlslookup Section: utils Architecture: any Depends: ${shlibs:Depends}, ${misc:Depends} Description: utility like nslookup(1), but uses libnss_tls.so instead of DNS nss-tls is an alternative, encrypted name resolving library to use with glibc, which uses DNS-over-HTTPS (DoH). . The glibc name resolver can be configured through nsswitch.conf(5) to use nss-tls instead of the DNS resolver, or fall back to DNS when nss-tls fails. . This way, all applications that use the standard resolver API (getaddrinfo(), gethostbyname(), etc'), are transparently migrated from DNS to encrypted means of name resolving, with zero application-side changes and minimal resource consumption footprint. However, nss-tls does not deal with applications that use their own, built-in DNS resolver. . This package contains the utility program to lookup DNS names using libnss-tls. nss-tls-1.1/debian/copyright000066400000000000000000000022321370415710700161370ustar00rootroot00000000000000Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: nss-tls Upstream-Contact: Dima Krasner Source: https://github.com/dimkr/nss-tls Files: * Copyright: 2018-2020 Dima Krasner License: LGPL-2.0+ Files: debian/* Copyright: 2020 Kan-Ru Chen (陳侃如) License: LGPL-2.0+ License: LGPL-2.0+ This package is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. . This package is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. . You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . . On Debian systems, the complete text of the GNU Lesser General Public License can be found in "/usr/share/common-licenses/LGPL-2". nss-tls-1.1/debian/libnss-tls.install000066400000000000000000000000331370415710700176630ustar00rootroot00000000000000usr/lib/*/libnss_tls*.so.* nss-tls-1.1/debian/libnss-tls.lintian-overrides000066400000000000000000000001361370415710700216570ustar00rootroot00000000000000# package is a NSS module, not a system library libnss-tls: package-name-doesnt-match-sonames nss-tls-1.1/debian/libnss-tls.postinst000077500000000000000000000032621370415710700201120ustar00rootroot00000000000000#!/bin/sh set -e # This code was taken from libnss-myhostname # try to insert tls entries to the "hosts" line in /etc/nsswitch.conf to # automatically enable libnss-tls support; do not change the # configuration if the "hosts" line already references some tls lookups insert_nss_entry() { echo "Checking NSS setup..." # abort if /etc/nsswitch.conf does not exist if ! [ -e /etc/nsswitch.conf ]; then echo "Could not find /etc/nsswitch.conf." return fi echo "Adding 'tls' to nsswitch.conf..." perl -i -pe ' sub insert { my $line = shift; # this also splits on tab my @bits=split(" ", $line); # do not break configuration if the "hosts" line already references # tls if (grep { $_ eq "tls"} @bits) { return $line; } if (grep { $_ eq "dns"} @bits) { # add tls before dns $line =~ s/(\s+)dns(\s+)/$1tls dns$2/; return $line; } else { if (grep { $_ eq "resolve"} @bits) { # add tls before resolve $line =~ s/(\s+)resolve(\s+)/$1tls resolve$2/; return $line; } else { # add tls at the end return $line . " tls"; } } } s/^(hosts:\s+)(.*)/$1.insert($2)/e; ' /etc/nsswitch.conf } if [ "$1" = configure ] && [ -z "$2" ]; then echo "First installation detected..." # first install: setup the recommended configuration (unless # nsswitch.conf already contains tls entries) insert_nss_entry fi #DEBHELPER# nss-tls-1.1/debian/libnss-tls.postrm000077500000000000000000000014131370415710700175470ustar00rootroot00000000000000#!/bin/sh set -e remove_nss_entry() { local file=$1 local pkg=$2 local module=$3 refcount=$(dpkg-query -f '${db:Status-Abbrev} ${binary:Package}\n' \ -W $pkg | grep '^i' | wc -l) if [ "$refcount" -gt 0 ] ; then # package is installed for other architectures still, do nothing return fi echo "Checking NSS setup..." # abort if file does not exist if ! [ -e $file ]; then echo "Could not find ${file}." return fi # we must remove possible [foo=bar] options as well echo "Removing 'tls' from nsswitch.conf..." sed -i -r "/hosts:/ s/[[:space:]]+$module\b([[:space:]]*\[[^]]*\])*//" $file } if [ "$1" = remove ]; then remove_nss_entry /etc/nsswitch.conf libnss-tls tls fi #DEBHELPER# nss-tls-1.1/debian/not-installed000066400000000000000000000000301370415710700166760ustar00rootroot00000000000000usr/lib/*/libnss_tls.so nss-tls-1.1/debian/nss-tlsd.install000066400000000000000000000002131370415710700173400ustar00rootroot00000000000000etc/nss-tls.conf lib/systemd/system/nss-tlsd.service usr/lib/systemd/user/nss-tlsd.service usr/sbin/nss-tlsd usr/share/man/man8/nss-tlsd.8 nss-tls-1.1/debian/rules000077500000000000000000000012251370415710700152650ustar00rootroot00000000000000#!/usr/bin/make -f # See debhelper(7) (uncomment to enable) # output every command that modifies files on the build system. #export DH_VERBOSE = 1 # see FEATURE AREAS in dpkg-buildflags(1) #export DEB_BUILD_MAINT_OPTIONS = hardening=+all # see ENVIRONMENT in dpkg-buildflags(1) # package maintainers to append CFLAGS #export DEB_CFLAGS_MAINT_APPEND = -Wall -pedantic # package maintainers to append LDFLAGS #export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed DEFAULT_RESOLVERS=https://9.9.9.9/dns-query,https://dns.google/dns-query+get,https://1.1.1.1/dns-query %: dh $@ override_dh_auto_configure: dh_auto_configure -- -Dresolvers=$(DEFAULT_RESOLVERS) nss-tls-1.1/debian/source/000077500000000000000000000000001370415710700155055ustar00rootroot00000000000000nss-tls-1.1/debian/source/format000066400000000000000000000000141370415710700167130ustar00rootroot000000000000003.0 (quilt) nss-tls-1.1/debian/tlslookup.install000066400000000000000000000000611370415710700176260ustar00rootroot00000000000000usr/bin/tlslookup usr/share/man/man1/tlslookup.1 nss-tls-1.1/debian/watch000066400000000000000000000004201370415710700152320ustar00rootroot00000000000000# See uscan(1) for format # Compulsory line, this is a version 4 file version=4 # GitHub hosted projects opts="filenamemangle=s%(?:.*?)?v?(\d[\d.]*)\.tar\.gz%nss-tls-$1.tar.gz%" \ https://github.com/dimkr/nss-tls/tags \ (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate nss-tls-1.1/meson.build000066400000000000000000000103331370415710700151250ustar00rootroot00000000000000# This file is part of nss-tls. # # Copyright (C) 2018, 2019, 2020 Dima Krasner # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA project('nss-tls', 'c', version: '1.9', license : ['LGPL2.1+']) prefix = get_option('prefix') sys_conf_dir = get_option('sysconfdir') local_state_dir = get_option('localstatedir') nss_tls_socket_name = 'nss-tlsd.sock' nss_tls_conf_name = 'nss-tls.conf' nss_tls_socket_dir = '@0@/run/nss-tls'.format(join_paths(prefix, local_state_dir)) nss_tls_socket_path = '@0@/@1@'.format(nss_tls_socket_dir, nss_tls_socket_name) nss_tls_user = get_option('user') nss_tls_group = get_option('group') nss_tlsd_path = join_paths(get_option('prefix'), get_option('sbindir'), 'nss-tlsd') add_project_arguments( '-DNSS_TLS_SOCKET_NAME="@0@"'.format(nss_tls_socket_name), '-DNSS_TLS_CONF_NAME="@0@"'.format(nss_tls_conf_name), '-DNSS_TLS_SOCKET_DIR="@0@"'.format(nss_tls_socket_dir), '-DNSS_TLS_SOCKET_PATH="@0@"'.format(nss_tls_socket_path), '-DNSS_TLS_TIMEOUT=@0@'.format(get_option('timeout')), '-DNSS_TLS_USER="@0@"'.format(nss_tls_user), '-DNSS_TLS_GROUP="@0@"'.format(nss_tls_group), '-DNSS_TLS_SYSCONFDIR="@0@"'.format(join_paths(prefix, sys_conf_dir)), language: 'c' ) systemd = dependency('systemd', required: false) if systemd.found() add_project_arguments('-DNSS_TLS_SYSTEMD', language: 'c') endif if get_option('buildtype').startswith('debug') add_project_arguments('-DNSS_TLS_DEBUG', language: 'c') endif nss_tlsd = executable('nss-tlsd', 'nss-tlsd.c', dependencies: [ meson.get_compiler('c').find_library('resolv'), dependency('glib-2.0', version: '>=2.44'), dependency('gio-2.0'), dependency('gio-unix-2.0'), dependency('libsoup-2.4'), ], install: true, install_dir: get_option('sbindir')) libnss_tls = shared_library('nss_tls', 'nss-tls.c', version: '2', dependencies: [dependency('threads')], install: true) tlslookup = executable('tlslookup', 'tlslookup.c', link_with: libnss_tls, install: true) cfg = configuration_data() cfg.set('nss_tlsd_path', nss_tlsd_path) cfg.set('resolvers', get_option('resolvers')) nss_tls_conf = configure_file(input: 'nss-tls.conf.in', output: 'nss-tls.conf', configuration: cfg) install_data(nss_tls_conf, install_dir: sys_conf_dir) if systemd.found() nss_tlsd_service = configure_file(input: 'nss-tlsd.service.in', output: 'nss-tlsd.service', configuration: cfg) systemd_unit_dir = systemd.get_pkgconfig_variable('systemdsystemunitdir') install_data(nss_tlsd_service, install_dir: systemd_unit_dir) nss_tlsd_user_service = configure_file(input: 'nss-tlsd-user.service.in', output: 'nss-tlsd-user.service', configuration: cfg) systemd_user_unit_dir = systemd.get_pkgconfig_variable('systemduserunitdir') install_data(nss_tlsd_user_service, install_dir: systemd_user_unit_dir, rename: 'nss-tlsd.service') endif install_man('nss-tlsd.8') install_man('tlslookup.1') nss-tls-1.1/meson_options.txt000066400000000000000000000007761370415710700164320ustar00rootroot00000000000000option( 'resolvers', type: 'string', description: 'Comma-delimited URLs of DoH servers to use' ) option( 'timeout', type: 'integer', value: 4, description: 'Timeout for each resolving attempt' ) option( 'user', type: 'string', value: 'daemon', description: 'An unprivileged user to drop to when nss-tlsd runs as root' ) option( 'group', type: 'string', value: 'daemon', description: 'An unprivileged group to drop to when nss-tlsd runs as root' ) nss-tls-1.1/nss-tls.c000066400000000000000000000126231370415710700145360ustar00rootroot00000000000000/* * This file is part of nss-tls. * * Copyright (C) 2018, 2019, 2020 Dima Krasner * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include #include #include #include #include #include #include #include #include #include "nss-tls.h" static void cleanup(void *arg) { close((int)(intptr_t)arg); } enum nss_status _nss_tls_gethostbyname2_r(const char *name, int af, struct hostent *ret, char *buf, size_t buflen, int *errnop, int *h_errnop) { struct sockaddr_un sun = {.sun_family = AF_UNIX}; struct timeval tv = {.tv_sec = NSS_TLS_TIMEOUT / 2, .tv_usec = 0}; struct nss_tls_data *data = (struct nss_tls_data *)buf; const char *dir; ssize_t out, total; size_t len; int s, i, state; enum nss_status status = NSS_STATUS_TRYAGAIN; uint8_t count; if (buflen < sizeof(*data)) { *errnop = ERANGE; *h_errnop = NETDB_INTERNAL; return NSS_STATUS_TRYAGAIN; } *errnop = ENOENT; *h_errnop = NETDB_SUCCESS; if (geteuid() == 0) strcpy(sun.sun_path, NSS_TLS_SOCKET_PATH); else { dir = getenv("XDG_RUNTIME_DIR"); if (dir) { len = strlen(dir); if (len > sizeof(sun.sun_path) - sizeof("/"NSS_TLS_SOCKET_NAME)) return NSS_STATUS_TRYAGAIN; memcpy(sun.sun_path, dir, len); sun.sun_path[len] = '/'; ++len; strncpy(sun.sun_path + len, NSS_TLS_SOCKET_NAME, sizeof(sun.sun_path) - len); sun.sun_path[sizeof(sun.sun_path) - 1] = '\0'; } else strcpy(sun.sun_path, NSS_TLS_SOCKET_PATH); } pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &state); s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); if (s < 0) { if (state != PTHREAD_CANCEL_DISABLE) pthread_setcancelstate(state, NULL); *errnop = EAGAIN; return NSS_STATUS_TRYAGAIN; } pthread_cleanup_push(cleanup, (void *)(intptr_t)s); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); if ((setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0) || (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0)) goto pop; if (connect(s, (const struct sockaddr *)&sun, sizeof(sun)) < 0) { if (errno != ENOENT) goto pop; strcpy(sun.sun_path, NSS_TLS_SOCKET_PATH); if (connect(s, (const struct sockaddr *)&sun, sizeof(sun)) < 0) goto pop; } data->req.af = af; strncpy(data->req.name, name, sizeof(data->req.name)); data->req.name[sizeof(data->req.name) - 1] = '\0'; for (total = 0; total < sizeof(data->req); total += out) { out = send(s, (unsigned char *)&data->req + total, sizeof(data->req) - total, MSG_NOSIGNAL); if (out <= 0) goto pop; } for (total = 0; total < sizeof(data->res); total += out) { out = recv(s, (unsigned char *)&data->res + total, sizeof(data->res) - total, 0); if (out < 0) goto pop; if (out == 0) break; } if (total == 0) { status = NSS_STATUS_NOTFOUND; goto pop; } if (total != sizeof(data->res)) goto pop; if (data->res.cname[0]) { ret->h_name = data->res.cname; data->aliases[0] = data->req.name; data->aliases[1] = NULL; } else { ret->h_name = data->req.name; data->aliases[0] = NULL; } ret->h_aliases = data->aliases; ret->h_addrtype = af; data->addrs[0] = NULL; ret->h_addr_list = data->addrs; count = data->res.count; if (count == 0) { *h_errnop = HOST_NOT_FOUND; status = NSS_STATUS_NOTFOUND; goto pop; } if (count > NSS_TLS_ADDRS_MAX) count = NSS_TLS_ADDRS_MAX; switch (af) { case AF_INET: ret->h_length = sizeof(struct in_addr); break; case AF_INET6: ret->h_length = sizeof(struct in6_addr); break; default: status = NSS_STATUS_NOTFOUND; goto pop; } for (i = 0; i < count; ++i) data->addrs[i] = (char *)&data->res.addrs[i]; data->addrs[i] = NULL; *errnop = 0; status = NSS_STATUS_SUCCESS; pop: pthread_cleanup_pop(1); return status; } nss-tls-1.1/nss-tls.conf.in000066400000000000000000000000371370415710700156420ustar00rootroot00000000000000[global] resolvers=@resolvers@ nss-tls-1.1/nss-tls.h000066400000000000000000000025451370415710700145450ustar00rootroot00000000000000/* * This file is part of nss-tls. * * Copyright (C) 2018, 2019 Dima Krasner * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #define NSS_TLS_ADDRS_MAX 16 struct nss_tls_req { int af; char name[NS_MAXDNAME]; } __attribute__((packed)); struct nss_tls_res { uint8_t count; int64_t expiry; char cname[NS_MAXDNAME]; union { struct in_addr in; struct in6_addr in6; } addrs[NSS_TLS_ADDRS_MAX]; } __attribute__((packed)); struct nss_tls_data { char *aliases[2]; char *addrs[NSS_TLS_ADDRS_MAX + 1]; struct nss_tls_req req; struct nss_tls_res res; }; nss-tls-1.1/nss-tlsd-user.service.in000066400000000000000000000020461370415710700174770ustar00rootroot00000000000000# This file is part of nss-tls. # # Copyright (C) 2018, 2019 Dima Krasner # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA [Unit] Description=NSS TLS Daemon Documentation=man:nss-tlsd(8) Documentation=https://github.com/dimkr/nss-tls [Service] Type=simple ExecStart=@nss_tlsd_path@ -c StandardOutput=null StandardError=null Restart=on-failure [Install] WantedBy=default.target nss-tls-1.1/nss-tlsd.8000066400000000000000000000003701370415710700146230ustar00rootroot00000000000000.TH nss-tlsd 8 .SH NAME .B nss-tlsd \- DNS over HTTPS resolver .SH SYNOPSIS .B nss-tlsd .SH DESCRIPTION Performs DNS queries over HTTPS, in the name of libnss-tls users. .SH "SEE ALSO" .B tlslookup(1) .SH AUTHOR Dima Krasner (dima@dimakrasner.com) nss-tls-1.1/nss-tlsd.c000066400000000000000000001030371370415710700147020ustar00rootroot00000000000000/* * This file is part of nss-tls. * * Copyright (C) 2018, 2019, 2020 Dima Krasner * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "nss-tls.h" #define CACHE_CLEANUP_INTERVAL 5 #define FALLBACK_TTL (60 * 1000000) #define MIN_TTL 10 #define CACHE_SIZE 1024 #define MAX_CONNS_PER_RESOLVER 10 #define MAX_RESOLVERS 16 #define MAX_REQ_SIZE 512 enum nss_tls_methods { NSS_TLS_METHOD_POST, NSS_TLS_METHOD_MIN = NSS_TLS_METHOD_POST, NSS_TLS_METHOD_GET, NSS_TLS_METHOD_MAX, NSS_TLS_METHOD_RANDOM }; struct nss_tls_session { unsigned char dns[UINT16_MAX]; struct nss_tls_req request; struct nss_tls_res response; gint64 type; GSocketConnection *connection; SoupMessage *message; gboolean canon; }; static SoupSession *soup = NULL; static struct { SoupURI *uri; gchar *url; const gchar *domain; enum nss_tls_methods method; } resolvers[MAX_RESOLVERS]; static gint32 nresolvers = 0; static gboolean cache = FALSE; static gboolean randomize = FALSE; static GHashTable *caches[2] = {NULL, NULL}; static GFile *cfg_file = NULL, *resolv_conf = NULL; static GFileMonitor *cfg_monitor = NULL, *resolv_conf_monitor = NULL; static gboolean check_ttl (gpointer key, gpointer value, gpointer user_data) { const gchar *name = (const gchar *)key; struct nss_tls_res *res = (struct nss_tls_res *)value; gint64 now = *(gint64 *)user_data; if (now > res->expiry) { g_debug ("Cache for %s has expired", name); return TRUE; } return FALSE; } static gboolean on_cache_cleanup (gpointer user_data) { gint64 now; gint i; now = g_get_monotonic_time (); for (i = 0; i < G_N_ELEMENTS (caches); ++i) { g_hash_table_foreach_remove (caches[i], check_ttl, &now); } return TRUE; } static GHashTable * choose_cache (const int af) { if (af == AF_INET) { return caches[0]; } return caches[1]; } static void add_to_cache (const struct nss_tls_req *req, struct nss_tls_res *res) { gchar *key; struct nss_tls_res *val; gint64 now; GHashTable *cache; cache = choose_cache (req->af); if (!cache || (g_hash_table_size (cache) >= CACHE_SIZE)) { return; } if (res->expiry == -1) { now = g_get_monotonic_time (); if (now > INT64_MAX - FALLBACK_TTL) { return; } res->expiry = now + FALLBACK_TTL; } key = g_strdup (req->name); val = g_memdup (res, sizeof (*res)); g_hash_table_insert (cache, key, val); g_debug ("Caching %s until %"G_GINT64_FORMAT, req->name, res->expiry); } static const struct nss_tls_res * query_cache (const int af, const char *name) { gpointer res = NULL; GHashTable *cache; cache = choose_cache (af); if (cache) { res = g_hash_table_lookup (cache, name); if (res) { g_debug ("Found %s in the cache", name); } } return (const struct nss_tls_res *)res; } static gboolean get_cached_response (struct nss_tls_session *session) { const struct nss_tls_res *res, *cres; res = query_cache (session->request.af, session->request.name); if (!res) { return FALSE; } if (res->cname[0]) { cres = query_cache (session->request.af, res->cname); if (cres) { memcpy (session->response.addrs, cres->addrs, cres->count * sizeof(cres->addrs[0])); session->response.count = cres->count; session->response.expiry = cres->expiry; strcpy (session->response.cname, res->cname); return TRUE; } } memcpy (&session->response, res, sizeof (session->response)); return TRUE; } static void on_response (GObject *source_object, GAsyncResult *res, gpointer user_data); static void on_sent (GObject *source_object, GAsyncResult *res, gpointer user_data); static gchar * encode_dns_query (const unsigned char *buf, const gsize len) { gchar *b64; size_t i; b64 = g_base64_encode (buf, len); /* https://tools.ietf.org/html/rfc4648#section-5 */ for (i = 0; i < strlen (b64); ++i) { switch (b64[i]) { case '+': b64[i] = '-'; break; case '/': b64[i] = '_'; break; case '=': b64[i] = '\0'; return b64; } } return b64; } static gboolean resolve_domain (struct nss_tls_session *session) { static unsigned char sbuf[MAX_REQ_SIZE]; unsigned char *buf = sbuf; g_autofree gchar *url = NULL, *dns = NULL; GOutputStream *out; int type, len; SoupMessageFlags flags; guint id = 0; gint method; if (get_cached_response (session)) { out = g_io_stream_get_output_stream (G_IO_STREAM (session->connection)); g_output_stream_write_all_async (out, &session->response, sizeof (session->response), G_PRIORITY_DEFAULT, NULL, on_sent, session); return TRUE; } if (nresolvers == 0) { return FALSE; } switch (session->request.af) { case AF_INET: type = ns_t_a; break; case AF_INET6: type = ns_t_aaaa; break; default: return FALSE; } if (randomize) { id = g_random_int_range (0, nresolvers); } else if (nresolvers > 1) { id = g_str_hash (session->request.name) % nresolvers; } if (resolvers[id].method == NSS_TLS_METHOD_RANDOM) { method = g_random_int_range (NSS_TLS_METHOD_MIN, NSS_TLS_METHOD_MAX); } else { method = (gint)resolvers[id].method; } if (method == NSS_TLS_METHOD_POST) { buf = g_malloc (MAX_REQ_SIZE); } len = res_mkquery (QUERY, session->request.name, ns_c_in, type, NULL, 0, NULL, buf, MAX_REQ_SIZE); if (len <= 1) { if (method == NSS_TLS_METHOD_POST) { g_free (buf); } return FALSE; } /* * always use 0 for the transaction ID, to improve the server's cache hit * rate */ buf[0] = buf[1] = 0; if (nresolvers > 1) { g_debug ("Resolving %s (%s) using %s", session->request.name, (session->request.af == AF_INET) ? "IPv4" : "IPv6", resolvers[id].url); } else { g_debug ("Resolving %s (%s)", session->request.name, (session->request.af == AF_INET) ? "IPv4" : "IPv6"); } session->response.cname[0] = '\0'; session->type = (gint64)type; if (method == NSS_TLS_METHOD_POST) { session->message = soup_message_new ("POST", resolvers[id].url); } else { dns = encode_dns_query (buf, (gsize)len); url = g_strdup_printf ("%s?dns=%s", resolvers[id].url, dns); session->message = soup_message_new ("GET", url); } flags = soup_message_get_flags (session->message); soup_message_set_flags (session->message, flags | SOUP_MESSAGE_IDEMPOTENT); if (method == NSS_TLS_METHOD_POST) { soup_message_set_request (session->message, "application/dns-message", SOUP_MEMORY_TAKE, (const char *)buf, (gsize)len); } soup_message_headers_append (session->message->request_headers, "Accept", "application/dns-message"); soup_session_send_async (soup, session->message, NULL, on_response, session); return TRUE; } static void resolve_cname (struct nss_tls_session *session) { g_debug ("The canonical name of %s is %s", session->request.name, session->response.cname); strcpy (session->request.name, session->response.cname); /* * ignore CNAME records for this name; we don't want to be stuck in an * infinite loop if the canonical form of A is B, while B has a CNAME record * that points back to A */ session->canon = TRUE; resolve_domain (session); } static void on_close (GObject *source_object, GAsyncResult *res, gpointer user_data) { struct nss_tls_session *session = (struct nss_tls_session *)user_data; g_io_stream_close_finish (G_IO_STREAM (source_object), res, NULL); g_object_unref (session->connection); g_free (session); } static void stop_session (struct nss_tls_session *session) { g_io_stream_close_async (G_IO_STREAM (session->connection), G_PRIORITY_DEFAULT, NULL, on_close, session); } /* step 4: we're done sending the response to libnss_tls */ static void on_sent (GObject *source_object, GAsyncResult *res, gpointer user_data) { struct nss_tls_session *session = (struct nss_tls_session *)user_data; gsize out; g_output_stream_write_all_finish (G_OUTPUT_STREAM (source_object), res, &out, NULL); stop_session (session); } static void on_answer (struct nss_tls_session *session, const unsigned char *dns, const gsize len, ns_msg *msg, const int rr_id, const int a_type, const size_t addrlen) { ns_rr rr; gint64 ttl, now, expiry; int type; if (ns_parserr (msg, ns_s_an, rr_id, &rr) < 0) { g_warning ("Failed to parse a result record for %s", session->request.name); return; } if (ns_rr_class (rr) != ns_c_in) return; type = ns_rr_type (rr); if (type == a_type) { if (ns_rr_rdlen (rr) == addrlen) { memcpy (&session->response.addrs[session->response.count], ns_rr_rdata (rr), addrlen); ++session->response.count; ttl = (gint64)ns_rr_ttl (rr); if (ttl <= INT64_MAX / 1000000) { if (ttl < MIN_TTL) ttl = MIN_TTL; ttl *= 1000000; now = g_get_monotonic_time (); /* * after looking at all answer records, we use the shortest * TTL for all answers */ if (INT64_MAX - ttl >= now) { expiry = (int64_t)(now + ttl); if ((session->response.expiry == -1) || (expiry < session->response.expiry)) { session->response.expiry = expiry; } } } } } else if (!session->canon && (type == ns_t_cname) && !session->response.cname[0] && (ns_rr_rdlen (rr) > 0)) { if (dn_expand (dns, dns + len, ns_rr_rdata (rr), session->response.cname, sizeof (session->response.cname)) <= 0) { session->response.cname[0] = '\0'; } } } static void on_body (GObject *source_object, GAsyncResult *res, gpointer user_data) { ns_msg msg; g_autoptr(GError) err = NULL; struct nss_tls_session *session = (struct nss_tls_session *)user_data; GOutputStream *out; gsize len; size_t addrlen; int id, count, a_type; if (!g_input_stream_read_all_finish (G_INPUT_STREAM (source_object), res, &len, &err) || !len) { goto cleanup; } switch (session->request.af) { case AF_INET: a_type = ns_t_a; addrlen = sizeof (session->response.addrs[0].in); break; case AF_INET6: a_type = ns_t_aaaa; addrlen = sizeof (session->response.addrs[0].in6); break; default: goto cleanup; } if (ns_initparse (session->dns, (int)len, &msg) < 0) { g_warning ("Failed to parse the result for %s", session->request.name); goto cleanup; } count = ns_msg_count(msg, ns_s_an); for (id = 0; ((id < count) && ((session->response.count < G_N_ELEMENTS (session->response.addrs)) || !session->response.cname[0])); ++id) { on_answer (session, session->dns, len, &msg, id, a_type, addrlen); } /* we want to cache addresses or the lack of any addresses */ add_to_cache (&session->request, &session->response); if (session->response.cname[0] && (session->response.count == 0)) { resolve_cname (session); return; } out = g_io_stream_get_output_stream (G_IO_STREAM (session->connection)); g_output_stream_write_all_async (out, &session->response, sizeof (session->response), G_PRIORITY_DEFAULT, NULL, on_sent, session); g_debug ("Done resolving %s with %hhu %s result(s)", session->request.name, session->response.count, (session->request.af == AF_INET) ? "IPv4" : "IPv6"); return; cleanup: if (session->response.count == 0) { stop_session (session); } } /* step 3: we received the HTTPS response, parse it to construct our response * and send it to libnss_tls */ static void on_response (GObject *source_object, GAsyncResult *res, gpointer user_data) { g_autoptr(GError) err = NULL; struct nss_tls_session *session = (struct nss_tls_session *)user_data; g_autoptr(GInputStream) in = NULL; const char *type; in = soup_session_send_finish (SOUP_SESSION (source_object), res, &err); if (!in) { if (err) { g_warning ("Failed to query %s: %s", session->request.name, err->message); } else { g_warning ("Failed to query %s", session->request.name); } goto cleanup; } if (!SOUP_STATUS_IS_SUCCESSFUL (session->message->status_code)) { g_warning ("Failed to query %s: HTTP %d", session->request.name, session->message->status_code); goto cleanup; } type = soup_message_headers_get_content_type ( session->message->response_headers, NULL ); if (type && strcmp (type, "application/dns-message")) { g_warning ("Bad response type for %s: %s", session->request.name, type); goto cleanup; } g_input_stream_read_all_async (in, session->dns, sizeof (session->dns), G_PRIORITY_DEFAULT, NULL, on_body, session); g_object_unref (session->message); return; cleanup: g_object_unref (session->message); if (session->response.count == 0) { stop_session (session); } } /* * we don't want to leak the local domain to the DoH server provider (for * example, it may indicate a router model) and we don't want to waste time on * this query if it's going to fail anyway */ static gboolean is_suffixed (const gchar *name) { struct __res_state res; gchar *suffix; gboolean ret; guint i; if (res_ninit (&res) < 0) { return FALSE; } for (i = 0; (i < G_N_ELEMENTS (res.dnsrch)) && res.dnsrch[i]; ++i) { suffix = g_strconcat (".", res.dnsrch[i], NULL); ret = g_str_has_suffix (name, suffix); g_free (suffix); if (ret) { g_debug ("%s is suffixed by a local domain", name); return ret; } } return FALSE; } /* * the DoH server addresses must be resolved by other means, otherwise this * results in infinite recursion */ static gboolean is_server_domain (const gchar *name) { gint i; for (i = 0; i < nresolvers; ++i) { if (strcmp (name, resolvers[i].domain) == 0) { g_debug ("%s is a DoH server domain", name); return TRUE; } } return FALSE; } /* step 2: we received a request from libnss_tls and send a HTTPS request */ static void on_request (GObject *source_object, GAsyncResult *res, gpointer user_data) { g_autoptr(GError) err = NULL; struct nss_tls_session *session = user_data; gsize len; if (!g_input_stream_read_all_finish (G_INPUT_STREAM (source_object), res, &len, &err)) { if (err) { g_warning ("Failed to receive a request: %s", err->message); } else { g_warning ("Failed to receive a request"); } goto fail; } if (len != sizeof (session->request)) { g_debug ("Bad request"); goto fail; } session->request.name[sizeof (session->request.name) - 1] = '\0'; if (is_suffixed (session->request.name) || is_server_domain (session->request.name)) { goto fail; } if (resolve_domain (session)) { return; } fail: stop_session (session); } /* step 1: we accept a new connection from libnss_tls and wait for it to send a * request */ static void on_connection (GSocketService *service, GSocketConnection *connection, GObject *source_object, gpointer user_data) { GSocket *s; struct nss_tls_session *session; GInputStream *in; /* we disconnect the client after NSS_TLS_TIMEOUT seconds */ s = g_socket_connection_get_socket (connection); g_socket_set_timeout (s, NSS_TLS_TIMEOUT); session = g_new0 (struct nss_tls_session, 1); session->connection = g_object_ref (connection); session->response.count = 0; session->response.expiry = -1; /* we assume the domain is not canonical */ session->canon = FALSE; in = g_io_stream_get_input_stream (G_IO_STREAM (connection)); /* read the incoming request */ g_input_stream_read_all_async (in, &session->request, sizeof (session->request), G_PRIORITY_DEFAULT, NULL, on_request, session); } static gboolean on_term (gpointer user_data) { g_main_loop_quit ((GMainLoop *)user_data); return FALSE; } static void parse_cfg (const gboolean root); static void update_cfg (const gboolean root) { gint pnresolvers = nresolvers, i; if (cfg_monitor) { g_object_unref (cfg_monitor); cfg_monitor = NULL; g_object_unref (cfg_file); } if (resolv_conf_monitor) { g_object_unref (resolv_conf_monitor); resolv_conf_monitor = NULL; g_object_unref (resolv_conf); } parse_cfg (root); for (i = 0; i < pnresolvers; ++i) { soup_uri_free (resolvers[i].uri); g_free (resolvers[i].url); } nresolvers -= pnresolvers; memcpy (resolvers, &resolvers[pnresolvers], sizeof (resolvers[0]) * nresolvers); } static void on_cfg_changed (GFileMonitor *monitor, GFile *file, GFile *other_file, GFileMonitorEvent event_type, gpointer user_data) { gboolean root = (gboolean)(gintptr)user_data; if ((event_type != G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT) && (event_type != G_FILE_MONITOR_EVENT_DELETED)) { return; } update_cfg (root); } static void watch_file (const gchar *path, const gboolean root, GFile **file, GFileMonitor **mon) { *file = g_file_new_for_path (path); *mon = g_file_monitor_file (*file, G_FILE_MONITOR_NONE, NULL, NULL); if (*mon) { g_signal_connect (*mon, "changed", G_CALLBACK (on_cfg_changed), (gpointer)(gintptr)root); } else { g_object_unref (*file); *file = NULL; } } static void watch_cfg (const gchar *path, const gboolean root) { return watch_file (path, root, &cfg_file, &cfg_monitor); } static void watch_resolv_conf (const gchar *path, const gboolean root) { return watch_file (path, root, &resolv_conf, &resolv_conf_monitor); } static void add_resolver (const char *addr) { if (strchr (addr, ':')) { resolvers[nresolvers].url = g_strconcat ("https://[", addr, "]/dns-query", NULL); } else { resolvers[nresolvers].url = g_strconcat ("https://", addr, "/dns-query", NULL); } resolvers[nresolvers].uri = soup_uri_new (resolvers[nresolvers].url); resolvers[nresolvers].domain = soup_uri_get_host (resolvers[nresolvers].uri); resolvers[nresolvers].method = NSS_TLS_METHOD_POST; ++nresolvers; } static gchar * find_resolv_conf (void) { g_autofree gchar *rpath = NULL; #ifdef NSS_TLS_SYSTEMD g_autofree gchar *base = NULL, *dir = NULL; #endif gchar *tmp; rpath = g_file_read_link (_PATH_RESCONF, NULL); if (!rpath) { return g_strdup (_PATH_RESCONF); } #ifdef NSS_TLS_SYSTEMD /* * hack for systems with systemd: systemd-resolved hijacks * /etc/resolv.conf by replacing it with a symlink to * /run/systemd/resolve/stub-resolv.conf and the actual DNS servers * are specified in /run/systemd/resolve/resolv.conf */ base = g_path_get_basename (rpath); if (strcmp (base, "stub-resolv.conf") == 0) { dir = g_path_get_dirname (rpath); return g_build_filename (dir, "resolv.conf", NULL); } #endif tmp = rpath; rpath = NULL; return tmp; } static void use_dns_servers (const gchar *path) { GFile *file; GFileInputStream *fio; GDataInputStream *in; char *line; g_debug ("Parsing %s", path); if (nresolvers >= G_N_ELEMENTS (resolvers)) { return; } file = g_file_new_for_path (path); if (!file) { return; } fio = g_file_read (file, NULL, NULL); if (!fio) { g_object_unref (file); return; } in = g_data_input_stream_new (G_INPUT_STREAM (fio)); if (in) { do { line = g_data_input_stream_read_line (in, NULL, NULL, NULL); if (!line) { break; } if (g_str_has_prefix (line, "nameserver ")) { add_resolver (&line[sizeof("nameserver ") - 1]); if (nresolvers >= G_N_ELEMENTS (resolvers)) { g_free (line); break; } } g_free (line); } while (1); g_object_unref (in); } g_object_unref (file); g_object_unref (fio); } static void parse_cfg (const gboolean root) { GValue val = G_VALUE_INIT; const gchar *dirs[3] = {NULL, NULL, NULL}; g_autofree gchar *user_dir = NULL; gchar **list, **p; g_autofree gchar *path = NULL, *resconf = NULL; char *plus; g_autoptr(GKeyFile) cfg = NULL; g_autoptr(GError) err = NULL; if (root) { dirs[0] = NSS_TLS_SYSCONFDIR; } else { dirs[0] = g_get_user_config_dir (); if (dirs[0]) { dirs[1] = NSS_TLS_SYSCONFDIR; } else { user_dir = g_build_filename (g_get_home_dir (), ".config", NULL); if (user_dir) { dirs[0] = user_dir; dirs[1] = NSS_TLS_SYSCONFDIR; } else { dirs[0] = NSS_TLS_SYSCONFDIR; } } } cfg = g_key_file_new (); if (!g_key_file_load_from_dirs (cfg, NSS_TLS_CONF_NAME, dirs, &path, G_KEY_FILE_NONE, &err)) { if (g_error_matches (err, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_NOT_FOUND)) { resconf = find_resolv_conf (); use_dns_servers (resconf); } goto parsed; } g_key_file_set_list_separator (cfg, ','); list = g_key_file_get_string_list (cfg, "global", "resolvers", NULL, &err); if (!list) { if (g_error_matches (err, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_KEY_NOT_FOUND)) { resconf = find_resolv_conf (); use_dns_servers (resconf); } goto parsed; } if (!list[0]) { resconf = find_resolv_conf (); use_dns_servers (resconf); goto parsed; } for (p = list; *p && (nresolvers < G_N_ELEMENTS (resolvers)); ++p) { plus = strchr (*p, '+'); if (plus) { *plus = '\0'; ++plus; } resolvers[nresolvers].uri = soup_uri_new (*p); if (!resolvers[nresolvers].uri) { g_warning ("Bad resolver: %s", *p); g_free (*p); continue; } resolvers[nresolvers].url = *p; resolvers[nresolvers].domain = soup_uri_get_host (resolvers[nresolvers].uri); resolvers[nresolvers].method = NSS_TLS_METHOD_POST; if (plus) { if (strcmp (plus, "get") == 0) { resolvers[nresolvers].method = NSS_TLS_METHOD_GET; } else if (strcmp (plus, "random") == 0) { resolvers[nresolvers].method = NSS_TLS_METHOD_RANDOM; } else if (strcmp (plus, "post")) { g_warning ("Unknown resolving method: %s", plus); } } ++nresolvers; } g_free (list); parsed: if (randomize && (nresolvers > 1)) { g_warning ("Disabling deterministic server choice may harm privacy"); } if (nresolvers > 0) { g_value_init (&val, G_TYPE_INT); g_value_set_int (&val, MAX_CONNS_PER_RESOLVER * nresolvers); g_object_set_property (G_OBJECT (soup), SOUP_SESSION_MAX_CONNS, &val); } if (path) { watch_cfg (path, root); } if (resconf) { watch_resolv_conf (resconf, root); } } static GOptionEntry opts[] = { {"cache", 'c', 0, G_OPTION_ARG_NONE, &cache, "Cache responses", NULL}, { "random", 'r', 0, G_OPTION_ARG_NONE, &randomize, "Choose a random server every time", NULL } }; static gboolean parse_cmdline (int argc, char **argv) { GOptionContext *ctx; gboolean ret; ctx = g_option_context_new (NULL); g_option_context_add_main_entries (ctx, opts, NULL); ret = g_option_context_parse (ctx, &argc, &argv, NULL); g_option_context_free (ctx); return ret; } int main (int argc, char **argv) { static char root_socket[] = NSS_TLS_SOCKET_PATH; GMainLoop *loop; GSocketService *s; GSocketAddress *sa; const gchar *runtime_dir; gchar *dir; struct passwd *user; gchar *user_socket = root_socket; #ifdef NSS_TLS_DEBUG static SoupLogger *logger; #endif int mode = 0600; gint i; uid_t uid; gid_t gid; gboolean root; if (!parse_cmdline (argc, argv)) { return EXIT_FAILURE; } root = (geteuid () == 0); if (root) { user = getpwnam (NSS_TLS_USER); if (!user) { return EXIT_FAILURE; } uid = user->pw_uid; gid = user->pw_gid; /* * create a directory owned by a non-privileged user, where we put the * socket */ if (((mkdir (NSS_TLS_SOCKET_DIR, 0755) < 0) && ((errno != EEXIST) || (chmod (NSS_TLS_SOCKET_DIR, 0755) < 0))) || (chown (NSS_TLS_SOCKET_DIR, uid, gid) < 0) || (setgroups (1, &gid) < 0) || (setgid (gid) < 0) || (setuid (uid) < 0)) { return EXIT_FAILURE; } mode = 0666; } else { runtime_dir = g_get_user_runtime_dir (); if (!runtime_dir) { return EXIT_FAILURE; } user_socket = g_build_filename (runtime_dir, NSS_TLS_SOCKET_NAME, NULL); } if (root && cache) { g_warning ("Enabling cache when running as root may harm privacy"); } if (cache) { for (i = 0; i < G_N_ELEMENTS (caches); ++i) { caches[i] = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); } } /* * /etc/resolv.conf may be a relative symlink and we want to support GLib * versions that don't have g_canonicalize_filename() */ dir = g_path_get_dirname (_PATH_RESCONF); if (dir) { chdir (dir); g_free (dir); } soup = soup_session_new_with_options (SOUP_SESSION_TIMEOUT, NSS_TLS_TIMEOUT, SOUP_SESSION_IDLE_TIMEOUT, NSS_TLS_TIMEOUT, SOUP_SESSION_MAX_CONNS_PER_HOST, MAX_CONNS_PER_RESOLVER, NULL); #ifdef NSS_TLS_DEBUG logger = soup_logger_new (SOUP_LOGGER_LOG_BODY, 128); soup_session_add_feature (soup, SOUP_SESSION_FEATURE (logger)); #endif parse_cfg (root); g_unlink (user_socket); sa = g_unix_socket_address_new (user_socket); s = g_socket_service_new (); loop = g_main_loop_new (NULL, FALSE); if (cache) { g_timeout_add_seconds (CACHE_CLEANUP_INTERVAL, on_cache_cleanup, NULL); } g_socket_listener_add_address (G_SOCKET_LISTENER (s), sa, G_SOCKET_TYPE_STREAM, 0, NULL, NULL, NULL); g_signal_connect (s, "incoming", G_CALLBACK (on_connection), NULL); g_socket_service_start (s); g_chmod (user_socket , mode); g_unix_signal_add (SIGINT, on_term, loop); g_unix_signal_add (SIGTERM, on_term, loop); g_main_loop_run (loop); for (i = 0; i < nresolvers; ++i) { soup_uri_free (resolvers[i].uri); g_free (resolvers[i].url); } g_main_loop_unref (loop); g_object_unref (s); g_unlink (user_socket); if (user_socket != root_socket) { g_free (user_socket); } g_object_unref (sa); if (cfg_monitor) { g_object_unref (cfg_monitor); g_object_unref (cfg_file); } if (resolv_conf_monitor) { g_object_unref (resolv_conf_monitor); g_object_unref (resolv_conf); } if (cache) { for (i = G_N_ELEMENTS (caches) - 1; i >= 0; --i) { g_hash_table_unref (caches[i]); } } return EXIT_SUCCESS; } nss-tls-1.1/nss-tlsd.service.in000066400000000000000000000020441370415710700165210ustar00rootroot00000000000000# This file is part of nss-tls. # # Copyright (C) 2018 Dima Krasner # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA [Unit] Description=NSS TLS Daemon Documentation=man:nss-tlsd(8) Documentation=https://github.com/dimkr/nss-tls [Service] Type=simple ExecStart=@nss_tlsd_path@ StandardOutput=null StandardError=null Restart=on-failure [Install] WantedBy=network-online.target nss-tls-1.1/tlslookup.1000066400000000000000000000007061370415710700151040ustar00rootroot00000000000000.TH tlslookup 1 .SH NAME .B tlslookup \- resolve the internet address with DNS queries over HTTPS/TLS .SH SYNOPSIS .B tlslookup \fIhost\fR .SH DESCRIPTION Similar to nslookup(1), tlslookup is a program to query internet domain name servers. tlslookup resolves the internet address of \fIhost\fR with DNS queries over HTTPS/TLS by talking to the nss-tlsd(8) daemon. .SH "SEE ALSO" .B nss-tlsd(8), nslookup(1) .SH AUTHOR Dima Krasner (dima@dimakrasner.com)nss-tls-1.1/tlslookup.c000066400000000000000000000052451370415710700151710ustar00rootroot00000000000000/* * This file is part of nss-tls. * * Copyright (C) 2019 Dima Krasner * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include #include #include #include "nss-tls.h" extern enum nss_status _nss_tls_gethostbyname2_r(const char *name, int af, struct hostent *ret, char *buf, size_t buflen, int *errnop, int *h_errnop); int main(int argc, char *argv[]) { struct nss_tls_data data; struct hostent ent; char buf[INET6_ADDRSTRLEN]; int err, h_err, i, afs[] = {AF_INET, AF_INET6}; uint16_t total = 0; uint8_t j; if (argc != 2) { fprintf(stderr, "Usage: tlslookup HOST\n" "Resolve the internet address of HOST.\n"); return EXIT_FAILURE; } for (i = 0; i < sizeof(afs) / sizeof(afs[0]); ++i) { switch (_nss_tls_gethostbyname2_r(argv[1], afs[i], &ent, (char *)&data, sizeof(data), &err, &h_err)) { case NSS_STATUS_SUCCESS: break; case NSS_STATUS_NOTFOUND: continue; default: return EXIT_FAILURE; } for (j = 0; j < data.res.count; ++j) { if (!inet_ntop(afs[i], &data.res.addrs[j], buf, sizeof(buf)) || (puts(buf) == EOF)) return EXIT_FAILURE; } total += data.res.count; } if (total == 0) return EXIT_FAILURE; return EXIT_SUCCESS; }