├── .github ├── FUNDING.yml └── workflows │ ├── release.yml │ └── test.yml ├── .gitignore ├── .goreleaser.yml ├── Dockerfile ├── LICENSE ├── README.md ├── carbon.svg ├── cli └── cli.go ├── coverage_badge.png ├── go.mod ├── go.sum ├── main.go ├── main_test.go ├── output ├── output.go ├── output_test.go ├── pretty.go ├── pretty_test.go ├── raw.go └── structured.go ├── resolver.go ├── transport ├── LICENSE ├── dnscrypt.go ├── dnscrypt_test.go ├── http.go ├── http_test.go ├── odoh.go ├── odoh_test.go ├── plain.go ├── plain_test.go ├── quic.go ├── quic_test.go ├── tls.go ├── tls_test.go ├── transport.go └── transport_test.go ├── update-usage-readme.sh ├── util ├── tls │ └── tls.go ├── util.go └── util_test.go └── xfr.go /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: ["natesales"] 4 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: goreleaser 2 | 3 | on: 4 | push: 5 | tags: 6 | - "v*" 7 | 8 | jobs: 9 | goreleaser: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout 13 | uses: actions/checkout@v4 14 | with: 15 | fetch-depth: 0 16 | - name: Set up Go 17 | uses: actions/setup-go@v4 18 | with: 19 | go-version: 1.21 20 | - name: Docker Login 21 | uses: docker/login-action@v3 22 | with: 23 | registry: ghcr.io 24 | username: ${{ github.repository_owner }} 25 | password: ${{ secrets.GITHUB_TOKEN }} 26 | - name: Run GoReleaser 27 | uses: goreleaser/goreleaser-action@v5 28 | with: 29 | version: latest 30 | args: release --clean 31 | env: 32 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} 33 | FURY_TOKEN: ${{ secrets.FURY_TOKEN }} 34 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Run tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | paths: 8 | - "*.go" 9 | - ".github/workflows/*" 10 | - "README.md" 11 | 12 | pull_request: 13 | paths: 14 | - "*.go" 15 | - ".github/workflows/*" 16 | - "README.md" 17 | 18 | jobs: 19 | build: 20 | name: Build 21 | runs-on: ubuntu-latest 22 | steps: 23 | - uses: actions/setup-go@v4 24 | with: 25 | go-version: 1.21 26 | - uses: actions/checkout@v3 27 | - run: go build -v ./... 28 | - run: go install github.com/jpoles1/gopherbadger@latest 29 | - run: go install github.com/gotesttools/gotestfmt/v2/cmd/gotestfmt@latest 30 | 31 | # Run tests with nice formatting. Save the original log in /tmp/gotest.log 32 | - name: Run tests 33 | run: | 34 | set -euo pipefail 35 | go test -p 1 -json -v -covermode atomic -coverprofile=cover.out ./... 2>&1 | tee /tmp/gotest.log | gotestfmt 36 | 37 | - name: Upload original test log 38 | uses: actions/upload-artifact@v4 39 | if: always() 40 | with: 41 | name: test-log 42 | path: /tmp/gotest.log 43 | if-no-files-found: error 44 | 45 | - name: Generate coverage badge 46 | run: gopherbadger -style=for-the-badge -covercmd "go tool cover -func=cover.out" 47 | 48 | - name: Commit coverage badge 49 | uses: EndBug/add-and-commit@v7 50 | with: 51 | message: "ci: update coverage" 52 | add: "coverage_badge.png" 53 | author_name: "github-actions[bot]" 54 | author_email: "github-actions[bot]@users.noreply.github.com" 55 | 56 | - run: ./update-usage-readme.sh 57 | 58 | - name: Commit README update 59 | uses: EndBug/add-and-commit@v7 60 | with: 61 | message: "ci: update binary usage in README" 62 | add: "README.md" 63 | author_name: "github-actions[bot]" 64 | author_email: "github-actions[bot]@users.noreply.github.com" 65 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | dist/ 3 | q 4 | cover.out 5 | README.tmp.md 6 | *_recaxfr/ 7 | -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | before: 2 | hooks: 3 | - go mod download 4 | builds: 5 | - env: 6 | - CGO_ENABLED=0 7 | goos: 8 | - linux 9 | - darwin 10 | - freebsd 11 | - windows 12 | goarch: 13 | - amd64 14 | - arm64 15 | scoop: 16 | name: q 17 | commit_author: 18 | name: natesales 19 | email: nate@natesales.net 20 | commit_msg_template: Scoop update for {{ .ProjectName }} version {{ .Tag }} 21 | checksum: 22 | name_template: "checksums.txt" 23 | snapshot: 24 | name_template: "{{ .Tag }}-next" 25 | changelog: 26 | sort: asc 27 | filters: 28 | exclude: 29 | - "^docs:" 30 | - "^test:" 31 | nfpms: 32 | - id: nfpm-default 33 | package_name: q 34 | file_name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}" 35 | vendor: Nate Sales 36 | homepage: https://natesales.net/ 37 | maintainer: Nate Sales 38 | description: A tiny CLI DNS client library with support for UDP, TCP, DoT, DoH, and DoQ. 39 | license: GNU GPL-3.0 40 | section: utils 41 | priority: extra 42 | formats: 43 | - deb 44 | - rpm 45 | publishers: 46 | - name: fury.io 47 | ids: 48 | - nfpm-default 49 | dir: "{{ dir .ArtifactPath }}" 50 | cmd: curl -s -F package=@{{ .ArtifactName }} https://{{ .Env.FURY_TOKEN }}@push.fury.io/natesales/ 51 | brews: 52 | - name: q 53 | homepage: https://github.com/natesales/repo 54 | repository: 55 | owner: natesales 56 | name: repo 57 | dockers: 58 | - image_templates: 59 | - "ghcr.io/natesales/q:{{ .Version }}-amd64" 60 | use: buildx 61 | build_flag_templates: 62 | - --platform=linux/amd64 63 | - --label=org.opencontainers.image.version={{ .Version }} 64 | - --label=org.opencontainers.image.revision={{ .FullCommit }} 65 | - --label=org.opencontainers.image.licenses=GPL-3.0-only 66 | - image_templates: 67 | - "ghcr.io/natesales/q:{{ .Version }}-arm64" 68 | use: buildx 69 | build_flag_templates: 70 | - --platform=linux/arm64 71 | - --label=org.opencontainers.image.version={{ .Version }} 72 | - --label=org.opencontainers.image.revision={{ .FullCommit }} 73 | - --label=org.opencontainers.image.licenses=GPL-3.0-only 74 | goarch: arm64 75 | docker_manifests: 76 | - name_template: "ghcr.io/natesales/q:{{ .Version }}" 77 | image_templates: 78 | - "ghcr.io/natesales/q:{{ .Version }}-amd64" 79 | - "ghcr.io/natesales/q:{{ .Version }}-arm64" 80 | - name_template: "ghcr.io/natesales/q:latest" 81 | image_templates: 82 | - "ghcr.io/natesales/q:{{ .Version }}-amd64" 83 | - "ghcr.io/natesales/q:{{ .Version }}-arm64" 84 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:latest 2 | COPY q /usr/bin/q 3 | ENTRYPOINT ["/usr/bin/q"] 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |

q

3 | 4 | A tiny and feature-rich command line DNS client with support for UDP, TCP, DoT, DoH, DoQ, and ODoH. 5 | 6 | [![Release](https://img.shields.io/github/v/release/natesales/q?style=for-the-badge)](https://github.com/natesales/q/releases) 7 | ![Coverage](coverage_badge.png) 8 | [![Go Report](https://goreportcard.com/badge/github.com/natesales/q?style=for-the-badge)](https://goreportcard.com/report/github.com/natesales/q) 9 | [![License](https://img.shields.io/github/license/natesales/q?style=for-the-badge)](https://raw.githubusercontent.com/natesales/q/main/LICENSE) 10 | 11 | ![q screenshot](carbon.svg) 12 |
13 | 14 | ### Examples 15 | 16 | ```text 17 | q example.com Lookup default records for a domain 18 | q example.com MX SOA ...or specify a list of types 19 | 20 | q example.com MX @9.9.9.9 Query a specific server 21 | q example.com MX @https://dns.quad9.net ...over HTTPS (or TCP, TLS, QUIC, or ODoH)... 22 | q @sdns://AgcAAAAAAAAAAAAHOS45LjkuOQA ...or from a DNS Stamp 23 | 24 | q example.com MX --format=raw Output in raw (dig) format 25 | q example.com MX --format=json ...or as JSON (or YAML) 26 | ``` 27 | 28 | ### Usage 29 | 30 | ```text 31 | Usage: 32 | q [OPTIONS] [@server] [type...] [name] 33 | 34 | All long form (--) flags can be toggled with the dig-standard +[no]flag notation. 35 | 36 | Application Options: 37 | -q, --qname= Query name 38 | -s, --server= DNS server(s) 39 | -t, --type= RR type (e.g. A, AAAA, MX, etc.) or type 40 | integer 41 | -x, --reverse Reverse lookup 42 | -d, --dnssec Set the DO (DNSSEC OK) bit in the OPT record 43 | -n, --nsid Set EDNS0 NSID opt 44 | -N, --nsid-only Set EDNS0 NSID opt and query only for the NSID 45 | --subnet= Set EDNS0 client subnet 46 | -c, --chaos Use CHAOS query class 47 | -C= Set query class (default: IN 0x01) (default: 48 | 1) 49 | -p, --odoh-proxy= ODoH proxy 50 | --timeout= Query timeout (default: 10s) 51 | --pad Set EDNS0 padding 52 | --http2 Use HTTP/2 for DoH 53 | --http3 Use HTTP/3 for DoH 54 | --id-check Check DNS response ID (default: true) 55 | --reuse-conn Reuse connections across queries to the same 56 | server (default: true) 57 | --txtconcat Concatenate TXT responses 58 | --qid= Set query ID (-1 for random) (default: -1) 59 | -b, --bootstrap-server= DNS server to use for bootstrapping 60 | --bootstrap-timeout= Bootstrapping timeout (default: 5s) 61 | --cookie= EDNS0 cookie 62 | --recaxfr Perform recursive AXFR 63 | -f, --format= Output format (pretty, column, json, yaml, 64 | raw) (default: pretty) 65 | --pretty-ttls Format TTLs in human readable format 66 | (default: true) 67 | --short-ttls Remove zero components of pretty TTLs. 68 | (24h0m0s->24h) (default: true) 69 | --color Enable color output 70 | --question Show question section 71 | --opt Show OPT records 72 | --answer Show answer section (default: true) 73 | --authority Show authority section 74 | --additional Show additional section 75 | -S, --stats Show time statistics 76 | --all Show all sections and statistics 77 | -w Resolve ASN/ASName for A and AAAA records 78 | -r, --short Show record values only 79 | -R, --resolve-ips Resolve PTR records for IP addresses in A and 80 | AAAA records 81 | --round-ttls Round TTLs to the nearest minute 82 | --aa Set AA (Authoritative Answer) flag in query 83 | --ad Set AD (Authentic Data) flag in query 84 | --cd Set CD (Checking Disabled) flag in query 85 | --rd Set RD (Recursion Desired) flag in query 86 | (default: true) 87 | --ra Set RA (Recursion Available) flag in query 88 | --z Set Z (Zero) flag in query 89 | --t Set TC (Truncated) flag in query 90 | -i, --tls-insecure-skip-verify Disable TLS certificate verification 91 | --tls-server-name= TLS server name for host verification 92 | --tls-min-version= Minimum TLS version to use (default: 1.0) 93 | --tls-max-version= Maximum TLS version to use (default: 1.3) 94 | --tls-next-protos= TLS next protocols for ALPN 95 | --tls-cipher-suites= TLS cipher suites 96 | --tls-curve-preferences= TLS curve preferences 97 | --tls-client-cert= TLS client certificate file 98 | --tls-client-key= TLS client key file 99 | --tls-key-log-file= TLS key log file [$SSLKEYLOGFILE] 100 | --http-user-agent= HTTP user agent 101 | --http-method= HTTP method (default: GET) 102 | --pmtud PMTU discovery (default: true) 103 | --quic-alpn-tokens= QUIC ALPN tokens (default: doq, doq-i11) 104 | --quic-length-prefix Add RFC 9250 compliant length prefix 105 | (default: true) 106 | --dnscrypt-tcp Use TCP for DNSCrypt (default UDP) 107 | --dnscrypt-udp-size= Maximum size of a DNS response this client 108 | can sent or receive (default: 0) 109 | --dnscrypt-key= DNSCrypt public key 110 | --dnscrypt-provider= DNSCrypt provider name 111 | --default-rr-types= Default record types (default: A, AAAA, NS, 112 | MX, TXT, CNAME) 113 | --udp-buffer= Set EDNS0 UDP size in query (default: 1232) 114 | -v, --verbose Show verbose log messages 115 | --trace Show trace log messages 116 | -V, --version Show version and exit 117 | 118 | Help Options: 119 | -h, --help Show this help message 120 | ``` 121 | 122 | ### Demo 123 | 124 | [![asciicast](https://asciinema.org/a/XdWPPvZgx4hEBFwGnGwL13bsZ.svg)](https://asciinema.org/a/XdWPPvZgx4hEBFwGnGwL13bsZ) 125 | 126 | ### Protocol Support 127 | 128 | - UDP/TCP DNS ([RFC 1034](https://tools.ietf.org/html/rfc1034)) 129 | - DNS over TLS ([RFC 7858](https://tools.ietf.org/html/rfc7858)) 130 | - DNS over HTTPS ([RFC 8484](https://tools.ietf.org/html/rfc8484)) 131 | - DNS over QUIC ([RFC 9250](https://tools.ietf.org/html/rfc9250)) 132 | - Oblivious DNS over HTTPS ([RFC 9230](https://tools.ietf.org/html/rfc9230)) 133 | - DNSCrypt v2 ([draft-dennis-dprive-dnscrypt](https://dnscrypt.github.io/dnscrypt-protocol/draft-denis-dprive-dnscrypt.html)) 134 | 135 | ### Installation 136 | 137 | `q` is available from: 138 | 139 | - [apt/yum/brew from my package repositories](https://github.com/natesales/repo) 140 | - [GitHub releases](https://github.com/natesales/q/releases) 141 | - [q-dns-git](https://aur.archlinux.org/packages/q-dns-git/) in the AUR 142 | - `go install github.com/natesales/q@latest` 143 | - `docker run --rm -it ghcr.io/natesales/q` 144 | 145 | To install `q` from source: 146 | 147 | ```sh 148 | git clone https://github.com/natesales/q && cd q 149 | go install 150 | 151 | # Without debug information 152 | go install -ldflags="-s -w -X main.version=release" 153 | ``` 154 | 155 | ### Server Selection 156 | 157 | `q` will use a server from the following sources, in order: 158 | 159 | 1. `@server` argument (e.g. `@9.9.9.9` or `@https://dns.google/dns-query`) 160 | 2. `Q_DEFAULT_SERVER` environment variable 161 | 3. `/etc/resolv.conf` 162 | 163 | ### TLS Decryption 164 | 165 | `q` supports TLS decryption through a key log file generated when 166 | the `SSLKEYLOGFILE` environment variable is set to a file path. 167 | 168 | ### Feature Comparison 169 | 170 | | Protocol | q | doggo | dog | kdig | dig | drill | 171 | |:------------------------------|:-:|:-----:|:---:|:----:|:---:|:-----:| 172 | | **Transport Protocols** | | | | | | | 173 | | UDP/TCP | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 174 | | DNS over TLS | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | 175 | | DNS over HTTPS | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | 176 | | DNS over QUIC | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | 177 | | Oblivious DNS over HTTPS | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 178 | | DNSCrypt v2 | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | 179 | | **Features** | | | | | | | 180 | | Recursive AXFR | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 181 | | IP Whois | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 182 | | Resolve PTRs from A/AAAAs | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 183 | | Server from DNS Stamp | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | 184 | | **Output Formats** | | | | | | | 185 | | Raw (dig-style) | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | 186 | | Pretty colors | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | 187 | | JSON | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | 188 | | YAML | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | 189 | | **Output Control** | | | | | | | 190 | | Toggle question section | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | 191 | | Toggle answer section | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | 192 | | Toggle authority section | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | 193 | | Toggle additional section | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | 194 | | Show query time | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | 195 | | **Query Flags** | | | | | | | 196 | | AA | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 197 | | AD | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 198 | | CD | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 199 | | RD | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | 200 | | Z | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | 201 | | DO | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 202 | | TC | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | 203 | | **Protocol Tweaks** | | | | | | | 204 | | HTTP Method | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 205 | | QUIC ALPN Tokens | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 206 | | QUIC toggle PMTU discovery | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 207 | | QUIC timeouts (dial and idle) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 208 | | TLS handshake timeout | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 209 | -------------------------------------------------------------------------------- /cli/cli.go: -------------------------------------------------------------------------------- 1 | package cli 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | "strconv" 7 | "strings" 8 | "time" 9 | 10 | "github.com/miekg/dns" 11 | log "github.com/sirupsen/logrus" 12 | ) 13 | 14 | type Flags struct { 15 | Name string `short:"q" long:"qname" description:"Query name"` 16 | Server []string `short:"s" long:"server" description:"DNS server(s)"` 17 | Types []string `short:"t" long:"type" description:"RR type (e.g. A, AAAA, MX, etc.) or type integer"` 18 | Reverse bool `short:"x" long:"reverse" description:"Reverse lookup"` 19 | DNSSEC bool `short:"d" long:"dnssec" description:"Set the DO (DNSSEC OK) bit in the OPT record"` 20 | NSID bool `short:"n" long:"nsid" description:"Set EDNS0 NSID opt"` 21 | NSIDOnly bool `short:"N" long:"nsid-only" description:"Set EDNS0 NSID opt and query only for the NSID"` 22 | ClientSubnet string `long:"subnet" description:"Set EDNS0 client subnet"` 23 | Chaos bool `short:"c" long:"chaos" description:"Use CHAOS query class"` 24 | Class uint16 `short:"C" description:"Set query class (default: IN 0x01)" default:"1"` 25 | ODoHProxy string `short:"p" long:"odoh-proxy" description:"ODoH proxy"` 26 | Timeout time.Duration `long:"timeout" description:"Query timeout" default:"10s"` 27 | Pad bool `long:"pad" description:"Set EDNS0 padding"` 28 | HTTP2 bool `long:"http2" description:"Use HTTP/2 for DoH"` 29 | HTTP3 bool `long:"http3" description:"Use HTTP/3 for DoH"` 30 | IDCheck bool `long:"id-check" description:"Check DNS response ID (default: true)"` 31 | ReuseConn bool `long:"reuse-conn" description:"Reuse connections across queries to the same server (default: true)"` 32 | TXTConcat bool `long:"txtconcat" description:"Concatenate TXT responses"` 33 | ID int `long:"qid" description:"Set query ID (-1 for random)" default:"-1"` 34 | BootstrapServer string `short:"b" long:"bootstrap-server" description:"DNS server to use for bootstrapping"` 35 | BootstrapTimeout time.Duration `long:"bootstrap-timeout" description:"Bootstrapping timeout" default:"5s"` 36 | Cookie string `long:"cookie" description:"EDNS0 cookie"` 37 | 38 | // Special query modes 39 | RecAXFR bool `long:"recaxfr" description:"Perform recursive AXFR"` 40 | 41 | // Output 42 | Format string `short:"f" long:"format" description:"Output format (pretty, column, json, yaml, raw)" default:"pretty"` 43 | PrettyTTLs bool `long:"pretty-ttls" description:"Format TTLs in human readable format (default: true)"` 44 | ShortTTLs bool `long:"short-ttls" description:"Remove zero components of pretty TTLs. (24h0m0s->24h) (default: true)"` 45 | Color bool `long:"color" description:"Enable color output"` 46 | ShowQuestion bool `long:"question" description:"Show question section"` 47 | ShowOpt bool `long:"opt" description:"Show OPT records"` 48 | ShowAnswer bool `long:"answer" description:"Show answer section (default: true)"` 49 | ShowAuthority bool `long:"authority" description:"Show authority section"` 50 | ShowAdditional bool `long:"additional" description:"Show additional section"` 51 | ShowStats bool `short:"S" long:"stats" description:"Show time statistics"` 52 | ShowAll bool `long:"all" description:"Show all sections and statistics"` 53 | Whois bool `short:"w" description:"Resolve ASN/ASName for A and AAAA records"` 54 | ValueOnly bool `short:"r" long:"short" description:"Show record values only"` 55 | ResolveIPs bool `short:"R" long:"resolve-ips" description:"Resolve PTR records for IP addresses in A and AAAA records"` 56 | RoundTTLs bool `long:"round-ttls" description:"Round TTLs to the nearest minute"` 57 | 58 | // Header flags 59 | AuthoritativeAnswer bool `long:"aa" description:"Set AA (Authoritative Answer) flag in query"` 60 | AuthenticData bool `long:"ad" description:"Set AD (Authentic Data) flag in query"` 61 | CheckingDisabled bool `long:"cd" description:"Set CD (Checking Disabled) flag in query"` 62 | RecursionDesired bool `long:"rd" description:"Set RD (Recursion Desired) flag in query (default: true)"` 63 | RecursionAvailable bool `long:"ra" description:"Set RA (Recursion Available) flag in query"` 64 | Zero bool `long:"z" description:"Set Z (Zero) flag in query"` 65 | Truncated bool `long:"t" description:"Set TC (Truncated) flag in query"` 66 | 67 | // TLS parameters 68 | TLSInsecureSkipVerify bool `short:"i" long:"tls-insecure-skip-verify" description:"Disable TLS certificate verification"` 69 | TLSServerName string `long:"tls-server-name" description:"TLS server name for host verification"` 70 | TLSMinVersion string `long:"tls-min-version" description:"Minimum TLS version to use" default:"1.0"` 71 | TLSMaxVersion string `long:"tls-max-version" description:"Maximum TLS version to use" default:"1.3"` 72 | TLSNextProtos []string `long:"tls-next-protos" description:"TLS next protocols for ALPN"` 73 | TLSCipherSuites []string `long:"tls-cipher-suites" description:"TLS cipher suites"` 74 | TLSCurvePreferences []string `long:"tls-curve-preferences" description:"TLS curve preferences"` 75 | TLSClientCertificate string `long:"tls-client-cert" description:"TLS client certificate file"` 76 | TLSClientKey string `long:"tls-client-key" description:"TLS client key file"` 77 | TLSKeyLogFile string `long:"tls-key-log-file" env:"SSLKEYLOGFILE" description:"TLS key log file"` 78 | 79 | // HTTP 80 | HTTPUserAgent string `long:"http-user-agent" description:"HTTP user agent" default:""` 81 | HTTPMethod string `long:"http-method" description:"HTTP method" default:"GET"` 82 | 83 | PMTUD bool `long:"pmtud" description:"PMTU discovery (default: true)"` 84 | 85 | // QUIC 86 | QUICALPNTokens []string `long:"quic-alpn-tokens" description:"QUIC ALPN tokens" default:"doq" default:"doq-i11"` //nolint:golint,staticcheck 87 | QUICLengthPrefix bool `long:"quic-length-prefix" description:"Add RFC 9250 compliant length prefix (default: true)"` 88 | 89 | // DNSCrypt 90 | DNSCryptTCP bool `long:"dnscrypt-tcp" description:"Use TCP for DNSCrypt (default UDP)"` 91 | DNSCryptUDPSize int `long:"dnscrypt-udp-size" description:"Maximum size of a DNS response this client can sent or receive" default:"0"` 92 | DNSCryptPublicKey string `long:"dnscrypt-key" description:"DNSCrypt public key"` 93 | DNSCryptProvider string `long:"dnscrypt-provider" description:"DNSCrypt provider name"` 94 | 95 | DefaultRRTypes []string `long:"default-rr-types" description:"Default record types" default:"A" default:"AAAA" default:"NS" default:"MX" default:"TXT" default:"CNAME"` //nolint:golint,staticcheck 96 | 97 | UDPBuffer uint16 `long:"udp-buffer" description:"Set EDNS0 UDP size in query" default:"1232"` 98 | Verbose bool `short:"v" long:"verbose" description:"Show verbose log messages"` 99 | Trace bool `long:"trace" description:"Show trace log messages"` 100 | ShowVersion bool `short:"V" long:"version" description:"Show version and exit"` 101 | } 102 | 103 | // ParsePlusFlags parses a list of flags notated by +[no]flag and sets the corresponding opts fields 104 | func ParsePlusFlags(opts *Flags, args []string) { 105 | for _, arg := range args { 106 | if len(arg) > 3 && arg[0] == '+' { 107 | argFound := false 108 | 109 | flag := strings.ToLower(arg[3:]) 110 | state := arg[1:3] != "no" 111 | if state { 112 | flag = strings.ToLower(arg[1:]) 113 | } 114 | 115 | v := reflect.Indirect(reflect.ValueOf(opts)) 116 | vT := v.Type() 117 | for i := 0; i < v.NumField(); i++ { 118 | fieldTag := vT.Field(i).Tag.Get("long") 119 | if vT.Field(i).Type == reflect.TypeOf(true) && fieldTag == flag { 120 | argFound = true 121 | reflect.ValueOf(opts).Elem().Field(i).SetBool(state) 122 | break 123 | } 124 | } 125 | 126 | if !argFound { 127 | log.Fatalf("unknown flag %s", arg) 128 | } 129 | } 130 | } 131 | } 132 | 133 | // SetDefaultTrueBools enables boolean flags that are true by default 134 | func SetDefaultTrueBools(opts *Flags) { 135 | v := reflect.Indirect(reflect.ValueOf(opts)) 136 | vT := v.Type() 137 | for i := 0; i < v.NumField(); i++ { 138 | defaultTrue := strings.Contains(vT.Field(i).Tag.Get("description"), "default: true") 139 | if vT.Field(i).Type == reflect.TypeOf(true) && defaultTrue { 140 | reflect.ValueOf(opts).Elem().Field(i).SetBool(true) 141 | } 142 | } 143 | } 144 | 145 | // SetFalseBooleans sets boolean flags to false from a given argument list and returns the remaining arguments 146 | func SetFalseBooleans(opts *Flags, args []string) []string { 147 | // Add equal signs to separated flags (e.g. --foo bar becomes --foo=bar) 148 | for i, arg := range args { 149 | if arg[0] == '-' && !strings.Contains(arg, "=") && i+1 < len(args) && (args[i+1] == "true" || args[i+1] == "false") { 150 | args[i] = arg + "=" + args[i+1] 151 | args = append(args[:i+1], args[i+2:]...) 152 | } 153 | } 154 | 155 | var remainingArgs []string 156 | for _, arg := range args { 157 | if strings.HasSuffix(arg, "=true") || strings.HasSuffix(arg, "=false") { 158 | flag := strings.ToLower(strings.TrimLeft(arg, "-")) 159 | flag = strings.TrimSuffix(flag, "=true") 160 | flag = strings.TrimSuffix(flag, "=false") 161 | 162 | v := reflect.Indirect(reflect.ValueOf(opts)) 163 | vT := v.Type() 164 | for i := 0; i < v.NumField(); i++ { 165 | if vT.Field(i).Type == reflect.TypeOf(true) && (vT.Field(i).Tag.Get("long") == flag || vT.Field(i).Tag.Get("short") == flag) { 166 | boolState := strings.HasSuffix(arg, "=true") 167 | log.Tracef("Setting %s to %t", arg, boolState) 168 | reflect.ValueOf(opts).Elem().Field(i).SetBool(boolState) 169 | break 170 | } 171 | } 172 | } else { 173 | remainingArgs = append(remainingArgs, arg) 174 | } 175 | } 176 | 177 | log.Tracef("remaining args: %v", remainingArgs) 178 | return remainingArgs 179 | } 180 | 181 | // ParseRRTypes parses a list of RR types in string format ("A", "AAAA", etc.) or integer format (1, 28, etc.) 182 | func ParseRRTypes(t []string) (map[uint16]bool, error) { 183 | rrTypes := make(map[uint16]bool, len(t)) 184 | for _, rrType := range t { 185 | typeCode, ok := dns.StringToType[strings.ToUpper(rrType)] 186 | if ok { 187 | rrTypes[typeCode] = true 188 | } else { 189 | typeCode, err := strconv.Atoi(rrType) 190 | if err != nil { 191 | return nil, fmt.Errorf("%s is not a valid RR type", rrType) 192 | } 193 | log.Debugf("using RR type %d as integer", typeCode) 194 | rrTypes[uint16(typeCode)] = true 195 | } 196 | } 197 | return rrTypes, nil 198 | } 199 | 200 | // isBool checks if a flag by a given name is a boolean flag of Flags 201 | func isBool(name string) bool { 202 | v := reflect.ValueOf(Flags{}) 203 | vT := v.Type() 204 | for i := 0; i < v.NumField(); i++ { 205 | if vT.Field(i).Tag.Get("short") == name || vT.Field(i).Tag.Get("long") == name { 206 | return vT.Field(i).Type == reflect.TypeOf(true) 207 | } 208 | } 209 | return false 210 | } 211 | 212 | // AddEqualSigns adds equal signs between flags and their values, ignoring boolean flags 213 | func AddEqualSigns(args []string) []string { 214 | var newArgs []string 215 | skip := false 216 | for i, arg := range args { 217 | if skip { 218 | skip = false 219 | continue 220 | } 221 | 222 | isFlag := arg[0] == '-' 223 | flagName := strings.TrimLeft(arg, "-") 224 | 225 | if isFlag && isBool(flagName) { // Standalone boolean flag 226 | newArgs = append(newArgs, arg) 227 | } else if isFlag && !isBool(flagName) { // Flag with mapping 228 | if i+1 < len(args) && args[i+1][0] != '-' { // If the next argument is not a flag 229 | newArgs = append(newArgs, arg+"="+args[i+1]) 230 | skip = true 231 | } else { // If the next argument is a flag, add the flag as is 232 | newArgs = append(newArgs, arg) 233 | } 234 | } else { // Positional argument 235 | newArgs = append(newArgs, arg) 236 | } 237 | } 238 | 239 | return newArgs 240 | } 241 | -------------------------------------------------------------------------------- /coverage_badge.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/natesales/q/f59283880c34e7a0b3966df658c2f6b1cc6c4870/coverage_badge.png -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/natesales/q 2 | 3 | go 1.21 4 | 5 | require ( 6 | github.com/ameshkov/dnscrypt/v2 v2.2.7 7 | github.com/jedisct1/go-dnsstamps v0.0.0-20230211133001-124a632de565 8 | github.com/jessevdk/go-flags v1.5.0 9 | github.com/json-iterator/go v1.1.12 10 | github.com/miekg/dns v1.1.57 11 | github.com/natesales/bgptools-go v0.0.0-20230212051756-2b519d61269c 12 | github.com/quic-go/quic-go v0.40.0 13 | github.com/sirupsen/logrus v1.9.3 14 | github.com/sthorne/odoh-go v1.0.4 15 | github.com/stretchr/testify v1.8.4 16 | golang.org/x/net v0.19.0 17 | gopkg.in/yaml.v3 v3.0.1 18 | ) 19 | 20 | require ( 21 | github.com/AdguardTeam/golibs v0.18.1 // indirect 22 | github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da // indirect 23 | github.com/aead/poly1305 v0.0.0-20180717145839-3fee0db0b635 // indirect 24 | github.com/ameshkov/dnsstamps v1.0.3 // indirect 25 | github.com/cisco/go-hpke v0.0.0-20230407100446-246075f83609 // indirect 26 | github.com/cisco/go-tls-syntax v0.0.0-20200617162716-46b0cfb76b9b // indirect 27 | github.com/cloudflare/circl v1.3.6 // indirect 28 | github.com/davecgh/go-spew v1.1.1 // indirect 29 | github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect 30 | github.com/google/pprof v0.0.0-20231212022811-ec68065c825e // indirect 31 | github.com/kr/pretty v0.3.1 // indirect 32 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect 33 | github.com/modern-go/reflect2 v1.0.2 // indirect 34 | github.com/onsi/ginkgo/v2 v2.13.2 // indirect 35 | github.com/pmezard/go-difflib v1.0.0 // indirect 36 | github.com/quic-go/qpack v0.4.0 // indirect 37 | github.com/quic-go/qtls-go1-20 v0.4.1 // indirect 38 | go.uber.org/mock v0.3.0 // indirect 39 | golang.org/x/crypto v0.16.0 // indirect 40 | golang.org/x/exp v0.0.0-20231206192017-f3f8817b8deb // indirect 41 | golang.org/x/mod v0.14.0 // indirect 42 | golang.org/x/sys v0.15.0 // indirect 43 | golang.org/x/text v0.14.0 // indirect 44 | golang.org/x/tools v0.16.1 // indirect 45 | ) 46 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | git.schwanenlied.me/yawning/x448.git v0.0.0-20170617130356-01b048fb03d6/go.mod h1:wQaGCqEu44ykB17jZHCevrgSVl3KJnwQBObUtrKU4uU= 2 | github.com/AdguardTeam/golibs v0.18.1 h1:6u0fvrIj2qjUsRdbIGJ9AR0g5QRSWdKIo/DYl3tp5aM= 3 | github.com/AdguardTeam/golibs v0.18.1/go.mod h1:DKhCIXHcUYtBhU8ibTLKh1paUL96n5zhQBlx763sj+U= 4 | github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da h1:KjTM2ks9d14ZYCvmHS9iAKVt9AyzRSqNU1qabPih5BY= 5 | github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da/go.mod h1:eHEWzANqSiWQsof+nXEI9bUVUyV6F53Fp89EuCh2EAA= 6 | github.com/aead/poly1305 v0.0.0-20180717145839-3fee0db0b635 h1:52m0LGchQBBVqJRyYYufQuIbVqRawmubW3OFGqK1ekw= 7 | github.com/aead/poly1305 v0.0.0-20180717145839-3fee0db0b635/go.mod h1:lmLxL+FV291OopO93Bwf9fQLQeLyt33VJRUg5VJ30us= 8 | github.com/ameshkov/dnscrypt/v2 v2.2.7 h1:aEitLIR8HcxVodZ79mgRcCiC0A0I5kZPBuWGFwwulAw= 9 | github.com/ameshkov/dnscrypt/v2 v2.2.7/go.mod h1:qPWhwz6FdSmuK7W4sMyvogrez4MWdtzosdqlr0Rg3ow= 10 | github.com/ameshkov/dnsstamps v1.0.3 h1:Srzik+J9mivH1alRACTbys2xOxs0lRH9qnTA7Y1OYVo= 11 | github.com/ameshkov/dnsstamps v1.0.3/go.mod h1:Ii3eUu73dx4Vw5O4wjzmT5+lkCwovjzaEZZ4gKyIH5A= 12 | github.com/cisco/go-hpke v0.0.0-20210215210317-01c430f1f302/go.mod h1:RSsoIHRMBe69FbF/fIbmWYa3rrC6vuPyC0MbNUpel3Q= 13 | github.com/cisco/go-hpke v0.0.0-20230407100446-246075f83609 h1:+zUH9Y9OFBb59WFBFAQJTK25GGTby/g0DU7P+Pz1WaI= 14 | github.com/cisco/go-hpke v0.0.0-20230407100446-246075f83609/go.mod h1:RJ2C6TWlNvW2BlTT+YcexuRwIyzXter42/IRyb2sOTg= 15 | github.com/cisco/go-tls-syntax v0.0.0-20200617162716-46b0cfb76b9b h1:Ves2turKTX7zruivAcUOQg155xggcbv3suVdbKCBQNM= 16 | github.com/cisco/go-tls-syntax v0.0.0-20200617162716-46b0cfb76b9b/go.mod h1:0AZAV7lYvynZQ5ErHlGMKH+4QYMyNCFd+AiL9MlrCYA= 17 | github.com/cloudflare/circl v1.0.0/go.mod h1:MhjB3NEEhJbTOdLLq964NIUisXDxaE1WkQPUxtgZXiY= 18 | github.com/cloudflare/circl v1.3.6 h1:/xbKIqSHbZXHwkhbrhrt2YOHIwYJlXH94E3tI/gDlUg= 19 | github.com/cloudflare/circl v1.3.6/go.mod h1:5XYMA4rFBvNIrhs50XuiBJ15vF2pZn4nnUKZrLbUZFA= 20 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= 21 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 22 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 23 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 24 | github.com/go-logr/logr v1.3.0 h1:2y3SDp0ZXuc6/cjLSZ+Q3ir+QB9T/iG5yYRXqsagWSY= 25 | github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= 26 | github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= 27 | github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= 28 | github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= 29 | github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= 30 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 31 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 32 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 33 | github.com/google/pprof v0.0.0-20231212022811-ec68065c825e h1:bwOy7hAFd0C91URzMIEBfr6BAz29yk7Qj0cy6S7DJlU= 34 | github.com/google/pprof v0.0.0-20231212022811-ec68065c825e/go.mod h1:czg5+yv1E0ZGTi6S6vVK1mke0fV+FaUhNGcd6VRS9Ik= 35 | github.com/jedisct1/go-dnsstamps v0.0.0-20230211133001-124a632de565 h1:BPBMaUCgtmiHvqgugbSuegXjADJfERsPbmRqgdq8Pjo= 36 | github.com/jedisct1/go-dnsstamps v0.0.0-20230211133001-124a632de565/go.mod h1:mEGEFZsGe4sG5Mb3Xi89pmsy+TZ0946ArbYMGKAM5uA= 37 | github.com/jessevdk/go-flags v1.5.0 h1:1jKYvbxEjfUl0fmqTCOfonvskHHXMjBySTLW4y9LFvc= 38 | github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4= 39 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= 40 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 41 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 42 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 43 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 44 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 45 | github.com/miekg/dns v1.1.57 h1:Jzi7ApEIzwEPLHWRcafCN9LZSBbqQpxjt/wpgvg7wcM= 46 | github.com/miekg/dns v1.1.57/go.mod h1:uqRjCRUuEAA6qsOiJvDd+CFo/vW+y5WR6SNmHE55hZk= 47 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= 48 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 49 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= 50 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= 51 | github.com/natesales/bgptools-go v0.0.0-20230212051756-2b519d61269c h1:bblm7D7Ld1/zkWvMU1j60lMk5h/F4AiKW23j1yffM5Y= 52 | github.com/natesales/bgptools-go v0.0.0-20230212051756-2b519d61269c/go.mod h1:jl8YnQACciyOXRgNIRhURrCF9FmRHjnfT8UCj3LBkyY= 53 | github.com/onsi/ginkgo/v2 v2.13.2 h1:Bi2gGVkfn6gQcjNjZJVO8Gf0FHzMPf2phUei9tejVMs= 54 | github.com/onsi/ginkgo/v2 v2.13.2/go.mod h1:XStQ8QcGwLyF4HdfcZB8SFOS/MWCgDuXMSBe6zrvLgM= 55 | github.com/onsi/gomega v1.29.0 h1:KIA/t2t5UBzoirT4H9tsML45GEbo3ouUnBHsCfD2tVg= 56 | github.com/onsi/gomega v1.29.0/go.mod h1:9sxs+SwGrKI0+PWe4Fxa9tFQQBG5xSsSbMXOI8PPpoQ= 57 | github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= 58 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 59 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 60 | github.com/quic-go/qpack v0.4.0 h1:Cr9BXA1sQS2SmDUWjSofMPNKmvF6IiIfDRmgU0w1ZCo= 61 | github.com/quic-go/qpack v0.4.0/go.mod h1:UZVnYIfi5GRk+zI9UMaCPsmZ2xKJP7XBUvVyT1Knj9A= 62 | github.com/quic-go/qtls-go1-20 v0.4.1 h1:D33340mCNDAIKBqXuAvexTNMUByrYmFYVfKfDN5nfFs= 63 | github.com/quic-go/qtls-go1-20 v0.4.1/go.mod h1:X9Nh97ZL80Z+bX/gUXMbipO6OxdiDi58b/fMC9mAL+k= 64 | github.com/quic-go/quic-go v0.40.0 h1:GYd1iznlKm7dpHD7pOVpUvItgMPo/jrMgDWZhMCecqw= 65 | github.com/quic-go/quic-go v0.40.0/go.mod h1:PeN7kuVJ4xZbxSv/4OX6S1USOX8MJvydwpTx31vx60c= 66 | github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= 67 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= 68 | github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= 69 | github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= 70 | github.com/sthorne/odoh-go v1.0.4 h1:RPJceVs/dIpNE3gyzk6wdSay+nR+tI1YXBUwykvCEXI= 71 | github.com/sthorne/odoh-go v1.0.4/go.mod h1:KdB/NGiepr9bLVs3k26uWl4HHPHqa2DaoPUgUfKNmJU= 72 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 73 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 74 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 75 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 76 | github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= 77 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 78 | go.uber.org/mock v0.3.0 h1:3mUxI1No2/60yUYax92Pt8eNOEecx2D3lcXZh2NEZJo= 79 | go.uber.org/mock v0.3.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= 80 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 81 | golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 82 | golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= 83 | golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY= 84 | golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= 85 | golang.org/x/exp v0.0.0-20231206192017-f3f8817b8deb h1:c0vyKkb6yr3KR7jEfJaOSv4lG7xPkbN6r52aJz1d8a8= 86 | golang.org/x/exp v0.0.0-20231206192017-f3f8817b8deb/go.mod h1:iRJReGqOEeBhDZGkGbynYwcHlctCvnjTYIamk7uXpHI= 87 | golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0= 88 | golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= 89 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 90 | golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= 91 | golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= 92 | golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE= 93 | golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 94 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 95 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 96 | golang.org/x/sys v0.0.0-20190602015325-4c4f7f33c9ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 97 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 98 | golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 99 | golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 100 | golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 101 | golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= 102 | golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 103 | golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= 104 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 105 | golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= 106 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 107 | golang.org/x/tools v0.16.1 h1:TLyB3WofjdOEepBHAU20JdNC1Zbg87elYofWYAY5oZA= 108 | golang.org/x/tools v0.16.1/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0= 109 | google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= 110 | google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= 111 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 112 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= 113 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 114 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 115 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 116 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 117 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "crypto/tls" 6 | "fmt" 7 | "io" 8 | "net" 9 | "net/url" 10 | "os" 11 | "regexp" 12 | "slices" 13 | "strings" 14 | "time" 15 | 16 | "github.com/jedisct1/go-dnsstamps" 17 | "github.com/jessevdk/go-flags" 18 | "github.com/miekg/dns" 19 | log "github.com/sirupsen/logrus" 20 | 21 | "github.com/natesales/q/cli" 22 | "github.com/natesales/q/output" 23 | "github.com/natesales/q/transport" 24 | "github.com/natesales/q/util" 25 | tlsutil "github.com/natesales/q/util/tls" 26 | ) 27 | 28 | const defaultServerVar = "Q_DEFAULT_SERVER" 29 | 30 | var opts = cli.Flags{} 31 | 32 | // Build process flags 33 | var ( 34 | version = "dev" 35 | commit = "unknown" 36 | date = "unknown" 37 | ) 38 | 39 | // clearOpts sets the default values for the CLI options 40 | func clearOpts() { 41 | opts = cli.Flags{} 42 | cli.SetDefaultTrueBools(&opts) 43 | 44 | // Enable color output if stdout is a terminal 45 | if fileInfo, _ := os.Stdout.Stat(); (fileInfo.Mode() & os.ModeCharDevice) != 0 { 46 | opts.Color = true 47 | } 48 | 49 | // Disable color output if NO_COLOR env var is set 50 | if os.Getenv("NO_COLOR") != "" { 51 | log.Debug("NO_COLOR set") 52 | opts.Color = false 53 | } 54 | util.UseColor = opts.Color 55 | } 56 | 57 | func txtConcat(m *dns.Msg) { 58 | var answers []dns.RR 59 | for _, answer := range m.Answer { 60 | if answer.Header().Rrtype == dns.TypeTXT { 61 | txt := answer.(*dns.TXT) 62 | 63 | // Concat TXT responses if requested 64 | if opts.TXTConcat { 65 | log.Debugf("Concatenating TXT response: %+v", txt.Txt) 66 | txt.Txt = []string{strings.Join(txt.Txt, "")} 67 | } 68 | answers = append(answers, txt) 69 | } else { 70 | answers = append(answers, answer) 71 | } 72 | } 73 | m.Answer = answers 74 | } 75 | 76 | // dnsStampToURL converts a DNS stamp string to a URL string 77 | func dnsStampToURL(s string) (string, error) { 78 | var u url.URL 79 | 80 | parsedStamp, err := dnsstamps.NewServerStampFromString(s) 81 | if err != nil { 82 | return "", err 83 | } 84 | 85 | switch parsedStamp.Proto { 86 | case dnsstamps.StampProtoTypePlain: 87 | u.Scheme = string(transport.TypePlain) 88 | case dnsstamps.StampProtoTypeTLS: 89 | u.Scheme = string(transport.TypeTLS) 90 | case dnsstamps.StampProtoTypeDoH: 91 | u.Scheme = string(transport.TypeHTTP) + "s" // default to HTTPS 92 | case dnsstamps.StampProtoTypeDNSCrypt: 93 | // DNS stamp parsing happens again in the DNSCrypt transport, so pass the input along unchanged 94 | return s, nil 95 | default: 96 | return "", fmt.Errorf("unsupported protocol %s in DNS stamp", parsedStamp.Proto.String()) 97 | } 98 | 99 | // TODO: This might be a source of problems...we might want to be using parsedStamp.ServerAddrStr 100 | u.Host = parsedStamp.ProviderName 101 | u.Path = parsedStamp.Path 102 | 103 | log.Tracef("DNS stamp parsed into URL as %s", u.String()) 104 | return u.String(), nil 105 | } 106 | 107 | // setPort sets the port of a url.URL 108 | func setPort(u *url.URL, port int) { 109 | if strings.Contains(u.Host, ":") { 110 | if strings.Contains(u.Host, "[") && strings.Contains(u.Host, "]") { 111 | u.Host = fmt.Sprintf("%s]:%d", strings.Split(u.Host, "]")[0], port) 112 | return 113 | } 114 | u.Host = "[" + u.Host + "]" 115 | } 116 | u.Host = fmt.Sprintf("%s:%d", u.Host, port) 117 | } 118 | 119 | // parseServer is a revised version of parseServer that uses the URL package for parsing 120 | func parseServer(s string) (string, transport.Type, error) { 121 | // Remove IPv6 scope ID if present 122 | var scopeId string 123 | v6scopeRe := regexp.MustCompile(`(^|\[)[a-fA-F0-9:]+%[a-zA-Z0-9]+`) 124 | if v6scopeRe.MatchString(s) { 125 | v6scopeRemoveRe := regexp.MustCompile(`(%[a-zA-Z0-9]+)`) 126 | matches := v6scopeRemoveRe.FindStringSubmatch(s) 127 | if len(matches) > 1 { 128 | scopeId = matches[1] 129 | s = v6scopeRemoveRe.ReplaceAllString(s, "") 130 | } 131 | log.Tracef("Removed IPv6 scope ID %s from server %s", scopeId, s) 132 | } 133 | 134 | // Handle DNS stamp 135 | if strings.HasPrefix(s, "sdns://") { 136 | var err error 137 | s, err = dnsStampToURL(s) 138 | if err != nil { 139 | return "", "", fmt.Errorf("converting DNS stamp to URL: %s", err) 140 | } 141 | // If s is still a DNS stamp, it's DNSCrypt 142 | if strings.HasPrefix(s, "sdns://") { 143 | return s, transport.TypeDNSCrypt, nil 144 | } 145 | } 146 | 147 | // Check if server starts with a scheme, if not, default to plain 148 | schemeRe := regexp.MustCompile(`^[a-zA-Z0-9]+://`) 149 | if !schemeRe.MatchString(s) { 150 | // Enclose in brackets if IPv6 151 | v6re := regexp.MustCompile(`^[a-fA-F0-9:]+$`) 152 | if v6re.MatchString(s) { 153 | s = "[" + s + "]" 154 | } 155 | s = "plain://" + s 156 | } 157 | 158 | // Parse server as URL 159 | tu, err := url.Parse(s) 160 | if err != nil { 161 | return "", "", fmt.Errorf("parsing %s as URL: %s", s, err) 162 | } 163 | 164 | // Parse transport type 165 | ts := transport.Type(tu.Scheme) 166 | if tu.Scheme == "https" { // Override HTTPS to HTTP, preserving tu.Scheme as HTTPS 167 | ts = transport.TypeHTTP 168 | } 169 | if !slices.Contains(transport.Types, ts) { 170 | return "", "", fmt.Errorf("unsupported transport %s. expected: %+v", ts, transport.Types) 171 | } 172 | 173 | // Set default port 174 | if tu.Port() == "" { 175 | switch ts { 176 | case transport.TypeQUIC, transport.TypeTLS: 177 | setPort(tu, 853) 178 | case transport.TypeHTTP: 179 | if tu.Scheme == "https" { 180 | setPort(tu, 443) 181 | } else { 182 | setPort(tu, 80) 183 | } 184 | case transport.TypePlain, transport.TypeTCP: 185 | setPort(tu, 53) 186 | } 187 | } 188 | 189 | // Add default path if missing 190 | if ts == transport.TypeHTTP && tu.Path == "" { 191 | tu.Path = "/dns-query" 192 | } 193 | 194 | server := tu.String() 195 | // Remove scheme from server if irrelevant to protocol 196 | if ts != transport.TypeHTTP { 197 | server = strings.Split(server, "://")[1] 198 | } 199 | 200 | // Add IPv6 scope ID back to server 201 | if scopeId != "" { 202 | server = strings.Replace(server, "]", scopeId+"]", 1) 203 | } 204 | 205 | return server, ts, nil 206 | } 207 | 208 | // driver is the "main" function for this program that accepts a flag slice for testing 209 | func driver(args []string, out io.Writer) error { 210 | args = cli.SetFalseBooleans(&opts, args) 211 | args = cli.AddEqualSigns(args) 212 | parser := flags.NewParser(&opts, flags.Default) 213 | parser.Usage = `[OPTIONS] [@server] [type...] [name] 214 | 215 | All long form (--) flags can be toggled with the dig-standard +[no]flag notation.` 216 | _, err := parser.ParseArgs(args) 217 | if err != nil { 218 | if !strings.Contains(err.Error(), "Usage") { 219 | log.Fatal(err) 220 | } 221 | os.Exit(1) 222 | } 223 | cli.ParsePlusFlags(&opts, args) 224 | util.UseColor = opts.Color 225 | 226 | if opts.Verbose { 227 | log.SetLevel(log.DebugLevel) 228 | } else if opts.Trace { 229 | log.SetLevel(log.TraceLevel) 230 | opts.ShowAll = true 231 | } 232 | 233 | if opts.ShowVersion { 234 | util.MustWritef(out, "https://github.com/natesales/q version %s (%s %s)\n", version, commit, date) 235 | return nil 236 | } 237 | 238 | if opts.ShowAll { 239 | opts.ShowQuestion = true 240 | opts.ShowAnswer = true 241 | opts.ShowAuthority = true 242 | opts.ShowAdditional = true 243 | opts.ShowStats = true 244 | } 245 | 246 | // Set bootstrap resolver 247 | if opts.BootstrapServer != "" { 248 | // Add port if not specified 249 | rePortSuffix := regexp.MustCompile(`:\d+$`) 250 | if !rePortSuffix.MatchString(opts.BootstrapServer) { 251 | opts.BootstrapServer += ":53" 252 | } 253 | 254 | net.DefaultResolver = &net.Resolver{ 255 | PreferGo: true, 256 | Dial: func(ctx context.Context, network, address string) (net.Conn, error) { 257 | d := net.Dialer{Timeout: opts.BootstrapTimeout} 258 | return d.DialContext(ctx, network, opts.BootstrapServer) 259 | }, 260 | } 261 | 262 | log.Debugf("Using bootstrap resolver %s", opts.BootstrapServer) 263 | } 264 | 265 | // Parse requested RR types 266 | rrTypes, err := cli.ParseRRTypes(opts.Types) 267 | if err != nil { 268 | return err 269 | } 270 | 271 | // Add non-flag RR types 272 | for _, arg := range args { 273 | // Find a server by @ symbol if it isn't set by flag 274 | if strings.HasPrefix(arg, "@") { 275 | opts.Server = append(opts.Server, strings.TrimPrefix(arg, "@")) 276 | } 277 | 278 | // Parse chaos class 279 | if strings.ToLower(arg) == "ch" { 280 | opts.Chaos = true 281 | } 282 | 283 | // Add non-flag RR types 284 | rrType, typeFound := dns.StringToType[strings.ToUpper(arg)] 285 | if typeFound { 286 | rrTypes[rrType] = true 287 | } 288 | 289 | // Set qname if not set by flag 290 | if opts.Name == "" && 291 | !util.ContainsAny(arg, []string{"@", "/", "\\", "+"}) && // Not a server, path, or flag 292 | !typeFound && // Not a RR type 293 | !strings.HasSuffix(arg, ".exe") && // Not an executable 294 | !strings.HasPrefix(arg, "-") { // Not a flag 295 | opts.Name = arg 296 | } 297 | } 298 | 299 | // If no RR types are defined, set a list of default ones 300 | if len(rrTypes) < 1 { 301 | if opts.Name == "" { 302 | rrTypes[dns.StringToType["NS"]] = true 303 | } else { 304 | for _, defaultRRType := range opts.DefaultRRTypes { 305 | rrTypes[dns.StringToType[defaultRRType]] = true 306 | } 307 | } 308 | } 309 | 310 | // Reverse address if required 311 | if opts.Reverse { 312 | opts.Name, err = dns.ReverseAddr(opts.Name) 313 | if err != nil { 314 | return fmt.Errorf("dns reverse: %s", err) 315 | } 316 | rrTypes[dns.StringToType["PTR"]] = true 317 | } 318 | 319 | // Log RR types 320 | if opts.Verbose { 321 | log.Debugf("Name: %s", opts.Name) 322 | var rrTypeStrings []string 323 | for rrType := range rrTypes { 324 | rrS, ok := dns.TypeToString[rrType] 325 | if !ok { 326 | rrS = fmt.Sprintf("TYPE%d", rrType) 327 | } 328 | rrTypeStrings = append(rrTypeStrings, rrS) 329 | } 330 | log.Debugf("RR types: %+v", rrTypeStrings) 331 | } 332 | 333 | // Set default DNS server 334 | if len(opts.Server) == 0 { 335 | opts.Server = make([]string, 1) 336 | 337 | if os.Getenv(defaultServerVar) != "" { 338 | opts.Server[0] = os.Getenv(defaultServerVar) 339 | log.Debugf("Using %s from %s environment variable", opts.Server, defaultServerVar) 340 | } else { 341 | log.Debugf("No server specified or %s set, using /etc/resolv.conf", defaultServerVar) 342 | conf, err := dns.ClientConfigFromFile("/etc/resolv.conf") 343 | if err != nil { 344 | opts.Server[0] = "https://cloudflare-dns.com/dns-query" 345 | log.Debugf("no server set, using %s", opts.Server) 346 | } else { 347 | if len(conf.Servers) == 0 { 348 | opts.Server[0] = "https://cloudflare-dns.com/dns-query" 349 | log.Debugf("no server set, using %s", opts.Server) 350 | } else { 351 | opts.Server[0] = conf.Servers[0] 352 | log.Debugf("found server %s from /etc/resolv.conf", opts.Server) 353 | } 354 | } 355 | } 356 | } 357 | 358 | // Validate ODoH 359 | if opts.ODoHProxy != "" { 360 | if !strings.HasPrefix(opts.ODoHProxy, "https://") { 361 | return fmt.Errorf("ODoH proxy must use HTTPS") 362 | } 363 | for _, server := range opts.Server { 364 | if !strings.HasPrefix(server, "https://") { 365 | return fmt.Errorf("ODoH target must use HTTPS") 366 | } 367 | } 368 | } 369 | 370 | log.Debugf("Server(s): %s", opts.Server) 371 | 372 | if opts.Chaos { 373 | log.Debug("Flag set, using chaos class") 374 | opts.Class = dns.ClassCHAOS 375 | } 376 | 377 | if opts.NSIDOnly { 378 | opts.NSID = true 379 | } 380 | 381 | // Create TLS config 382 | tlsConfig := &tls.Config{ 383 | InsecureSkipVerify: opts.TLSInsecureSkipVerify, 384 | ServerName: opts.TLSServerName, 385 | MinVersion: tlsutil.Version(opts.TLSMinVersion, tls.VersionTLS10), 386 | MaxVersion: tlsutil.Version(opts.TLSMaxVersion, tls.VersionTLS13), 387 | NextProtos: opts.TLSNextProtos, 388 | CipherSuites: tlsutil.ParseCipherSuites(opts.TLSCipherSuites), 389 | CurvePreferences: tlsutil.ParseCurves(opts.TLSCurvePreferences), 390 | } 391 | 392 | // TLS client certificate authentication 393 | if opts.TLSClientCertificate != "" { 394 | cert, err := tls.LoadX509KeyPair(opts.TLSClientCertificate, opts.TLSClientKey) 395 | if err != nil { 396 | return fmt.Errorf("unable to load client certificate: %s", err) 397 | } 398 | tlsConfig.Certificates = []tls.Certificate{cert} 399 | } 400 | 401 | // TLS secret logging 402 | if opts.TLSKeyLogFile != "" { 403 | log.Warnf("TLS secret logging enabled") 404 | keyLogFile, err := os.OpenFile(opts.TLSKeyLogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) 405 | if err != nil { 406 | return fmt.Errorf("unable to open TLS key log file: %s", err) 407 | } 408 | tlsConfig.KeyLogWriter = keyLogFile 409 | } 410 | 411 | var rrTypesSlice []uint16 412 | for rrType := range rrTypes { 413 | rrTypesSlice = append(rrTypesSlice, rrType) 414 | } 415 | msgs := createQuery(opts, rrTypesSlice) 416 | 417 | errChan := make(chan error) 418 | 419 | go func() { 420 | var entries []*output.Entry 421 | for _, serverStr := range opts.Server { 422 | // Parse server address and transport type 423 | server, transportType, err := parseServer(serverStr) 424 | if err != nil { 425 | errChan <- fmt.Errorf("parsing server %s: %s", serverStr, err) 426 | } 427 | log.Debugf("Using server %s with transport %s", server, transportType) 428 | 429 | // Recursive zone transfer 430 | if opts.RecAXFR { 431 | if opts.Name == "" { 432 | errChan <- fmt.Errorf("no name specified for AXFR") 433 | } 434 | _ = RecAXFR(opts.Name, server, out) 435 | errChan <- nil // exit immediately 436 | } 437 | 438 | // Create transport 439 | txp, err := newTransport(server, transportType, tlsConfig) 440 | if err != nil { 441 | errChan <- fmt.Errorf("creating transport: %s", err) 442 | } 443 | 444 | startTime := time.Now() 445 | var replies []*dns.Msg 446 | for _, msg := range msgs { 447 | if txp == nil { 448 | errChan <- fmt.Errorf("transport is nil") 449 | } 450 | reply, err := (*txp).Exchange(&msg) 451 | if err != nil { 452 | errChan <- fmt.Errorf("exchange: %s", err) 453 | } 454 | 455 | if reply == nil { 456 | errChan <- fmt.Errorf("no reply from server") 457 | } 458 | 459 | if opts.ShowOpt { 460 | for _, o := range reply.Extra { 461 | if o.Header().Rrtype == dns.TypeOPT { 462 | fmt.Printf("OPT: %v\n", o) 463 | } 464 | } 465 | } 466 | 467 | if transportType != transport.TypeQUIC && opts.IDCheck && reply.Id != msg.Id { 468 | errChan <- fmt.Errorf("ID mismatch: expected %d, got %d", msg.Id, reply.Id) 469 | } 470 | replies = append(replies, reply) 471 | } 472 | 473 | // Process TXT parsing 474 | if opts.TXTConcat { 475 | for _, reply := range replies { 476 | txtConcat(reply) 477 | } 478 | } 479 | 480 | // Round TTL 481 | if opts.RoundTTLs { 482 | for _, reply := range replies { 483 | for _, rr := range reply.Answer { 484 | rr.Header().Ttl = rr.Header().Ttl - (rr.Header().Ttl % 60) 485 | } 486 | } 487 | } 488 | 489 | e := &output.Entry{ 490 | Queries: msgs, 491 | Replies: replies, 492 | Server: server, 493 | Time: time.Since(startTime), 494 | } 495 | 496 | if opts.ResolveIPs { 497 | e.LoadPTRs(txp) 498 | } 499 | 500 | entries = append(entries, e) 501 | 502 | if err := (*txp).Close(); err != nil { 503 | errChan <- fmt.Errorf("closing transport: %s", err) 504 | } 505 | } 506 | 507 | printer := output.Printer{ 508 | Out: out, 509 | Opts: &opts, 510 | } 511 | 512 | if (opts.NSID && (opts.Format == output.FormatPretty || opts.Format == output.FormatColumn)) || opts.NSIDOnly { 513 | printer.PrettyPrintNSID(entries, !opts.NSIDOnly) 514 | } 515 | 516 | // Skip printing if NSIDOnly is set 517 | if opts.NSIDOnly { 518 | errChan <- nil 519 | } 520 | 521 | switch opts.Format { 522 | case output.FormatPretty: 523 | printer.PrintPretty(entries) 524 | case output.FormatColumn: 525 | printer.PrintColumn(entries) 526 | case output.FormatRAW: 527 | printer.PrintRaw(entries) 528 | case output.FormatJSON, output.FormatYAML, "yml": 529 | printer.PrintStructured(entries) 530 | default: 531 | errChan <- fmt.Errorf("invalid output format") 532 | } 533 | 534 | errChan <- nil 535 | }() 536 | 537 | select { 538 | case <-time.After(opts.Timeout): 539 | return fmt.Errorf("timeout after %s", opts.Timeout) 540 | case err := <-errChan: 541 | return err 542 | } 543 | 544 | return nil 545 | } 546 | 547 | func main() { 548 | clearOpts() 549 | if err := driver(os.Args[1:], os.Stdout); err != nil { 550 | log.Fatal(err) 551 | } 552 | } 553 | -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "os" 6 | "path/filepath" 7 | "regexp" 8 | "strings" 9 | "testing" 10 | 11 | "github.com/stretchr/testify/assert" 12 | 13 | "github.com/natesales/q/cli" 14 | "github.com/natesales/q/transport" 15 | ) 16 | 17 | func run(args ...string) (*bytes.Buffer, error) { 18 | clearOpts() 19 | var out bytes.Buffer 20 | err := driver(append([]string{"+nocolor"}, args...), &out) 21 | return &out, err 22 | } 23 | 24 | func TestMainQuery(t *testing.T) { 25 | out, err := run( 26 | "--all", 27 | "-q", "example.com", 28 | ) 29 | assert.Nil(t, err) 30 | assert.Regexp(t, regexp.MustCompile(`example.com. .* TXT "v=spf1 -all"`), out.String()) 31 | } 32 | 33 | func TestMainVersion(t *testing.T) { 34 | out, err := run("-V") 35 | assert.Nil(t, err) 36 | assert.Contains(t, out.String(), "https://github.com/natesales/q version dev (unknown unknown)") 37 | } 38 | 39 | // TODO 40 | //func TestMainODoHQuery(t *testing.T) { 41 | // out, err := run( 42 | // "--all", 43 | // "-q", "example.com", 44 | // "-s", "https://odoh.cloudflare-dns.com", 45 | // "--odoh-proxy", "https://odoh.crypto.sx", 46 | // ) 47 | // assert.Nil(t, err) 48 | // assert.Regexp(t, regexp.MustCompile(`example.com. .* TXT "v=spf1 -all"`), out.String()) 49 | //} 50 | 51 | func TestMainRawFormat(t *testing.T) { 52 | out, err := run( 53 | "--all", 54 | "-q", "example.com", 55 | "--format=raw", 56 | ) 57 | assert.Nil(t, err) 58 | assert.Contains(t, out.String(), "v=spf1 -all") 59 | assert.Contains(t, out.String(), "a.iana-servers.net") 60 | } 61 | 62 | func TestMainJSONFormat(t *testing.T) { 63 | out, err := run( 64 | "--all", 65 | "-q", "example.com", 66 | "--format=json", 67 | ) 68 | assert.Nil(t, err) 69 | o := strings.ReplaceAll(out.String(), `\\"`, `"`) 70 | assert.Contains(t, o, `"preference":0,"mx":"."`) 71 | assert.Contains(t, o, `"ns":"a.iana-servers.net."`) 72 | assert.Contains(t, o, `"txt":["v=spf1 -all"`) 73 | } 74 | 75 | func TestMainInvalidOutputFormat(t *testing.T) { 76 | _, err := run( 77 | "--all", 78 | "-q", "example.com", 79 | "--format=invalid", 80 | ) 81 | if !(err != nil && strings.Contains(err.Error(), "invalid output format")) { 82 | t.Errorf("invalid output format should throw an error") 83 | } 84 | } 85 | 86 | func TestMainParseTypes(t *testing.T) { 87 | out, err := run( 88 | "--all", 89 | "-q", "example.com", 90 | "-t", "A", 91 | "-t", "AAAA", 92 | ) 93 | assert.Nil(t, err) 94 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 95 | assert.Regexp(t, regexp.MustCompile(`example.com. .* AAAA .*`), out.String()) 96 | } 97 | 98 | func TestMainInvalidTypes(t *testing.T) { 99 | _, err := run( 100 | "--all", 101 | "-q", "example.com", 102 | "-t", "INVALID", 103 | ) 104 | if !(err != nil && strings.Contains(err.Error(), "INVALID is not a valid RR type")) { 105 | t.Errorf("expected invalid type error, got %+v", err) 106 | } 107 | } 108 | 109 | func TestMainInvalidODoHUpstream(t *testing.T) { 110 | _, err := run( 111 | "--all", 112 | "-q", "example.com", 113 | "-s", "tls://odoh.cloudflare-dns.com", 114 | "--odoh-proxy", "https://odoh.crypto.sx", 115 | ) 116 | assert.NotNil(t, err) 117 | assert.Contains(t, err.Error(), "ODoH target must use HTTPS") 118 | } 119 | 120 | func TestMainInvalidODoHProxy(t *testing.T) { 121 | _, err := run( 122 | "--all", 123 | "-q", "example.com", 124 | "-s", "https://odoh.cloudflare-dns.com", 125 | "--odoh-proxy", "tls://odoh1.surfdomeinen.nl", 126 | ) 127 | assert.NotNil(t, err) 128 | assert.Contains(t, err.Error(), "ODoH proxy must use HTTPS") 129 | } 130 | 131 | func TestMainReverseQuery(t *testing.T) { 132 | out, err := run( 133 | "--all", 134 | "-x", 135 | "-q", "1.1.1.1", 136 | ) 137 | assert.Nil(t, err) 138 | assert.Regexp(t, regexp.MustCompile(`1.1.1.1.in-addr.arpa. .* PTR one.one.one.one`), out.String()) 139 | } 140 | 141 | func TestMainInferredQname(t *testing.T) { 142 | out, err := run( 143 | "--all", 144 | "example.com", 145 | "A", 146 | ) 147 | assert.Nil(t, err) 148 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 149 | } 150 | 151 | func TestMainInferredServer(t *testing.T) { 152 | out, err := run( 153 | "--all", 154 | "-q", "example.com", 155 | "@8.8.8.8", 156 | "-t", "A", 157 | ) 158 | assert.Nil(t, err) 159 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 160 | } 161 | 162 | func TestMainInvalidReverseQuery(t *testing.T) { 163 | _, err := run( 164 | "--all", 165 | "-x", 166 | "example.com", 167 | ) 168 | if !(err != nil && strings.Contains(err.Error(), "unrecognized address: example.com")) { 169 | t.Errorf("expected address error, got %+v", err) 170 | } 171 | } 172 | 173 | func TestMainInvalidUpstream(t *testing.T) { 174 | _, err := run( 175 | "--all", 176 | "-s", "127.127.127.127:1", 177 | "example.com", 178 | ) 179 | if !(err != nil && 180 | (strings.Contains(err.Error(), "connection refused") || 181 | strings.Contains(err.Error(), "i/o timeout"))) { 182 | t.Errorf("expected connection error, got %+v", err) 183 | } 184 | } 185 | 186 | func TestMainDNSSECArg(t *testing.T) { 187 | out, err := run( 188 | "--all", 189 | "example.com", 190 | "+dnssec", 191 | "@9.9.9.9", 192 | ) 193 | assert.Nil(t, err) 194 | t.Logf("out: %s", out.String()) 195 | assert.Regexp(t, regexp.MustCompile(`example.com. .* RRSIG .*`), out.String()) 196 | } 197 | 198 | func TestMainPad(t *testing.T) { 199 | out, err := run( 200 | "--all", 201 | "-q", "example.com", 202 | "--pad", 203 | "--format=json", 204 | ) 205 | assert.Nil(t, err) 206 | o := strings.ReplaceAll(out.String(), `\\"`, `"`) 207 | assert.Contains(t, o, `"truncated":false`) 208 | } 209 | 210 | func TestMainChaosClass(t *testing.T) { 211 | out, err := run( 212 | "--all", 213 | "id.server", 214 | "CH", 215 | "TXT", 216 | "@9.9.9.9", 217 | ) 218 | assert.Nil(t, err) 219 | assert.Regexp(t, regexp.MustCompile(`id.server. .* TXT ".*.pch.net"`), out.String()) 220 | } 221 | 222 | func TestMainParsePlusFlags(t *testing.T) { 223 | cli.ParsePlusFlags(&opts, []string{"+dnssec", "+nord"}) 224 | assert.True(t, opts.DNSSEC) 225 | assert.False(t, opts.RecursionDesired) 226 | } 227 | 228 | func TestMainTCPQuery(t *testing.T) { 229 | out, err := run( 230 | "--all", 231 | "-t", "A", 232 | "-q", "example.com", 233 | "@tcp://1.1.1.1", 234 | ) 235 | assert.Nil(t, err) 236 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 237 | } 238 | 239 | func TestMainTLSQuery(t *testing.T) { 240 | out, err := run( 241 | "--all", 242 | "-q", "example.com", 243 | "-t", "A", 244 | "@tls://1.1.1.1", 245 | ) 246 | assert.Nil(t, err) 247 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 248 | } 249 | 250 | func TestMainHTTPSQuery(t *testing.T) { 251 | out, err := run( 252 | "--all", 253 | "-q", "example.com", 254 | "-t", "A", 255 | "@https://dns.quad9.net", 256 | ) 257 | assert.Nil(t, err) 258 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 259 | } 260 | 261 | func TestMainQUICQuery(t *testing.T) { 262 | out, err := run( 263 | "--all", 264 | "-q", "example.com", 265 | "-t", "A", 266 | "@quic://dns.adguard.com", 267 | ) 268 | assert.Nil(t, err) 269 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 270 | } 271 | 272 | func TestMainDNSCryptStampQuery(t *testing.T) { 273 | out, err := run( 274 | "-q", "example.com", 275 | "-t", "A", 276 | "@sdns://AQMAAAAAAAAAETk0LjE0MC4xNC4xNDo1NDQzINErR_JS3PLCu_iZEIbq95zkSV2LFsigxDIuUso_OQhzIjIuZG5zY3J5cHQuZGVmYXVsdC5uczEuYWRndWFyZC5jb20", 277 | ) 278 | assert.Nil(t, err) 279 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 280 | } 281 | 282 | func TestMainDNSCryptManualQuery(t *testing.T) { 283 | out, err := run( 284 | "-q", "example.com", 285 | "-t", "A", 286 | "@dnscrypt://94.140.14.14:5443", 287 | "--dnscrypt-key", "d12b47f252dcf2c2bbf8991086eaf79ce4495d8b16c8a0c4322e52ca3f390873", 288 | "--dnscrypt-provider", "2.dnscrypt.default.ns1.adguard.com", 289 | ) 290 | assert.Nil(t, err) 291 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 292 | } 293 | 294 | func TestMainInvalidServerURL(t *testing.T) { 295 | out, err := run( 296 | "--all", 297 | "-q", "example.com", 298 | "@bad::server::url", 299 | "--format=json", 300 | ) 301 | assert.NotNil(t, err) 302 | assert.NotRegexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 303 | } 304 | 305 | func TestMainInvalidTransportScheme(t *testing.T) { 306 | out, err := run( 307 | "--all", 308 | "-q", "example.com", 309 | "@invalid://example.com", 310 | "--format=json", 311 | ) 312 | assert.NotNil(t, err) 313 | assert.NotRegexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 314 | } 315 | 316 | func TestMainTLS12(t *testing.T) { 317 | out, err := run( 318 | "--all", 319 | "-q", "example.com", 320 | "--tls-min-version=1.1", 321 | "--tls-max-version=1.2", 322 | "@tls://dns.quad9.net", 323 | "-t", "A", 324 | ) 325 | assert.Nil(t, err) 326 | assert.Regexp(t, regexp.MustCompile(`example.com. .* A .*`), out.String()) 327 | } 328 | 329 | func TestMainNSID(t *testing.T) { 330 | out, err := run( 331 | "--all", 332 | "@9.9.9.9", 333 | "+nsid", 334 | ) 335 | assert.Nil(t, err) 336 | assert.Regexp(t, regexp.MustCompile(`.*.pch.net.*`), out.String()) 337 | } 338 | 339 | func TestMainECSv4(t *testing.T) { 340 | out, err := run( 341 | "--all", 342 | "@script-ns.packetframe.com", 343 | "TXT", 344 | "query.script.packetframe.com", 345 | "--subnet", "192.0.2.0/24", 346 | ) 347 | assert.Nil(t, err) 348 | assert.Contains(t, out.String(), `'subnet':'192.0.2.0/24/0'`) 349 | } 350 | 351 | func TestMainECSv6(t *testing.T) { 352 | out, err := run( 353 | "--all", 354 | "@script-ns.packetframe.com", 355 | "TXT", 356 | "query.script.packetframe.com", 357 | "--subnet", "2001:db8::/48", 358 | ) 359 | assert.Nil(t, err) 360 | assert.Contains(t, out.String(), `'subnet':'[2001:db8::]/48/0'`) 361 | } 362 | 363 | func TestMainHTTPUserAgent(t *testing.T) { 364 | out, err := run( 365 | "--all", 366 | "@https://dns.quad9.net", 367 | "--http-user-agent", "Example/1.0", 368 | "-t", "NS", 369 | ) 370 | assert.Nil(t, err) 371 | assert.Regexp(t, regexp.MustCompile(`. .* NS a.root-servers.net.`), out.String()) 372 | } 373 | 374 | func TestMainParseServer(t *testing.T) { 375 | for _, tc := range []struct { 376 | Server string 377 | Type transport.Type 378 | ExpectedHost string 379 | }{ 380 | { // IPv4 plain with no port 381 | Server: "1.1.1.1", 382 | Type: transport.TypePlain, 383 | ExpectedHost: "1.1.1.1:53", 384 | }, 385 | { // IPv4 plain with explicit port 386 | Server: "1.1.1.1:5353", 387 | Type: transport.TypePlain, 388 | ExpectedHost: "1.1.1.1:5353", 389 | }, 390 | { // IPv6 plain with no port 391 | Server: "2a09::", 392 | Type: transport.TypePlain, 393 | ExpectedHost: "[2a09::]:53", 394 | }, 395 | { // IPv6 plain with explicit port 396 | Server: "[2a09::]:5353", 397 | Type: transport.TypePlain, 398 | ExpectedHost: "[2a09::]:5353", 399 | }, 400 | { // TLS with no port 401 | Server: "tls://dns.quad9.net", 402 | Type: transport.TypeTLS, 403 | ExpectedHost: "dns.quad9.net:853", 404 | }, 405 | { // TLS with explicit port 406 | Server: "tls://dns.quad9.net:8530", 407 | Type: transport.TypeTLS, 408 | ExpectedHost: "dns.quad9.net:8530", 409 | }, 410 | { // HTTPS with no endpoint 411 | Server: "https://dns.quad9.net", 412 | Type: transport.TypeHTTP, 413 | ExpectedHost: "https://dns.quad9.net:443/dns-query", 414 | }, 415 | { // HTTPS with IPv4 address 416 | Server: "https://1.1.1.1", 417 | Type: transport.TypeHTTP, 418 | ExpectedHost: "https://1.1.1.1:443/dns-query", 419 | }, 420 | { // TCP with no port 421 | Server: "tcp://dns.quad9.net", 422 | Type: transport.TypeTCP, 423 | ExpectedHost: "dns.quad9.net:53", 424 | }, 425 | { // HTTPS with IPv6 address 426 | Server: "https://2a09::", 427 | Type: transport.TypeHTTP, 428 | ExpectedHost: "https://[2a09::]:443/dns-query", 429 | }, 430 | { // HTTPS with explicit endpoint 431 | Server: "https://dns.quad9.net/other-dns-endpoint", 432 | Type: transport.TypeHTTP, 433 | ExpectedHost: "https://dns.quad9.net:443/other-dns-endpoint", 434 | }, 435 | { // QUIC with no port 436 | Server: "quic://dns.adguard.com", 437 | Type: transport.TypeQUIC, 438 | ExpectedHost: "dns.adguard.com:853", 439 | }, 440 | { // QUIC with explicit port 441 | Server: "quic://dns.adguard.com:8530", 442 | Type: transport.TypeQUIC, 443 | ExpectedHost: "dns.adguard.com:8530", 444 | }, 445 | { // IPv6 plain with scope ID but without port 446 | Server: "fe80::1%en0", 447 | Type: transport.TypePlain, 448 | ExpectedHost: "[fe80::1%en0]:53", 449 | }, 450 | { // IPv6 with scope ID and explicit port 451 | Server: "plain://[fe80::1%en0]:53", 452 | Type: transport.TypePlain, 453 | ExpectedHost: "[fe80::1%en0]:53", 454 | }, 455 | { // DNS Stamp 456 | Server: "sdns://AgcAAAAAAAAAAAAHOS45LjkuOQA", 457 | Type: transport.TypeHTTP, 458 | ExpectedHost: "https://9.9.9.9:443/dns-query", 459 | }, 460 | { // URL encoded path (https://github.com/natesales/q/issues/66) 461 | Server: "https://localhost/1%3A89%3D%3D%3A64fx", 462 | Type: transport.TypeHTTP, 463 | ExpectedHost: "https://localhost:443/1%3A89%3D%3D%3A64fx", 464 | }, 465 | { // Colons in URL path (https://github.com/natesales/q/issues/66) 466 | Server: "https://localhost/1:89==:64fx", 467 | Type: transport.TypeHTTP, 468 | ExpectedHost: "https://localhost:443/1:89==:64fx", 469 | }, 470 | { // Plain IPv6 address 471 | Server: "2001:db8:11:8340:dea6:32ff:fe5b:a19e", 472 | Type: transport.TypePlain, 473 | ExpectedHost: "[2001:db8:11:8340:dea6:32ff:fe5b:a19e]:53", 474 | }, 475 | } { 476 | t.Run(tc.Server, func(t *testing.T) { 477 | server, transportType, err := parseServer(tc.Server) 478 | assert.Nil(t, err) 479 | assert.Equal(t, tc.ExpectedHost, server) 480 | assert.Equal(t, tc.Type, transportType) 481 | }) 482 | } 483 | } 484 | 485 | func TestMainRecAXFR(t *testing.T) { 486 | out, err := run( 487 | "--all", 488 | "+recaxfr", 489 | "@nsztm1.digi.ninja", "zonetransfer.me", 490 | ) 491 | assert.Nil(t, err) 492 | assert.Contains(t, out.String(), `AXFR zonetransfer.me.`) 493 | assert.Contains(t, out.String(), `AXFR internal.zonetransfer.me.`) 494 | 495 | // Remove zonetransfer files 496 | files, err := filepath.Glob("zonetransfer.me*") 497 | assert.Nil(t, err) 498 | for _, f := range files { 499 | assert.Nil(t, os.RemoveAll(f)) 500 | } 501 | } 502 | 503 | func TestMainShowAll(t *testing.T) { 504 | out, err := run( 505 | "@9.9.9.9", 506 | "--all", 507 | "+all", 508 | "example.com", 509 | "A", 510 | ) 511 | assert.Nil(t, err) 512 | assert.Contains(t, out.String(), "example.com.") 513 | assert.Contains(t, out.String(), "Question:") 514 | assert.Contains(t, out.String(), "Answer:") 515 | assert.Contains(t, out.String(), "Stats:") 516 | } 517 | 518 | func TestMainResolveIPs(t *testing.T) { 519 | out, err := run( 520 | "core1.fmt2.he.net", 521 | "A", "AAAA", 522 | "-R", 523 | ) 524 | assert.Nil(t, err) 525 | assert.Regexp(t, regexp.MustCompile(`core1.fmt2.he.net. .* A .* \(core1.fmt2.he.net.\)`), out.String()) 526 | } 527 | 528 | func TestMainQueryDomainWithRRType(t *testing.T) { 529 | out, err := run( 530 | "NS.network", 531 | "A", 532 | ) 533 | assert.Nil(t, err) 534 | assert.Regexp(t, regexp.MustCompile(`NS.network. .* A .*`), out.String()) 535 | } 536 | 537 | func TestMainQueryTypeFlag(t *testing.T) { 538 | out, err := run( 539 | "-t", "65", 540 | "cloudflare.com", 541 | "-v", 542 | ) 543 | assert.Nil(t, err) 544 | assert.Regexp(t, regexp.MustCompile(`cloudflare.com. .* HTTPS 1 .*`), out.String()) 545 | } 546 | 547 | func TestMainDnsstampDoH(t *testing.T) { 548 | out, err := run( 549 | "@sdns://AgcAAAAAAAAADjEwNC4xNi4yNDguMjQ5ABJjbG91ZGZsYXJlLWRucy5jb20A", // cloudflare-dns.com 550 | "--all", 551 | ) 552 | 553 | assert.Nil(t, err) 554 | assert.Contains(t, out.String(), "from https://cloudflare-dns.com:443/dns-query") 555 | } 556 | 557 | func TestMainDnsstampDoHPath(t *testing.T) { 558 | _, err := run( 559 | "@sdns://AgcAAAAAAAAADjEwNC4xNi4yNDguMjQ5ABJjbG91ZGZsYXJlLWRucy5jb20FL3Rlc3Q", // cloudflare-dns.com/test 560 | "--all", 561 | ) 562 | 563 | // use err here because the query will result in a 404 564 | assert.Contains(t, err.Error(), "from https://cloudflare-dns.com:443/test") 565 | } 566 | 567 | func TestMainDnsstampInvalid(t *testing.T) { 568 | _, err := run( 569 | "@sdns://invalid", 570 | "--all", 571 | ) 572 | 573 | assert.NotNil(t, err) 574 | assert.Contains(t, err.Error(), "converting DNS stamp to URL: illegal base64 data") 575 | } 576 | 577 | -------------------------------------------------------------------------------- /output/output.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "io" 5 | "time" 6 | 7 | "github.com/natesales/q/transport" 8 | 9 | "github.com/miekg/dns" 10 | log "github.com/sirupsen/logrus" 11 | 12 | "github.com/natesales/q/cli" 13 | ) 14 | 15 | var ( 16 | FormatPretty = "pretty" 17 | FormatColumn = "column" 18 | FormatJSON = "json" 19 | FormatYAML = "yaml" 20 | FormatRAW = "raw" 21 | ) 22 | 23 | // Printer stores global options across multiple entries 24 | type Printer struct { 25 | Out io.Writer 26 | Opts *cli.Flags 27 | 28 | // Longest string lengths for column formatting 29 | longestTTL int 30 | longestRRType int 31 | } 32 | 33 | // Entry stores the replies from a server 34 | type Entry struct { 35 | Queries []dns.Msg 36 | Replies []*dns.Msg 37 | Server string 38 | 39 | // Time is the total time it took to query this server 40 | Time time.Duration 41 | 42 | PTRs map[string]string `json:"-"` // IP -> PTR value 43 | existingRRs map[string]bool 44 | } 45 | 46 | // LoadPTRs populates an entry's PTRs map with PTR values for all A/AAAA records 47 | func (e *Entry) LoadPTRs(txp *transport.Transport) { 48 | // Initialize PTR cache if it doesn't exist 49 | if e.PTRs == nil { 50 | e.PTRs = make(map[string]string) 51 | } 52 | 53 | for _, reply := range e.Replies { 54 | for _, rr := range reply.Answer { 55 | var ip string 56 | 57 | switch rr.Header().Rrtype { 58 | case dns.TypeA: 59 | ip = rr.(*dns.A).A.String() 60 | case dns.TypeAAAA: 61 | ip = rr.(*dns.AAAA).AAAA.String() 62 | default: 63 | continue 64 | } 65 | 66 | // Create PTR query 67 | qname, err := dns.ReverseAddr(ip) 68 | if err != nil { 69 | log.Fatalf("error reversing PTR record: %s", err) 70 | } 71 | msg := dns.Msg{} 72 | msg.SetQuestion(qname, dns.TypePTR) 73 | 74 | // Resolve qname and cache result 75 | resp, err := (*txp).Exchange(&msg) 76 | if err != nil { 77 | log.Debugf("error resolving PTR record: %s", err) 78 | } 79 | 80 | // Store in cache 81 | if len(resp.Answer) > 0 { 82 | e.PTRs[ip] = resp.Answer[0].(*dns.PTR).Ptr 83 | } 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /output/output_test.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "strings" 5 | "time" 6 | 7 | "github.com/miekg/dns" 8 | ) 9 | 10 | // replies returns a slice of example DNS answer messages 11 | func replies() []*dns.Msg { 12 | testZone := ` 13 | example.com. 86400 IN A 192.0.2.1 14 | example.com. 86400 IN A 192.0.2.2 15 | example.com. 86400 IN NS b.iana-servers.net. 16 | example.com. 86400 IN NS a.iana-servers.net. 17 | example.com. 86400 IN MX 0 . 18 | example.com. 86400 IN TXT "v=spf1 -all" 19 | ` 20 | 21 | // Convert the zone to DNS messages 22 | var msgs []*dns.Msg 23 | for _, line := range strings.Split(testZone, "\n") { 24 | if line != "" { 25 | rr, err := dns.NewRR(line) 26 | if err != nil { 27 | panic(err) 28 | } 29 | msgs = append(msgs, &dns.Msg{Answer: []dns.RR{rr}}) 30 | } 31 | } 32 | 33 | return msgs 34 | } 35 | 36 | var entries = []*Entry{ 37 | { 38 | Replies: replies(), 39 | Server: "192.0.2.10", 40 | Time: time.Second * 2, 41 | PTRs: nil, 42 | existingRRs: nil, 43 | }, 44 | } 45 | -------------------------------------------------------------------------------- /output/pretty.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "encoding/hex" 5 | "fmt" 6 | "sort" 7 | "strconv" 8 | "strings" 9 | "time" 10 | 11 | "github.com/miekg/dns" 12 | whois "github.com/natesales/bgptools-go" 13 | log "github.com/sirupsen/logrus" 14 | 15 | "github.com/natesales/q/cli" 16 | "github.com/natesales/q/util" 17 | ) 18 | 19 | // PrettyPrintNSID prints the NSID from a slice of entries 20 | func (p Printer) PrettyPrintNSID(entries []*Entry, printPrefix bool) { 21 | for _, entry := range entries { 22 | for _, r := range entry.Replies { 23 | for _, o := range r.Extra { 24 | if o.Header().Rrtype == dns.TypeOPT { 25 | for _, e := range o.(*dns.OPT).Option { 26 | if e.Option() == dns.EDNS0NSID { 27 | nsidStr, err := hex.DecodeString(e.String()) 28 | if err != nil { 29 | log.Warnf("error decoding NSID: %s", err) 30 | return 31 | } 32 | var suffix string 33 | if len(entries) > 1 { 34 | suffix = fmt.Sprintf(" (%s)", entry.Server) 35 | } 36 | 37 | var prefix string 38 | if printPrefix { 39 | prefix = util.Color(util.ColorWhite, "NSID:") + " " 40 | } 41 | 42 | util.MustWritef(p.Out, "%s%s%s\n", 43 | prefix, 44 | util.Color(util.ColorPurple, string(nsidStr)), 45 | suffix, 46 | ) 47 | return 48 | } 49 | } 50 | } 51 | } 52 | } 53 | } 54 | } 55 | 56 | // parseRR converts an RR into a pretty string and returns the qname, ttl, type, value, and whether to skip printing it because it's a duplicate 57 | func (e *Entry) parseRR(a dns.RR, opts *cli.Flags) *RR { 58 | // Initialize existingRRs map if it doesn't exist 59 | if e.existingRRs == nil { 60 | e.existingRRs = make(map[string]bool) 61 | } 62 | 63 | val := a.String() 64 | for _, cut := range []string{a.Header().Name, strconv.Itoa(int(a.Header().Ttl)), dns.ClassToString[a.Header().Class], dns.TypeToString[a.Header().Rrtype]} { 65 | val = strings.TrimSpace( 66 | strings.TrimPrefix(val, cut), 67 | ) 68 | } 69 | 70 | rrSignature := fmt.Sprintf("%s %d %s %s %s", a.Header().Name, a.Header().Ttl, dns.TypeToString[a.Header().Rrtype], val, e.Server) 71 | // Skip if we've already printed this RR 72 | if ok := e.existingRRs[rrSignature]; ok { 73 | return nil 74 | } 75 | e.existingRRs[rrSignature] = true 76 | 77 | ttl := fmt.Sprintf("%d", a.Header().Ttl) 78 | if opts.PrettyTTLs { 79 | ttl = (time.Duration(a.Header().Ttl) * time.Second).String() 80 | if opts.ShortTTLs { 81 | ttl = strings.ReplaceAll(ttl, "m0s", "m") 82 | ttl = strings.ReplaceAll(ttl, "h0m", "h") 83 | } 84 | } 85 | 86 | // Copy val now before modifying it with a suffix 87 | valCopy := val 88 | 89 | // Handle whois 90 | if opts.Whois && (a.Header().Rrtype == dns.TypeA || a.Header().Rrtype == dns.TypeAAAA) { 91 | resp, err := whois.Query(valCopy) 92 | if err != nil { 93 | log.Warnf("bgp.tools query: %s", err) 94 | } else { 95 | val += util.Color(util.ColorTeal, fmt.Sprintf(" (AS%d %s)", resp.AS, resp.ASName)) 96 | } 97 | } 98 | 99 | // Handle PTR resolution 100 | if opts.ResolveIPs && (a.Header().Rrtype == dns.TypeA || a.Header().Rrtype == dns.TypeAAAA) { 101 | val += util.Color(util.ColorMagenta, fmt.Sprintf(" (%s)", e.PTRs[valCopy])) 102 | } 103 | 104 | // Server suffix 105 | if len(opts.Server) > 1 { 106 | val += util.Color(util.ColorTeal, fmt.Sprintf(" (%s)", e.Server)) 107 | } 108 | 109 | return &RR{ 110 | util.Color(util.ColorPurple, a.Header().Name), 111 | util.Color(util.ColorGreen, ttl), 112 | util.Color(util.ColorMagenta, dns.TypeToString[a.Header().Rrtype]), 113 | val, 114 | } 115 | } 116 | 117 | // sortSlices sorts a slice of slices of strings by the nth element of each slice 118 | func sortSlices(s [][]string, n int) [][]string { 119 | sort.Slice(s, func(i, j int) bool { 120 | return s[i][n] < s[j][n] 121 | }) 122 | return s 123 | } 124 | 125 | // sortToPrint sorts a slice of records first by record type, then by value 126 | func sortToPrint(s [][]string) [][]string { 127 | // Organize by record type 128 | records := make(map[string][][]string) 129 | for _, record := range s { 130 | rrType := record[2] 131 | records[rrType] = append(records[rrType], record) 132 | } 133 | 134 | // Sort each record type 135 | for rrType, recs := range records { 136 | records[rrType] = sortSlices(recs, 3) 137 | } 138 | 139 | // Sort record types 140 | var sortedTypes []string 141 | for rrType := range records { 142 | sortedTypes = append(sortedTypes, rrType) 143 | } 144 | sort.Strings(sortedTypes) 145 | 146 | // Build final result 147 | var result [][]string 148 | for _, rrType := range sortedTypes { 149 | result = append(result, records[rrType]...) 150 | } 151 | return result 152 | } 153 | 154 | type RR struct { 155 | Name, TTL, Type, Value string 156 | } 157 | 158 | func toRRs(rrs []dns.RR, e *Entry, p *Printer) []RR { 159 | var out []RR 160 | for _, rr := range rrs { 161 | if rr := e.parseRR(rr, p.Opts); rr != nil { 162 | out = append(out, *rr) 163 | } 164 | } 165 | 166 | return out 167 | } 168 | 169 | // printSection prints a slice of RRs 170 | func (p Printer) printSection(rrs []RR) { 171 | var toPrint [][]string 172 | 173 | for _, a := range rrs { 174 | if p.Opts.ValueOnly { 175 | util.MustWriteln(p.Out, a.Value) 176 | continue 177 | } 178 | 179 | if len(a.TTL) > p.longestTTL { 180 | p.longestTTL = len(a.TTL) 181 | } 182 | if len(a.Type) > p.longestRRType { 183 | p.longestRRType = len(a.Type) 184 | } 185 | 186 | toPrint = append(toPrint, []string{a.Name, a.TTL, a.Type, a.Value}) 187 | } 188 | 189 | // Sort by record type 190 | toPrint = sortToPrint(toPrint) 191 | 192 | for _, a := range toPrint { 193 | if p.Opts.Format == "column" { 194 | util.MustWritef(p.Out, "%"+strconv.Itoa(p.longestRRType)+"s %-"+strconv.Itoa(p.longestTTL)+"s %s\n", a[2], a[1], a[3]) 195 | } else { 196 | util.MustWritef(p.Out, "%s %s %s %s\n", a[0], a[1], a[2], a[3]) 197 | } 198 | } 199 | } 200 | 201 | // PrintColumn prints an entry slice in column format 202 | func (p Printer) PrintColumn(entries []*Entry) { 203 | var answers []RR 204 | for _, e := range entries { 205 | for _, r := range e.Replies { 206 | rrs := toRRs(r.Answer, e, &p) 207 | answers = append(answers, rrs...) 208 | } 209 | } 210 | 211 | p.printSection(answers) 212 | } 213 | 214 | // flags returns a string of flags from a dns.Msg 215 | func flags(m *dns.Msg) string { 216 | out := "" 217 | if m.MsgHdr.Response { 218 | out += "qr " 219 | } 220 | if m.MsgHdr.Authoritative { 221 | out += "aa " 222 | } 223 | if m.MsgHdr.Truncated { 224 | out += "tc " 225 | } 226 | if m.MsgHdr.RecursionDesired { 227 | out += "rd " 228 | } 229 | if m.MsgHdr.RecursionAvailable { 230 | out += "ra " 231 | } 232 | if m.MsgHdr.Zero { 233 | out += "z " 234 | } 235 | if m.MsgHdr.AuthenticatedData { 236 | out += "ad " 237 | } 238 | if m.MsgHdr.CheckingDisabled { 239 | out += "cd " 240 | } 241 | return strings.TrimSuffix(out, " ") 242 | } 243 | 244 | func (p Printer) PrintPretty(entries []*Entry) { 245 | for _, entry := range entries { 246 | for i, reply := range entry.Replies { 247 | if p.Opts.ShowQuestion { 248 | util.MustWriteln(p.Out, util.Color(util.ColorWhite, "Question:")) 249 | for _, a := range reply.Question { 250 | util.MustWritef(p.Out, "%s %s\n", 251 | util.Color(util.ColorPurple, a.Name), 252 | util.Color(util.ColorMagenta, dns.TypeToString[a.Qtype]), 253 | ) 254 | } 255 | } 256 | if p.Opts.ShowAnswer && len(reply.Answer) > 0 { 257 | if p.Opts.ShowQuestion || p.Opts.ShowAuthority || p.Opts.ShowAdditional { 258 | util.MustWriteln(p.Out, util.Color(util.ColorWhite, "Answer:")) 259 | } 260 | p.printSection(toRRs(reply.Answer, entry, &p)) 261 | } 262 | if p.Opts.ShowAuthority && len(reply.Ns) > 0 { 263 | util.MustWriteln(p.Out, util.Color(util.ColorWhite, "Authority:")) 264 | p.printSection(toRRs(reply.Ns, entry, &p)) 265 | } 266 | if p.Opts.ShowAdditional && len(reply.Extra) > 0 { 267 | util.MustWriteln(p.Out, util.Color(util.ColorWhite, "Additional:")) 268 | p.printSection(toRRs(reply.Extra, entry, &p)) 269 | } 270 | 271 | // Print separator if there is more than one query 272 | if (p.Opts.ShowQuestion || p.Opts.ShowAuthority || p.Opts.ShowAdditional) && 273 | (len(entry.Replies) > 0 && i != len(entry.Replies)-1) { 274 | util.MustWritef(p.Out, "\n──\n\n") 275 | } 276 | 277 | if p.Opts.ShowStats { 278 | util.MustWriteln(p.Out, util.Color(util.ColorWhite, "Stats:")) 279 | util.MustWritef(p.Out, "Received %s from %s in %s (%s)\n", 280 | util.Color(util.ColorPurple, fmt.Sprintf("%d B", reply.Len())), 281 | util.Color(util.ColorGreen, entry.Server), 282 | util.Color(util.ColorTeal, entry.Time.Round(100*time.Microsecond)), 283 | util.Color(util.ColorMagenta, time.Now().Format("15:04:05 01-02-2006 MST")), 284 | ) 285 | 286 | util.MustWritef(p.Out, "Opcode: %s Status: %s ID %s: Flags: %s (%s Q %s A %s N %s E)\n", 287 | util.Color(util.ColorMagenta, dns.OpcodeToString[reply.MsgHdr.Opcode]), 288 | util.Color(util.ColorTeal, dns.RcodeToString[reply.MsgHdr.Rcode]), 289 | util.Color(util.ColorGreen, fmt.Sprintf("%d", reply.MsgHdr.Id)), 290 | util.Color(util.ColorPurple, flags(reply)), 291 | util.Color(util.ColorPurple, fmt.Sprintf("%d", len(reply.Question))), 292 | util.Color(util.ColorGreen, fmt.Sprintf("%d", len(reply.Answer))), 293 | util.Color(util.ColorTeal, fmt.Sprintf("%d", len(reply.Ns))), 294 | util.Color(util.ColorMagenta, fmt.Sprintf("%d", len(reply.Extra))), 295 | ) 296 | } 297 | } 298 | } 299 | } 300 | -------------------------------------------------------------------------------- /output/pretty_test.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "bytes" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | 9 | "github.com/natesales/q/cli" 10 | "github.com/natesales/q/util" 11 | ) 12 | 13 | func TestOutputPrettyPrintColumn(t *testing.T) { 14 | var buf bytes.Buffer 15 | util.UseColor = false 16 | p := Printer{Out: &buf, Opts: &cli.Flags{Format: "column"}} 17 | p.PrintColumn(entries) 18 | assert.Contains(t, buf.String(), `A 86400 192.0.2.2`) 19 | assert.Contains(t, buf.String(), `MX 86400 0 .`) 20 | assert.Contains(t, buf.String(), `NS 86400 a.iana-servers.net.`) 21 | assert.Contains(t, buf.String(), `NS 86400 b.iana-servers.net.`) 22 | assert.Contains(t, buf.String(), `TXT 86400 "v=spf1 -all"`) 23 | } 24 | -------------------------------------------------------------------------------- /output/raw.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "strconv" 5 | "time" 6 | 7 | "github.com/miekg/dns" 8 | 9 | "github.com/natesales/q/util" 10 | ) 11 | 12 | // rrSection generates a printable section from a given RR slice 13 | func rrSection(s, label string, rrs []dns.RR) string { 14 | if len(rrs) > 0 { 15 | s += "\n;; " + label + " SECTION:\n" 16 | for _, r := range rrs { 17 | if r != nil { 18 | s += r.String() + "\n" 19 | } 20 | } 21 | } 22 | 23 | return s 24 | } 25 | 26 | // PrintRaw a slice of entries in raw (dig-style) format 27 | func (p Printer) PrintRaw(entries []*Entry) { 28 | for _, entry := range entries { 29 | for i, reply := range entry.Replies { 30 | s := reply.MsgHdr.String() + " " 31 | s += "QUERY: " + strconv.Itoa(len(reply.Question)) + ", " 32 | s += "ANSWER: " + strconv.Itoa(len(reply.Answer)) + ", " 33 | s += "AUTHORITY: " + strconv.Itoa(len(reply.Ns)) + ", " 34 | s += "ADDITIONAL: " + strconv.Itoa(len(reply.Extra)) + "\n" 35 | opt := reply.IsEdns0() 36 | if opt != nil { 37 | // OPT PSEUDOSECTION 38 | s += opt.String() + "\n" 39 | } 40 | if p.Opts.ShowQuestion && len(reply.Question) > 0 { 41 | s += "\n;; QUESTION SECTION:\n" 42 | for _, r := range reply.Question { 43 | s += r.String() + "\n" 44 | } 45 | } 46 | if p.Opts.ShowAnswer { 47 | s += rrSection(s, "ANSWER", reply.Answer) 48 | } 49 | if p.Opts.ShowAuthority { 50 | s += rrSection(s, "AUTHORITY", reply.Ns) 51 | } 52 | if p.Opts.ShowAdditional && (opt == nil || len(reply.Extra) > 1) { 53 | s += rrSection(s, "ADDITIONAL", reply.Extra) 54 | } 55 | util.MustWriteln(p.Out, s) 56 | 57 | if p.Opts.ShowStats { 58 | util.MustWritef(p.Out, ";; Received %d B\n", reply.Len()) 59 | util.MustWritef(p.Out, ";; Time %s\n", time.Now().Format("15:04:05 01-02-2006 MST")) 60 | util.MustWritef(p.Out, ";; From %s in %s\n", entry.Server, entry.Time.Round(100*time.Microsecond)) 61 | } 62 | 63 | // Print separator if there is more than one query 64 | if len(entry.Replies) > 0 && i != len(entry.Replies)-1 { 65 | util.MustWritef(p.Out, "\n--\n\n") 66 | } 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /output/structured.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "strings" 5 | 6 | jsoniter "github.com/json-iterator/go" 7 | "github.com/json-iterator/go/extra" 8 | log "github.com/sirupsen/logrus" 9 | "gopkg.in/yaml.v3" 10 | 11 | "github.com/natesales/q/util" 12 | ) 13 | 14 | func (p Printer) PrintStructured(entries []*Entry) { 15 | var marshaler func(any) ([]byte, error) 16 | if p.Opts.Format == "json" { 17 | extra.SetNamingStrategy(strings.ToLower) 18 | json := jsoniter.ConfigCompatibleWithStandardLibrary 19 | marshaler = json.Marshal 20 | } else { // yaml 21 | marshaler = yaml.Marshal 22 | } 23 | 24 | b, err := marshaler(entries) 25 | if err != nil { 26 | log.Fatalf("error marshaling output: %s", err) 27 | } 28 | 29 | util.MustWriteln(p.Out, string(b)) 30 | } 31 | -------------------------------------------------------------------------------- /resolver.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/tls" 5 | "fmt" 6 | "net" 7 | "strings" 8 | 9 | "github.com/miekg/dns" 10 | log "github.com/sirupsen/logrus" 11 | 12 | "github.com/natesales/q/cli" 13 | "github.com/natesales/q/transport" 14 | ) 15 | 16 | // createQuery creates a slice of DNS queries 17 | func createQuery(opts cli.Flags, rrTypes []uint16) []dns.Msg { 18 | var queries []dns.Msg 19 | 20 | // Query for each requested RR type 21 | for _, qType := range rrTypes { 22 | req := dns.Msg{} 23 | 24 | if opts.ID != -1 { 25 | req.Id = uint16(opts.ID) 26 | } else { 27 | req.Id = dns.Id() 28 | } 29 | req.Authoritative = opts.AuthoritativeAnswer 30 | req.AuthenticatedData = opts.AuthenticData 31 | req.CheckingDisabled = opts.CheckingDisabled 32 | req.RecursionDesired = opts.RecursionDesired 33 | req.RecursionAvailable = opts.RecursionAvailable 34 | req.Zero = opts.Zero 35 | req.Truncated = opts.Truncated 36 | 37 | if opts.DNSSEC || opts.NSID || opts.Pad || opts.ClientSubnet != "" || opts.Cookie != "" { 38 | opt := &dns.OPT{ 39 | Hdr: dns.RR_Header{ 40 | Name: ".", 41 | Class: opts.UDPBuffer, 42 | Rrtype: dns.TypeOPT, 43 | }, 44 | } 45 | 46 | if opts.DNSSEC { 47 | opt.SetDo() 48 | } 49 | 50 | if opts.NSID { 51 | opt.Option = append(opt.Option, &dns.EDNS0_NSID{ 52 | Code: dns.EDNS0NSID, 53 | }) 54 | } 55 | 56 | if opts.Pad { 57 | paddingOpt := new(dns.EDNS0_PADDING) 58 | 59 | msgLen := req.Len() 60 | padLen := 128 - msgLen%128 61 | 62 | // Truncate padding to fit in UDP buffer 63 | if msgLen+padLen > int(opt.UDPSize()) { 64 | padLen = int(opt.UDPSize()) - msgLen 65 | if padLen < 0 { // Stop padding 66 | padLen = 0 67 | } 68 | } 69 | 70 | log.Debugf("Padding with %d bytes", padLen) 71 | paddingOpt.Padding = make([]byte, padLen) 72 | opt.Option = append(opt.Option, paddingOpt) 73 | } 74 | 75 | if opts.ClientSubnet != "" { 76 | ip, ipNet, err := net.ParseCIDR(opts.ClientSubnet) 77 | if err != nil { 78 | log.Fatalf("parsing subnet %s", opts.ClientSubnet) 79 | } 80 | mask, _ := ipNet.Mask.Size() 81 | log.Debugf("EDNS0 client subnet %s/%d", ip, mask) 82 | 83 | ednsSubnet := &dns.EDNS0_SUBNET{ 84 | Code: dns.EDNS0SUBNET, 85 | Address: ip, 86 | Family: 1, // IPv4 87 | SourceNetmask: uint8(mask), 88 | } 89 | 90 | if ednsSubnet.Address.To4() == nil { 91 | ednsSubnet.Family = 2 // IPv6 92 | } 93 | opt.Option = append(opt.Option, ednsSubnet) 94 | } 95 | 96 | if opts.Cookie != "" { 97 | cookie := &dns.EDNS0_COOKIE{ 98 | Code: dns.EDNS0COOKIE, 99 | Cookie: opts.Cookie, 100 | } 101 | opt.Option = append(opt.Option, cookie) 102 | } 103 | 104 | req.Extra = append(req.Extra, opt) 105 | } 106 | 107 | req.Question = []dns.Question{{ 108 | Name: dns.Fqdn(opts.Name), 109 | Qtype: qType, 110 | Qclass: opts.Class, 111 | }} 112 | 113 | queries = append(queries, req) 114 | } 115 | return queries 116 | } 117 | 118 | // newTransport creates a new transport based on local options 119 | func newTransport(server string, transportType transport.Type, tlsConfig *tls.Config) (*transport.Transport, error) { 120 | var ts transport.Transport 121 | 122 | common := transport.Common{ 123 | Server: server, 124 | ReuseConn: opts.ReuseConn, 125 | } 126 | 127 | switch transportType { 128 | case transport.TypeHTTP: 129 | if opts.ODoHProxy != "" { 130 | log.Debugf("Using ODoH transport with target %s proxy %s", server, opts.ODoHProxy) 131 | ts = &transport.ODoH{ 132 | Common: common, 133 | Proxy: opts.ODoHProxy, 134 | TLSConfig: tlsConfig, 135 | } 136 | } else { 137 | log.Debugf("Using HTTP(s) transport: %s", server) 138 | ts = &transport.HTTP{ 139 | Common: common, 140 | TLSConfig: tlsConfig, 141 | UserAgent: opts.HTTPUserAgent, 142 | Method: opts.HTTPMethod, 143 | HTTP2: opts.HTTP2, 144 | HTTP3: opts.HTTP3, 145 | NoPMTUd: !opts.PMTUD, 146 | } 147 | } 148 | case transport.TypeDNSCrypt: 149 | log.Debugf("Using DNSCrypt transport: %s", server) 150 | if strings.HasPrefix(server, "sdns://") { 151 | log.Traceln("Using provided DNS stamp for DNSCrypt") 152 | ts = &transport.DNSCrypt{ 153 | Common: common, 154 | ServerStamp: server, 155 | TCP: opts.DNSCryptTCP, 156 | UDPSize: opts.DNSCryptUDPSize, 157 | } 158 | } else { 159 | log.Traceln("Using manual DNSCrypt configuration") 160 | ts = &transport.DNSCrypt{Common: common, 161 | 162 | TCP: opts.DNSCryptTCP, 163 | UDPSize: opts.DNSCryptUDPSize, 164 | PublicKey: opts.DNSCryptPublicKey, 165 | ProviderName: opts.DNSCryptProvider, 166 | } 167 | } 168 | case transport.TypeQUIC: 169 | log.Debugf("Using QUIC transport: %s", server) 170 | 171 | tc := tlsConfig.Clone() 172 | tlsConfig.NextProtos = opts.QUICALPNTokens 173 | 174 | ts = &transport.QUIC{ 175 | Common: common, 176 | TLSConfig: tc, 177 | PMTUD: opts.PMTUD, 178 | AddLengthPrefix: opts.QUICLengthPrefix, 179 | } 180 | case transport.TypeTLS: 181 | log.Debugf("Using TLS transport: %s", server) 182 | ts = &transport.TLS{ 183 | Common: common, 184 | TLSConfig: tlsConfig, 185 | } 186 | case transport.TypeTCP: 187 | log.Debugf("Using TCP transport: %s", server) 188 | ts = &transport.Plain{ 189 | Common: common, 190 | PreferTCP: true, 191 | UDPBuffer: opts.UDPBuffer, 192 | } 193 | case transport.TypePlain: 194 | log.Debugf("Using UDP with TCP fallback: %s", server) 195 | ts = &transport.Plain{ 196 | Common: common, 197 | PreferTCP: false, 198 | UDPBuffer: opts.UDPBuffer, 199 | } 200 | default: 201 | return nil, fmt.Errorf("unknown transport protocol %s", transportType) 202 | } 203 | 204 | return &ts, nil 205 | } 206 | -------------------------------------------------------------------------------- /transport/LICENSE: -------------------------------------------------------------------------------- 1 | This implementation is based on https://github.com/AdguardTeam/dnsproxy, per the Apache license below 2 | 3 | Apache License 4 | Version 2.0, January 2004 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, 12 | and distribution as defined by Sections 1 through 9 of this document. 13 | 14 | "Licensor" shall mean the copyright owner or entity authorized by 15 | the copyright owner that is granting the License. 16 | 17 | "Legal Entity" shall mean the union of the acting entity and all 18 | other entities that control, are controlled by, or are under common 19 | control with that entity. For the purposes of this definition, 20 | "control" means (i) the power, direct or indirect, to cause the 21 | direction or management of such entity, whether by contract or 22 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 23 | outstanding shares, or (iii) beneficial ownership of such entity. 24 | 25 | "You" (or "Your") shall mean an individual or Legal Entity 26 | exercising permissions granted by this License. 27 | 28 | "Source" form shall mean the preferred form for making modifications, 29 | including but not limited to software source code, documentation 30 | source, and configuration files. 31 | 32 | "Object" form shall mean any form resulting from mechanical 33 | transformation or translation of a Source form, including but 34 | not limited to compiled object code, generated documentation, 35 | and conversions to other media types. 36 | 37 | "Work" shall mean the work of authorship, whether in Source or 38 | Object form, made available under the License, as indicated by a 39 | copyright notice that is included in or attached to the work 40 | (an example is provided in the Appendix below). 41 | 42 | "Derivative Works" shall mean any work, whether in Source or Object 43 | form, that is based on (or derived from) the Work and for which the 44 | editorial revisions, annotations, elaborations, or other modifications 45 | represent, as a whole, an original work of authorship. For the purposes 46 | of this License, Derivative Works shall not include works that remain 47 | separable from, or merely link (or bind by name) to the interfaces of, 48 | the Work and Derivative Works thereof. 49 | 50 | "Contribution" shall mean any work of authorship, including 51 | the original version of the Work and any modifications or additions 52 | to that Work or Derivative Works thereof, that is intentionally 53 | submitted to Licensor for inclusion in the Work by the copyright owner 54 | or by an individual or Legal Entity authorized to submit on behalf of 55 | the copyright owner. For the purposes of this definition, "submitted" 56 | means any form of electronic, verbal, or written communication sent 57 | to the Licensor or its representatives, including but not limited to 58 | communication on electronic mailing lists, source code control systems, 59 | and issue tracking systems that are managed by, or on behalf of, the 60 | Licensor for the purpose of discussing and improving the Work, but 61 | excluding communication that is conspicuously marked or otherwise 62 | designated in writing by the copyright owner as "Not a Contribution." 63 | 64 | "Contributor" shall mean Licensor and any individual or Legal Entity 65 | on behalf of whom a Contribution has been received by Licensor and 66 | subsequently incorporated within the Work. 67 | 68 | 2. Grant of Copyright License. Subject to the terms and conditions of 69 | this License, each Contributor hereby grants to You a perpetual, 70 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 71 | copyright license to reproduce, prepare Derivative Works of, 72 | publicly display, publicly perform, sublicense, and distribute the 73 | Work and such Derivative Works in Source or Object form. 74 | 75 | 3. Grant of Patent License. Subject to the terms and conditions of 76 | this License, each Contributor hereby grants to You a perpetual, 77 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 78 | (except as stated in this section) patent license to make, have made, 79 | use, offer to sell, sell, import, and otherwise transfer the Work, 80 | where such license applies only to those patent claims licensable 81 | by such Contributor that are necessarily infringed by their 82 | Contribution(s) alone or by combination of their Contribution(s) 83 | with the Work to which such Contribution(s) was submitted. If You 84 | institute patent litigation against any entity (including a 85 | cross-claim or counterclaim in a lawsuit) alleging that the Work 86 | or a Contribution incorporated within the Work constitutes direct 87 | or contributory patent infringement, then any patent licenses 88 | granted to You under this License for that Work shall terminate 89 | as of the date such litigation is filed. 90 | 91 | 4. Redistribution. You may reproduce and distribute copies of the 92 | Work or Derivative Works thereof in any medium, with or without 93 | modifications, and in Source or Object form, provided that You 94 | meet the following conditions: 95 | 96 | (a) You must give any other recipients of the Work or 97 | Derivative Works a copy of this License; and 98 | 99 | (b) You must cause any modified files to carry prominent notices 100 | stating that You changed the files; and 101 | 102 | (c) You must retain, in the Source form of any Derivative Works 103 | that You distribute, all copyright, patent, trademark, and 104 | attribution notices from the Source form of the Work, 105 | excluding those notices that do not pertain to any part of 106 | the Derivative Works; and 107 | 108 | (d) If the Work includes a "NOTICE" text file as part of its 109 | distribution, then any Derivative Works that You distribute must 110 | include a readable copy of the attribution notices contained 111 | within such NOTICE file, excluding those notices that do not 112 | pertain to any part of the Derivative Works, in at least one 113 | of the following places: within a NOTICE text file distributed 114 | as part of the Derivative Works; within the Source form or 115 | documentation, if provided along with the Derivative Works; or, 116 | within a display generated by the Derivative Works, if and 117 | wherever such third-party notices normally appear. The contents 118 | of the NOTICE file are for informational purposes only and 119 | do not modify the License. You may add Your own attribution 120 | notices within Derivative Works that You distribute, alongside 121 | or as an addendum to the NOTICE text from the Work, provided 122 | that such additional attribution notices cannot be construed 123 | as modifying the License. 124 | 125 | You may add Your own copyright statement to Your modifications and 126 | may provide additional or different license terms and conditions 127 | for use, reproduction, or distribution of Your modifications, or 128 | for any such Derivative Works as a whole, provided Your use, 129 | reproduction, and distribution of the Work otherwise complies with 130 | the conditions stated in this License. 131 | 132 | 5. Submission of Contributions. Unless You explicitly state otherwise, 133 | any Contribution intentionally submitted for inclusion in the Work 134 | by You to the Licensor shall be under the terms and conditions of 135 | this License, without any additional terms or conditions. 136 | Notwithstanding the above, nothing herein shall supersede or modify 137 | the terms of any separate license agreement you may have executed 138 | with Licensor regarding such Contributions. 139 | 140 | 6. Trademarks. This License does not grant permission to use the trade 141 | names, trademarks, service marks, or product names of the Licensor, 142 | except as required for reasonable and customary use in describing the 143 | origin of the Work and reproducing the content of the NOTICE file. 144 | 145 | 7. Disclaimer of Warranty. Unless required by applicable law or 146 | agreed to in writing, Licensor provides the Work (and each 147 | Contributor provides its Contributions) on an "AS IS" BASIS, 148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 149 | implied, including, without limitation, any warranties or conditions 150 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 151 | PARTICULAR PURPOSE. You are solely responsible for determining the 152 | appropriateness of using or redistributing the Work and assume any 153 | risks associated with Your exercise of permissions under this License. 154 | 155 | 8. Limitation of Liability. In no event and under no legal theory, 156 | whether in tort (including negligence), contract, or otherwise, 157 | unless required by applicable law (such as deliberate and grossly 158 | negligent acts) or agreed to in writing, shall any Contributor be 159 | liable to You for damages, including any direct, indirect, special, 160 | incidental, or consequential damages of any character arising as a 161 | result of this License or out of the use or inability to use the 162 | Work (including but not limited to damages for loss of goodwill, 163 | work stoppage, computer failure or malfunction, or any and all 164 | other commercial damages or losses), even if such Contributor 165 | has been advised of the possibility of such damages. 166 | 167 | 9. Accepting Warranty or Additional Liability. While redistributing 168 | the Work or Derivative Works thereof, You may choose to offer, 169 | and charge a fee for, acceptance of support, warranty, indemnity, 170 | or other liability obligations and/or rights consistent with this 171 | License. However, in accepting such obligations, You may act only 172 | on Your own behalf and on Your sole responsibility, not on behalf 173 | of any other Contributor, and only if You agree to indemnify, 174 | defend, and hold each Contributor harmless for any liability 175 | incurred by, or claims asserted against, such Contributor by reason 176 | of your accepting any such warranty or additional liability. 177 | 178 | END OF TERMS AND CONDITIONS 179 | 180 | APPENDIX: How to apply the Apache License to your work. 181 | 182 | To apply the Apache License to your work, attach the following 183 | boilerplate notice, with the fields enclosed by brackets "[]" 184 | replaced with your own identifying information. (Don't include 185 | the brackets!) The text should be enclosed in the appropriate 186 | comment syntax for the file format. We also recommend that a 187 | file or class name and description of purpose be included on the 188 | same "printed page" as the copyright notice for easier 189 | identification within third-party archives. 190 | 191 | Copyright 2020 Adguard Software Ltd 192 | 193 | Licensed under the Apache License, Version 2.0 (the "License"); 194 | you may not use this file except in compliance with the License. 195 | You may obtain a copy of the License at 196 | 197 | http://www.apache.org/licenses/LICENSE-2.0 198 | 199 | Unless required by applicable law or agreed to in writing, software 200 | distributed under the License is distributed on an "AS IS" BASIS, 201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 202 | See the License for the specific language governing permissions and 203 | limitations under the License. 204 | -------------------------------------------------------------------------------- /transport/dnscrypt.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "github.com/ameshkov/dnscrypt/v2" 5 | "github.com/jedisct1/go-dnsstamps" 6 | "github.com/miekg/dns" 7 | log "github.com/sirupsen/logrus" 8 | ) 9 | 10 | type DNSCrypt struct { 11 | Common 12 | ServerStamp string 13 | TCP bool // default false (UDP) 14 | UDPSize int 15 | 16 | // ServerStamp takes precedence if set 17 | PublicKey string 18 | ProviderName string 19 | 20 | resolver *dnscrypt.ResolverInfo 21 | client *dnscrypt.Client 22 | } 23 | 24 | func (d *DNSCrypt) setup() { 25 | if d.client == nil || d.resolver == nil || !d.ReuseConn { 26 | d.client = &dnscrypt.Client{ 27 | UDPSize: d.UDPSize, 28 | } 29 | 30 | if d.ServerStamp == "" { 31 | stamp, err := dnsstamps.NewDNSCryptServerStampFromLegacy(d.Server, d.PublicKey, d.ProviderName, 0) 32 | if err != nil { 33 | log.Fatalf("failed to create stamp from provider information: %s", err) 34 | } 35 | d.ServerStamp = stamp.String() 36 | log.Debugf("Created DNS stamp from manual DNSCrypt configuration: %s", d.ServerStamp) 37 | } 38 | 39 | // Resolve server DNS stamp 40 | ro, err := d.client.Dial(d.ServerStamp) 41 | if err != nil { 42 | log.Fatalf("failed to dial DNSCrypt server: %s", err) 43 | } 44 | d.resolver = ro 45 | } 46 | if d.TCP { 47 | d.client.Net = "tcp" 48 | } else { 49 | d.client.Net = "udp" 50 | } 51 | } 52 | 53 | func (d *DNSCrypt) Exchange(msg *dns.Msg) (*dns.Msg, error) { 54 | d.setup() 55 | return d.client.Exchange(msg, d.resolver) 56 | } 57 | 58 | func (d *DNSCrypt) Close() error { 59 | d.resolver = nil 60 | d.client = nil 61 | return nil 62 | } 63 | -------------------------------------------------------------------------------- /transport/dnscrypt_test.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | func dnscryptTransport() *DNSCrypt { 4 | return &DNSCrypt{ 5 | ServerStamp: "sdns://AQMAAAAAAAAAETk0LjE0MC4xNC4xNDo1NDQzINErR_JS3PLCu_iZEIbq95zkSV2LFsigxDIuUso_OQhzIjIuZG5zY3J5cHQuZGVmYXVsdC5uczEuYWRndWFyZC5jb20", 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /transport/http.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "bytes" 5 | "crypto/tls" 6 | "encoding/base64" 7 | "fmt" 8 | "io" 9 | "net/http" 10 | 11 | "github.com/miekg/dns" 12 | "github.com/quic-go/quic-go" 13 | "github.com/quic-go/quic-go/http3" 14 | log "github.com/sirupsen/logrus" 15 | "golang.org/x/net/http2" 16 | ) 17 | 18 | // HTTP makes a DNS query over HTTP(s) 19 | type HTTP struct { 20 | Common 21 | TLSConfig *tls.Config 22 | UserAgent string 23 | Method string 24 | HTTP2, HTTP3 bool 25 | NoPMTUd bool 26 | 27 | conn *http.Client 28 | } 29 | 30 | func (h *HTTP) Exchange(m *dns.Msg) (*dns.Msg, error) { 31 | if h.conn == nil || !h.ReuseConn { 32 | transport := http.DefaultTransport.(*http.Transport) 33 | transport.TLSClientConfig = h.TLSConfig 34 | h.conn = &http.Client{ 35 | Transport: transport, 36 | } 37 | if h.HTTP2 { 38 | log.Debug("Using HTTP/2") 39 | h.conn.Transport = &http2.Transport{ 40 | TLSClientConfig: h.TLSConfig, 41 | AllowHTTP: true, 42 | } 43 | } 44 | if h.HTTP3 { 45 | log.Debug("Using HTTP/3") 46 | h.conn.Transport = &http3.RoundTripper{ 47 | TLSClientConfig: h.TLSConfig, 48 | QuicConfig: &quic.Config{ 49 | DisablePathMTUDiscovery: h.NoPMTUd, 50 | }, 51 | } 52 | } 53 | } 54 | 55 | buf, err := m.Pack() 56 | if err != nil { 57 | return nil, fmt.Errorf("packing message: %w", err) 58 | } 59 | 60 | var queryURL string 61 | var req *http.Request 62 | switch h.Method { 63 | case http.MethodGet: 64 | queryURL = h.Server + "?dns=" + base64.RawURLEncoding.EncodeToString(buf) 65 | req, err = http.NewRequest(http.MethodGet, queryURL, nil) 66 | if err != nil { 67 | return nil, fmt.Errorf("creating http request to %s: %w", queryURL, err) 68 | } 69 | case http.MethodPost: 70 | queryURL = h.Server 71 | req, err = http.NewRequest(http.MethodPost, queryURL, bytes.NewReader(buf)) 72 | if err != nil { 73 | return nil, fmt.Errorf("creating http request to %s: %w", queryURL, err) 74 | } 75 | req.Header.Set("Content-Type", "application/dns-message") 76 | default: 77 | return nil, fmt.Errorf("unsupported HTTP method: %s", h.Method) 78 | } 79 | 80 | req.Header.Set("Accept", "application/dns-message") 81 | if h.UserAgent != "" { 82 | log.Debugf("Setting User-Agent to %s", h.UserAgent) 83 | req.Header.Set("User-Agent", h.UserAgent) 84 | } 85 | 86 | log.Debugf("[http] sending %s request to %s", h.Method, queryURL) 87 | resp, err := h.conn.Do(req) 88 | if resp != nil && resp.Body != nil { 89 | defer resp.Body.Close() 90 | } 91 | if err != nil { 92 | return nil, fmt.Errorf("requesting %s: %w", queryURL, err) 93 | } 94 | 95 | body, err := io.ReadAll(resp.Body) 96 | if err != nil { 97 | return nil, fmt.Errorf("reading %s: %w", queryURL, err) 98 | } 99 | 100 | if resp.StatusCode != http.StatusOK { 101 | return nil, fmt.Errorf("got status code %d from %s", resp.StatusCode, queryURL) 102 | } 103 | 104 | response := dns.Msg{} 105 | if err := response.Unpack(body); err != nil { 106 | return nil, fmt.Errorf("unpacking DNS response from %s: %w", queryURL, err) 107 | } 108 | 109 | return &response, nil 110 | } 111 | 112 | func (h *HTTP) Close() error { 113 | h.conn.CloseIdleConnections() 114 | return nil 115 | } 116 | -------------------------------------------------------------------------------- /transport/http_test.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "net/http" 5 | "testing" 6 | "time" 7 | 8 | "github.com/miekg/dns" 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | func httpTransport() *HTTP { 13 | return &HTTP{ 14 | Common: Common{ 15 | Server: "https://cloudflare-dns.com/dns-query", 16 | }, 17 | Method: http.MethodGet, 18 | } 19 | } 20 | 21 | func TestTransportHTTPPOST(t *testing.T) { 22 | tp := httpTransport() 23 | tp.Method = http.MethodPost 24 | reply, err := tp.Exchange(validQuery()) 25 | assert.Nil(t, err) 26 | assert.Greater(t, len(reply.Answer), 0) 27 | } 28 | 29 | func TestTransportHTTP3(t *testing.T) { 30 | tp := httpTransport() 31 | tp.HTTP3 = true 32 | reply, err := tp.Exchange(validQuery()) 33 | assert.Nil(t, err) 34 | assert.Greater(t, len(reply.Answer), 0) 35 | } 36 | 37 | func TestTransportHTTPInvalidResolver(t *testing.T) { 38 | tp := httpTransport() 39 | tp.Server = "https://example.com" 40 | _, err := tp.Exchange(validQuery()) 41 | assert.NotNil(t, err) 42 | assert.Contains(t, err.Error(), "unpacking DNS response") 43 | } 44 | 45 | func TestTransportHTTPServerError(t *testing.T) { 46 | listen := ":5380" 47 | go func() { 48 | if err := http.ListenAndServe(listen, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 49 | http.Error(w, "Server Error", http.StatusInternalServerError) 50 | })); err != nil { 51 | t.Errorf("error starting HTTP server: %s", err) 52 | } 53 | }() 54 | time.Sleep(50 * time.Millisecond) // Wait for server to start 55 | 56 | tp := httpTransport() 57 | tp.Server = "http://localhost" + listen 58 | _, err := tp.Exchange(validQuery()) 59 | assert.NotNil(t, err) 60 | assert.Contains(t, err.Error(), "got status code 500") 61 | } 62 | 63 | func TestTransportHTTPIDMismatch(t *testing.T) { 64 | listen := ":5381" 65 | go func() { 66 | if err := http.ListenAndServe(listen, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 67 | msg := dns.Msg{} 68 | msg.Id = 1 69 | buf, err := msg.Pack() 70 | if err != nil { 71 | t.Errorf("error packing DNS message: %s", err) 72 | return 73 | } 74 | if _, err := w.Write(buf); err != nil { 75 | t.Errorf("error writing DNS message: %s", err) 76 | } 77 | })); err != nil { 78 | t.Errorf("error starting HTTP server: %s", err) 79 | } 80 | }() 81 | time.Sleep(50 * time.Millisecond) // Wait for server to start 82 | 83 | tp := httpTransport() 84 | tp.Server = "http://localhost" + listen 85 | query := validQuery() 86 | reply, err := tp.Exchange(query) 87 | assert.Nil(t, err) 88 | assert.Equal(t, uint16(1), reply.Id) 89 | assert.NotEqual(t, 1, query.Id) 90 | } 91 | -------------------------------------------------------------------------------- /transport/odoh.go: -------------------------------------------------------------------------------- 1 | /* 2 | This implementation is based on https://github.com/cloudflare/odoh-client-go, per the MIT license below: 3 | 4 | The MIT License 5 | 6 | Copyright (c) 2019-2020, Cloudflare, Inc. and Christopher Wood. All rights reserved. 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining a copy 9 | of this software and associated documentation files (the "Software"), to deal 10 | in the Software without restriction, including without limitation the rights 11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the Software is 13 | furnished to do so, subject to the following conditions: 14 | 15 | The above copyright notice and this permission notice shall be included in 16 | all copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | THE SOFTWARE. 25 | */ 26 | 27 | package transport 28 | 29 | import ( 30 | "bytes" 31 | "crypto/tls" 32 | "errors" 33 | "fmt" 34 | "io" 35 | "net/http" 36 | "net/url" 37 | "strings" 38 | 39 | "github.com/miekg/dns" 40 | log "github.com/sirupsen/logrus" 41 | "github.com/sthorne/odoh-go" 42 | ) 43 | 44 | const ODoHContentType = "application/oblivious-dns-message" 45 | 46 | // buildURL adds HTTPS to argument s if it doesn't contain a protocol and appends defaultPath if no path is already specified 47 | func buildURL(s, defaultPath string) *url.URL { 48 | if //goland:noinspection HttpUrlsUsage 49 | !strings.HasPrefix(s, "https://") && !strings.HasPrefix(s, "http://") { 50 | s = "https://" + s 51 | } 52 | u, err := url.Parse(s) 53 | if err != nil { 54 | log.Fatalf("failed to parse url: %v", err) 55 | } 56 | if u.Path == "" { 57 | u.Path = defaultPath 58 | } 59 | return u 60 | } 61 | 62 | // ODoH makes a DNS query over ODoH 63 | type ODoH struct { 64 | Common // Server is the target 65 | Proxy string 66 | TLSConfig *tls.Config 67 | 68 | conn *http.Client 69 | } 70 | 71 | func (o *ODoH) Exchange(m *dns.Msg) (*dns.Msg, error) { 72 | // Query ODoH configs on target 73 | req, err := http.NewRequest( 74 | http.MethodGet, 75 | buildURL(strings.TrimSuffix(o.Server, "/dns-query"), "/.well-known/odohconfigs").String(), 76 | nil, 77 | ) 78 | if err != nil { 79 | return nil, fmt.Errorf("new target configs request: %s", err) 80 | } 81 | 82 | if o.conn == nil || !o.ReuseConn { 83 | o.conn = &http.Client{ 84 | Transport: &http.Transport{ 85 | TLSClientConfig: o.TLSConfig, 86 | }, 87 | } 88 | } 89 | resp, err := o.conn.Do(req) 90 | if err != nil { 91 | return nil, fmt.Errorf("do target configs request: %s", err) 92 | } 93 | defer resp.Body.Close() 94 | 95 | bodyBytes, err := io.ReadAll(resp.Body) 96 | if err != nil { 97 | return nil, err 98 | } 99 | odohConfigs, err := odoh.UnmarshalObliviousDoHConfigs(bodyBytes) 100 | if err != nil { 101 | return nil, fmt.Errorf("unmarshal target configs: %s", err) 102 | } 103 | 104 | if len(odohConfigs.Configs) == 0 { 105 | return nil, errors.New("target provided no valid ODoH configs") 106 | } 107 | log.Debugf("[odoh] retrieved %d ODoH configs", len(odohConfigs.Configs)) 108 | 109 | packedDnsQuery, err := m.Pack() 110 | if err != nil { 111 | return nil, err 112 | } 113 | 114 | firstODoHConfig := odohConfigs.Configs[0] 115 | log.Debugf("[odoh] using first ODoH config: %+v", firstODoHConfig) 116 | odnsMessage, queryContext, err := firstODoHConfig.Contents.EncryptQuery(odoh.CreateObliviousDNSQuery(packedDnsQuery, 0)) 117 | if err != nil { 118 | return nil, fmt.Errorf("encrypt query: %s", err) 119 | } 120 | 121 | t := buildURL(o.Server, "/dns-query") 122 | p := buildURL(o.Proxy, "/proxy") 123 | qry := p.Query() 124 | if qry.Get("targethost") == "" { 125 | qry.Set("targethost", t.Host) 126 | } 127 | if qry.Get("targetpath") == "" { 128 | qry.Set("targetpath", t.Path) 129 | } 130 | p.RawQuery = qry.Encode() 131 | 132 | log.Debugf("POST %s %+v", p, odnsMessage) 133 | req, err = http.NewRequest(http.MethodPost, p.String(), bytes.NewBuffer(odnsMessage.Marshal())) 134 | if err != nil { 135 | return nil, fmt.Errorf("create new request: %s", err) 136 | } 137 | req.Header.Set("Content-Type", ODoHContentType) 138 | req.Header.Set("Accept", ODoHContentType) 139 | 140 | resp, err = o.conn.Do(req) 141 | if err != nil { 142 | return nil, fmt.Errorf("do request: %s", err) 143 | } 144 | contentType := resp.Header.Get("Content-Type") 145 | if contentType != ODoHContentType { 146 | return nil, fmt.Errorf("%s responded with an invalid Content-Type header %s, expected %s", req.URL, contentType, ODoHContentType) 147 | } 148 | 149 | bodyBytes, err = io.ReadAll(resp.Body) 150 | if err != nil { 151 | return nil, fmt.Errorf("read response body: %s", err) 152 | } 153 | odohMessage, err := odoh.UnmarshalDNSMessage(bodyBytes) 154 | if err != nil { 155 | return nil, fmt.Errorf("odoh unmarshal: %s", err) 156 | } 157 | 158 | decryptedResponse, err := queryContext.OpenAnswer(odohMessage) 159 | if err != nil { 160 | return nil, fmt.Errorf("open answer: %s", err) 161 | } 162 | 163 | msg := &dns.Msg{} 164 | err = msg.Unpack(decryptedResponse) 165 | if err != nil { 166 | err = fmt.Errorf("unpack message: %s", err) 167 | } 168 | return msg, err 169 | } 170 | 171 | func (o *ODoH) Close() error { 172 | o.conn.CloseIdleConnections() 173 | return nil 174 | } 175 | -------------------------------------------------------------------------------- /transport/odoh_test.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func odohTransport() *ODoH { 10 | return &ODoH{ 11 | Common: Common{Server: "odoh.cloudflare-dns.com"}, 12 | Proxy: "odoh.crypto.sx", 13 | } 14 | } 15 | 16 | func TestODoHBuildURL(t *testing.T) { 17 | // Test with no query params 18 | u := buildURL("https://www.example.com", "") 19 | assert.Equal(t, "https://www.example.com", u.String()) 20 | 21 | // Test with query params 22 | u = buildURL("https://www.example.com", "?foo=bar&baz=qux") 23 | assert.Equal(t, "https://www.example.com/%3Ffoo=bar&baz=qux", u.String()) 24 | 25 | // Test with HTTP 26 | //goland:noinspection HttpUrlsUsage 27 | u = buildURL("http://www.example.com", "") 28 | //goland:noinspection HttpUrlsUsage 29 | assert.Equal(t, "http://www.example.com", u.String()) 30 | } 31 | 32 | func TestTransportODoHInvalidTarget(t *testing.T) { 33 | tp := odohTransport() 34 | tp.Server = "example.com" 35 | _, err := tp.Exchange(validQuery()) 36 | assert.NotNil(t, err) 37 | assert.Contains(t, err.Error(), "Invalid serialized ObliviousDoHConfig") 38 | } 39 | 40 | func TestTransportODoHInvalidProxy(t *testing.T) { 41 | tp := odohTransport() 42 | tp.Proxy = "example.com" 43 | _, err := tp.Exchange(validQuery()) 44 | assert.NotNil(t, err) 45 | assert.Contains(t, err.Error(), "responded with an invalid Content-Type header") 46 | } 47 | -------------------------------------------------------------------------------- /transport/plain.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "github.com/miekg/dns" 5 | log "github.com/sirupsen/logrus" 6 | ) 7 | 8 | // Plain makes a DNS query over TCP or UDP (with TCP fallback) 9 | type Plain struct { 10 | Common 11 | PreferTCP bool 12 | UDPBuffer uint16 13 | } 14 | 15 | func (p *Plain) Exchange(m *dns.Msg) (*dns.Msg, error) { 16 | tcpClient := dns.Client{Net: "tcp"} 17 | if p.PreferTCP { 18 | reply, _, tcpErr := tcpClient.Exchange(m, p.Server) 19 | return reply, tcpErr 20 | } 21 | 22 | client := dns.Client{UDPSize: p.UDPBuffer} 23 | reply, _, err := client.Exchange(m, p.Server) 24 | 25 | if reply != nil && reply.Truncated { 26 | log.Debugf("Truncated reply from %s for %s over UDP, retrying over TCP", p.Server, m.Question[0].String()) 27 | reply, _, err = tcpClient.Exchange(m, p.Server) 28 | } 29 | 30 | return reply, err 31 | } 32 | 33 | // Close is a no-op for the plain transport 34 | func (p *Plain) Close() error { 35 | return nil 36 | } 37 | -------------------------------------------------------------------------------- /transport/plain_test.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/miekg/dns" 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func plainTransport() *Plain { 11 | return &Plain{ 12 | Common: Common{ 13 | Server: "9.9.9.9:53", 14 | }, 15 | PreferTCP: false, 16 | UDPBuffer: 1232, 17 | } 18 | } 19 | 20 | func TestTransportPlainPreferTCP(t *testing.T) { 21 | tp := plainTransport() 22 | tp.PreferTCP = true 23 | reply, err := tp.Exchange(validQuery()) 24 | assert.Nil(t, err) 25 | assert.Greater(t, len(reply.Answer), 0) 26 | } 27 | 28 | func TestTransportPlainInvalidResolver(t *testing.T) { 29 | tp := plainTransport() 30 | tp.Server = "127.127.127.127:53" 31 | _, err := tp.Exchange(validQuery()) 32 | assert.NotNil(t, err) 33 | } 34 | 35 | func TestTransportPlainLargeResponse(t *testing.T) { 36 | msg := dns.Msg{} 37 | msg.RecursionDesired = true 38 | msg.Question = []dns.Question{{ 39 | Name: ".", 40 | Qtype: dns.StringToType["AXFR"], 41 | Qclass: dns.ClassINET, 42 | }} 43 | opt := &dns.OPT{ 44 | Hdr: dns.RR_Header{ 45 | Name: ".", 46 | Class: dns.DefaultMsgSize, 47 | Rrtype: dns.TypeOPT, 48 | }, 49 | } 50 | opt.SetDo() 51 | msg.Extra = append(msg.Extra, opt) 52 | 53 | tp := plainTransport() 54 | tp.Server = "f.root-servers.net:53" 55 | reply, err := tp.Exchange(&msg) 56 | assert.Nil(t, err) 57 | assert.Greater(t, len(reply.Answer), 0) 58 | } 59 | -------------------------------------------------------------------------------- /transport/quic.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "context" 5 | "crypto/tls" 6 | "encoding/binary" 7 | "fmt" 8 | "io" 9 | "net" 10 | 11 | "github.com/miekg/dns" 12 | "github.com/quic-go/quic-go" 13 | log "github.com/sirupsen/logrus" 14 | ) 15 | 16 | // DoQ Error Codes 17 | // https://datatracker.ietf.org/doc/html/rfc9250#section-8.4 18 | const ( 19 | DoQNoError = 0x0 // No error. This is used when the connection or stream needs to be closed, but there is no error to signal. 20 | DoQInternalError = 0x1 // The DoQ implementation encountered an internal error and is incapable of pursuing the transaction or the connection. 21 | DoQProtocolError = 0x2 // The DoQ implementation encountered a protocol error and is forcibly aborting the connection. 22 | DoQRequestCancelled = 0x3 // A DoQ client uses this to signal that it wants to cancel an outstanding transaction. 23 | DoQExcessiveLoad = 0x4 // A DoQ implementation uses this to signal when closing a connection due to excessive load. 24 | DoQUnspecifiedError = 0x5 // A DoQ implementation uses this in the absence of a more specific error code. 25 | DoQErrorReserved = 0xd098ea5e // Alternative error code used for tests. 26 | ) 27 | 28 | // QUIC makes a DNS query over QUIC 29 | type QUIC struct { 30 | Common 31 | TLSConfig *tls.Config 32 | PMTUD bool 33 | AddLengthPrefix bool 34 | 35 | conn *quic.Connection 36 | } 37 | 38 | func (q *QUIC) connection() quic.Connection { 39 | return *q.conn 40 | } 41 | 42 | // setServerName sets the TLS config server name to the QUIC server 43 | func (q *QUIC) setServerName() { 44 | host, _, err := net.SplitHostPort(q.Server) 45 | if err != nil { 46 | log.Fatalf("invalid QUIC server address: %s", err) 47 | } 48 | q.TLSConfig.ServerName = host 49 | } 50 | 51 | func (q *QUIC) Exchange(msg *dns.Msg) (*dns.Msg, error) { 52 | if q.conn == nil || !q.ReuseConn { 53 | log.Debugf("Connecting to %s", q.Server) 54 | q.setServerName() 55 | if len(q.TLSConfig.NextProtos) == 0 { 56 | log.Debug("No ALPN tokens specified, using default: \"doq\"") 57 | q.TLSConfig.NextProtos = []string{"doq"} 58 | } 59 | log.Debugf("Dialing with QUIC ALPN tokens: %v", q.TLSConfig.NextProtos) 60 | conn, err := quic.DialAddr( 61 | context.Background(), 62 | q.Server, 63 | q.TLSConfig, 64 | &quic.Config{ 65 | DisablePathMTUDiscovery: !q.PMTUD, 66 | }, 67 | ) 68 | if err != nil { 69 | return nil, fmt.Errorf("opening quic session to %s: %v", q.Server, err) 70 | } 71 | q.conn = &conn 72 | } 73 | 74 | // Clients and servers MUST NOT send the edns-tcp-keepalive EDNS(0) Option [RFC7828] in any messages sent 75 | // on a DoQ connection (because it is specific to the use of TCP/TLS as a transport). 76 | // https://datatracker.ietf.org/doc/html/rfc9250#section-5.5.2 77 | if opt := msg.IsEdns0(); opt != nil { 78 | for _, option := range opt.Option { 79 | if option.Option() == dns.EDNS0TCPKEEPALIVE { 80 | _ = q.connection().CloseWithError(DoQProtocolError, "") // Already closing the connection, so we don't care about the error 81 | q.conn = nil 82 | return nil, fmt.Errorf("EDNS0 TCP keepalive option is set") 83 | } 84 | } 85 | } 86 | 87 | stream, err := q.connection().OpenStream() 88 | if err != nil { 89 | return nil, fmt.Errorf("open new stream to %s: %v", q.Server, err) 90 | } 91 | 92 | // When sending queries over a QUIC connection, the DNS Message ID MUST 93 | // be set to zero. The stream mapping for DoQ allows for unambiguous 94 | // correlation of queries and responses and so the Message ID field is 95 | // not required. 96 | // https://datatracker.ietf.org/doc/html/rfc9250#section-4.2.1 97 | msg.Id = 0 98 | buf, err := msg.Pack() 99 | if err != nil { 100 | return nil, err 101 | } 102 | 103 | if q.AddLengthPrefix { 104 | // All DNS messages (queries and responses) sent over DoQ connections 105 | // MUST be encoded as a 2-octet length field followed by the message 106 | // content as specified in [RFC1035]. 107 | // https://datatracker.ietf.org/doc/html/rfc9250#section-4.2-4 108 | _, err = stream.Write(addPrefix(buf)) 109 | } else { 110 | _, err = stream.Write(buf) 111 | } 112 | if err != nil { 113 | return nil, err 114 | } 115 | 116 | // The client MUST send the DNS query over the selected stream, and MUST 117 | // indicate through the STREAM FIN mechanism that no further data will 118 | // be sent on that stream. 119 | // https://datatracker.ietf.org/doc/html/rfc9250#section-4.2 120 | _ = stream.Close() 121 | 122 | respBuf, err := io.ReadAll(stream) 123 | if err != nil { 124 | return nil, fmt.Errorf("reading response from %s: %s", q.Server, err) 125 | } 126 | if len(respBuf) == 0 { 127 | return nil, fmt.Errorf("empty response from %s", q.Server) 128 | } 129 | 130 | reply := dns.Msg{} 131 | if q.AddLengthPrefix { 132 | err = reply.Unpack(respBuf[2:]) 133 | } else { 134 | err = reply.Unpack(respBuf) 135 | } 136 | if err != nil { 137 | return nil, fmt.Errorf("unpacking response from %s: %s", q.Server, err) 138 | } 139 | 140 | return &reply, nil 141 | } 142 | 143 | // addPrefix adds a 2-byte prefix with the DNS message length. 144 | func addPrefix(b []byte) (m []byte) { 145 | m = make([]byte, 2+len(b)) 146 | binary.BigEndian.PutUint16(m, uint16(len(b))) 147 | copy(m[2:], b) 148 | 149 | return m 150 | } 151 | 152 | func (q *QUIC) Close() error { 153 | return q.connection().CloseWithError(DoQNoError, "") 154 | } 155 | -------------------------------------------------------------------------------- /transport/quic_test.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import "crypto/tls" 4 | 5 | func quicTransport() *QUIC { 6 | return &QUIC{ 7 | Common: Common{Server: "dns.adguard.com:8853"}, 8 | PMTUD: true, 9 | AddLengthPrefix: true, 10 | TLSConfig: &tls.Config{NextProtos: []string{"doq"}}, 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /transport/tls.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "crypto/tls" 5 | "fmt" 6 | "net" 7 | 8 | "github.com/miekg/dns" 9 | ) 10 | 11 | // TLS makes a DNS query over TLS 12 | type TLS struct { 13 | Common 14 | TLSConfig *tls.Config 15 | conn *tls.Conn 16 | } 17 | 18 | func (t *TLS) Exchange(msg *dns.Msg) (*dns.Msg, error) { 19 | if t.conn == nil || !t.ReuseConn { 20 | var err error 21 | t.conn, err = tls.DialWithDialer( 22 | &net.Dialer{}, 23 | "tcp", 24 | t.Server, 25 | t.TLSConfig, 26 | ) 27 | if err != nil { 28 | return nil, err 29 | } 30 | if err = t.conn.Handshake(); err != nil { 31 | return nil, err 32 | } 33 | } 34 | 35 | c := dns.Conn{Conn: t.conn} 36 | if err := c.WriteMsg(msg); err != nil { 37 | return nil, fmt.Errorf("write msg to %s: %v", t.Server, err) 38 | } 39 | 40 | return c.ReadMsg() 41 | } 42 | 43 | // Close closes the TLS connection 44 | func (t *TLS) Close() error { 45 | if t.conn != nil { 46 | return t.conn.Close() 47 | } 48 | return nil 49 | } 50 | -------------------------------------------------------------------------------- /transport/tls_test.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | func tlsTransport() *TLS { 4 | return &TLS{ 5 | Common: Common{ 6 | Server: "dns.quad9.net:853", 7 | ReuseConn: false, 8 | }, 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /transport/transport.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "github.com/miekg/dns" 5 | ) 6 | 7 | type Transport interface { 8 | Exchange(*dns.Msg) (*dns.Msg, error) 9 | Close() error 10 | } 11 | 12 | type Common struct { 13 | Server string 14 | ReuseConn bool 15 | } 16 | 17 | type Type string 18 | 19 | const ( 20 | TypePlain Type = "plain" 21 | TypeTCP Type = "tcp" 22 | TypeTLS Type = "tls" 23 | TypeHTTP Type = "http" 24 | TypeQUIC Type = "quic" 25 | TypeDNSCrypt Type = "dnscrypt" 26 | ) 27 | 28 | // Types is a list of all supported transports 29 | var Types = []Type{TypePlain, TypeTCP, TypeTLS, TypeHTTP, TypeQUIC, TypeDNSCrypt} 30 | 31 | // Interface guards 32 | var ( 33 | _ Transport = (*Plain)(nil) 34 | _ Transport = (*TLS)(nil) 35 | _ Transport = (*HTTP)(nil) 36 | _ Transport = (*ODoH)(nil) 37 | _ Transport = (*QUIC)(nil) 38 | _ Transport = (*DNSCrypt)(nil) 39 | ) 40 | -------------------------------------------------------------------------------- /transport/transport_test.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/miekg/dns" 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | // validQuery creates a simple, valid query for testing 11 | func validQuery() *dns.Msg { 12 | msg := dns.Msg{} 13 | msg.RecursionDesired = true 14 | msg.Id = dns.Id() 15 | msg.Question = []dns.Question{{ 16 | Name: "example.com.", 17 | Qtype: dns.StringToType["A"], 18 | Qclass: dns.ClassINET, 19 | }} 20 | return &msg 21 | } 22 | 23 | // invalidQuery creates a simple, invalid query for testing 24 | func invalidQuery() *dns.Msg { 25 | msg := &dns.Msg{} 26 | msg.RecursionDesired = true 27 | msg.Id = dns.Id() 28 | msg.Question = []dns.Question{{ 29 | Name: "invalid label!", 30 | }} 31 | return msg 32 | } 33 | 34 | func transportHarness(t *testing.T, transport Transport) { 35 | defer transport.Close() 36 | for _, tc := range []struct { 37 | // Name is the name of the test 38 | Name string 39 | 40 | // ShouldError is true if the test should error 41 | ShouldError bool 42 | 43 | // Query is the message to send 44 | Query *dns.Msg 45 | }{ 46 | {Name: "ValidQuery", ShouldError: false, Query: validQuery()}, 47 | {Name: "InvalidQuery", ShouldError: true, Query: invalidQuery()}, 48 | } { 49 | t.Run("TransportHarness"+tc.Name, func(t *testing.T) { 50 | reply, err := transport.Exchange(tc.Query) 51 | if tc.ShouldError { 52 | assert.NotNil(t, err) 53 | } else { 54 | assert.Nil(t, err) 55 | assert.Equal(t, tc.Query.Id, reply.Id) 56 | for _, q := range tc.Query.Question { 57 | for _, a := range reply.Answer { 58 | if q.Name == a.Header().Name { 59 | assert.Equal(t, q.Qtype, a.Header().Rrtype) 60 | assert.Equal(t, q.Qclass, a.Header().Class) 61 | } 62 | } 63 | } 64 | } 65 | }) 66 | } 67 | } 68 | 69 | func TestTransportPlain(t *testing.T) { 70 | transportHarness(t, plainTransport()) 71 | } 72 | 73 | func TestTransportTLS(t *testing.T) { 74 | transportHarness(t, tlsTransport()) 75 | } 76 | 77 | func TestTransportQUIC(t *testing.T) { 78 | transportHarness(t, quicTransport()) 79 | } 80 | 81 | func TestTransportHTTP(t *testing.T) { 82 | transportHarness(t, httpTransport()) 83 | } 84 | 85 | func TestTransportDNSCrypt(t *testing.T) { 86 | transportHarness(t, dnscryptTransport()) 87 | } 88 | 89 | func TestTransportReuseTLS(t *testing.T) { 90 | transport := tlsTransport() 91 | transport.ReuseConn = true 92 | transportHarness(t, transport) 93 | } 94 | 95 | func TestTransportReuseQUIC(t *testing.T) { 96 | transport := quicTransport() 97 | transport.ReuseConn = true 98 | transportHarness(t, transport) 99 | } 100 | 101 | func TestTransportReuseHTTP(t *testing.T) { 102 | transport := httpTransport() 103 | transport.ReuseConn = true 104 | transportHarness(t, transport) 105 | } 106 | 107 | func TestTransportReuseDNSCrypt(t *testing.T) { 108 | transport := dnscryptTransport() 109 | transport.ReuseConn = true 110 | transportHarness(t, transport) 111 | } 112 | 113 | // TODO: Enable test 114 | // func TestTransportODoH(t *testing.T) { 115 | // transportHarness(t, odohTransport()) 116 | // } 117 | // func TestTransportReuseODoH(t *testing.T) { 118 | // transport := odohTransport() 119 | // transport.ReuseConn = true 120 | // reuseTransportHarness(t, transport) 121 | // } 122 | -------------------------------------------------------------------------------- /update-usage-readme.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cat README.md | sed '/# Usage/q' > README.tmp.md 4 | printf '\n```text\n' >> README.tmp.md 5 | stty rows 1000 cols 1000 6 | go build && ./q -h | sed -z '$ s/\n$//' >> README.tmp.md 7 | printf '```\n\n### Demo\n' >> README.tmp.md 8 | cat README.md | sed '1,/### Demo/d' >> README.tmp.md 9 | mv README.tmp.md README.md 10 | -------------------------------------------------------------------------------- /util/tls/tls.go: -------------------------------------------------------------------------------- 1 | package tls 2 | 3 | import ( 4 | "crypto/tls" 5 | 6 | log "github.com/sirupsen/logrus" 7 | ) 8 | 9 | // cipherSuiteToInt converts a cipher suite name to its integer identifier 10 | var cipherSuiteToInt = map[string]uint16{ 11 | // TLS 1.0 - 1.2 12 | "TLS_RSA_WITH_RC4_128_SHA": tls.TLS_RSA_WITH_RC4_128_SHA, 13 | "TLS_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, 14 | "TLS_RSA_WITH_AES_128_CBC_SHA": tls.TLS_RSA_WITH_AES_128_CBC_SHA, 15 | "TLS_RSA_WITH_AES_256_CBC_SHA": tls.TLS_RSA_WITH_AES_256_CBC_SHA, 16 | "TLS_RSA_WITH_AES_128_CBC_SHA256": tls.TLS_RSA_WITH_AES_128_CBC_SHA256, 17 | "TLS_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_RSA_WITH_AES_128_GCM_SHA256, 18 | "TLS_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_RSA_WITH_AES_256_GCM_SHA384, 19 | "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 20 | "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 21 | "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 22 | "TLS_ECDHE_RSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, 23 | "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 24 | "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 25 | "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 26 | "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 27 | "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 28 | "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 29 | "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 30 | "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 31 | "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 32 | "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256": tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 33 | "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256": tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 34 | 35 | // TLS 1.3 36 | "TLS_AES_128_GCM_SHA256": tls.TLS_AES_128_GCM_SHA256, 37 | "TLS_AES_256_GCM_SHA384": tls.TLS_AES_256_GCM_SHA384, 38 | "TLS_CHACHA20_POLY1305_SHA256": tls.TLS_CHACHA20_POLY1305_SHA256, 39 | } 40 | 41 | var curveToInt = map[string]tls.CurveID{ 42 | "P256": tls.CurveP256, 43 | "P384": tls.CurveP384, 44 | "P521": tls.CurveP521, 45 | "X25519": tls.X25519, 46 | } 47 | 48 | // ParseCipherSuites converts a slice of cipher suite names to a slice of cipher suite ints 49 | func ParseCipherSuites(cipherSuites []string) []uint16 { 50 | var cipherSuiteInts []uint16 51 | for _, cipherSuite := range cipherSuites { 52 | if cipherSuiteInt, ok := cipherSuiteToInt[cipherSuite]; ok { 53 | cipherSuiteInts = append(cipherSuiteInts, cipherSuiteInt) 54 | } else { 55 | log.Fatalf("Unknown TLS cipher suite: %s", cipherSuite) 56 | } 57 | } 58 | return cipherSuiteInts 59 | } 60 | 61 | // ParseCurves parses a slice of curves into their IDs 62 | func ParseCurves(curves []string) []tls.CurveID { 63 | var curveIDs []tls.CurveID 64 | for _, curve := range curves { 65 | if curveID, ok := curveToInt[curve]; ok { 66 | curveIDs = append(curveIDs, curveID) 67 | } else { 68 | log.Fatalf("Unknown TLS curve: %s", curve) 69 | } 70 | } 71 | return curveIDs 72 | } 73 | 74 | // Version returns a TLS version number by given protocol string with a fallback 75 | func Version(version string, fallback uint16) uint16 { 76 | switch version { 77 | case "1.0": 78 | return tls.VersionTLS10 79 | case "1.1": 80 | return tls.VersionTLS11 81 | case "1.2": 82 | return tls.VersionTLS12 83 | case "1.3": 84 | return tls.VersionTLS13 85 | default: 86 | return fallback 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "strings" 7 | 8 | log "github.com/sirupsen/logrus" 9 | ) 10 | 11 | var UseColor = true 12 | 13 | const ( 14 | ColorBlack = "black" 15 | ColorRed = "red" 16 | ColorGreen = "green" 17 | ColorYellow = "yellow" 18 | ColorPurple = "purple" 19 | ColorMagenta = "magenta" 20 | ColorTeal = "teal" 21 | ColorWhite = "white" 22 | ) 23 | 24 | // ANSI colors 25 | var colors = map[string]string{ 26 | ColorBlack: "\033[1;30m%s\033[0m", 27 | ColorRed: "\033[1;31m%s\033[0m", 28 | ColorGreen: "\033[1;32m%s\033[0m", 29 | ColorYellow: "\033[1;33m%s\033[0m", 30 | ColorPurple: "\033[1;34m%s\033[0m", 31 | ColorMagenta: "\033[1;35m%s\033[0m", 32 | ColorTeal: "\033[1;36m%s\033[0m", 33 | ColorWhite: "\033[1;37m%s\033[0m", 34 | } 35 | 36 | // Color returns a color formatted string 37 | func Color(color string, args ...interface{}) string { 38 | if _, ok := colors[color]; !ok { 39 | panic("invalid color: " + color) 40 | } 41 | 42 | if UseColor { 43 | return fmt.Sprintf(colors[color], fmt.Sprint(args...)) 44 | } else { 45 | return fmt.Sprint(args...) 46 | } 47 | } 48 | 49 | func ContainsAny(s string, subStrings []string) bool { 50 | for _, sub := range subStrings { 51 | if strings.Contains(s, sub) { 52 | return true 53 | } 54 | } 55 | return false 56 | } 57 | 58 | func MustWriteln(out io.Writer, s string) { 59 | if _, err := out.Write([]byte(s + "\n")); err != nil { 60 | log.Fatal(err) 61 | } 62 | } 63 | 64 | func MustWritef(out io.Writer, format string, a ...interface{}) { 65 | if _, err := out.Write([]byte(fmt.Sprintf(format, a...))); err != nil { 66 | log.Fatal(err) 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /util/util_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "bytes" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestUtilContainsAny(t *testing.T) { 11 | assert.True(t, ContainsAny("foo", []string{"foo", "bar"})) 12 | assert.True(t, ContainsAny("bar", []string{"foo", "bar"})) 13 | assert.False(t, ContainsAny("baz", []string{"foo", "bar"})) 14 | } 15 | 16 | func TestUtilMustWriteln(t *testing.T) { 17 | var out bytes.Buffer 18 | MustWriteln(&out, "foo") 19 | assert.Equal(t, "foo\n", out.String()) 20 | } 21 | 22 | func TestUtilMustWritef(t *testing.T) { 23 | var out bytes.Buffer 24 | MustWritef(&out, "foo %s", "bar") 25 | assert.Equal(t, "foo bar", out.String()) 26 | } 27 | 28 | func TestUtilColor(t *testing.T) { 29 | assert.Equal(t, "\033[1;31mfoo\033[0m", Color("red", "foo")) 30 | assert.Equal(t, "\033[1;37mfoo\033[0m", Color("white", "foo")) 31 | } 32 | -------------------------------------------------------------------------------- /xfr.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "os" 7 | "path" 8 | "strings" 9 | "time" 10 | 11 | "github.com/miekg/dns" 12 | log "github.com/sirupsen/logrus" 13 | 14 | "github.com/natesales/q/util" 15 | ) 16 | 17 | var ( 18 | queried map[string]bool 19 | all []dns.RR 20 | ) 21 | 22 | func axfr(label, server string) []dns.RR { 23 | t := new(dns.Transfer) 24 | m := new(dns.Msg) 25 | m.SetAxfr(dns.Fqdn(label)) 26 | ch, err := t.In(m, server) 27 | if err != nil { 28 | log.Fatalf("Failed to transfer zone: %s", err) 29 | } 30 | 31 | var rrs []dns.RR 32 | for env := range ch { 33 | if env.Error != nil { 34 | log.Warnf("AXFR section error (%s): %s", label, env.Error) 35 | continue 36 | } 37 | rrs = append(rrs, env.RR...) 38 | } 39 | 40 | return rrs 41 | } 42 | 43 | // RecAXFR performs an AXFR on the given label and all of its children and writes the zone file to disk 44 | func RecAXFR(label, server string, out io.Writer) []dns.RR { 45 | util.MustWritef(out, "Attempting recursive AXFR for %s\n", label) 46 | 47 | // Reset state 48 | queried = make(map[string]bool) 49 | all = make([]dns.RR, 0) 50 | 51 | dir := fmt.Sprintf("%s_%s_recaxfr", 52 | strings.TrimPrefix(label, "."), 53 | strings.ReplaceAll(time.Now().Format(time.UnixDate), " ", "-"), 54 | ) 55 | 56 | // Create recursive AXFR directory if it doesn't exist 57 | if _, err := os.Stat(dir); os.IsNotExist(err) { 58 | err := os.MkdirAll(dir, 0755) 59 | if err != nil { 60 | log.Fatalf("creating recaxfr directory: %s", err) 61 | } 62 | } 63 | 64 | addToTree(label, dir, server, out) 65 | util.MustWritef(out, "AXFR complete, %d records saved to %s\n", len(all), dir) 66 | 67 | return all 68 | } 69 | 70 | func addToTree(label, dir, server string, out io.Writer) { 71 | label = dns.Fqdn(label) 72 | if queried[label] { 73 | return 74 | } 75 | util.MustWritef(out, "AXFR %s\n", label) 76 | queried[label] = true 77 | rrs := axfr(label, server) 78 | 79 | // Write RRs to zone file 80 | if len(rrs) > 0 { 81 | var zoneFile string 82 | for _, rr := range rrs { 83 | zoneFile += rr.String() + "\n" 84 | } 85 | if err := os.WriteFile( 86 | path.Join(dir, strings.TrimSuffix(label, ".")+".zone"), 87 | []byte(zoneFile), 88 | 0644, 89 | ); err != nil { 90 | log.Fatalf("Failed to write zone file: %s", err) 91 | } 92 | } 93 | 94 | for _, rr := range rrs { 95 | all = append(all, rr) 96 | if _, ok := rr.(*dns.NS); ok { 97 | addToTree(rr.Header().Name, dir, server, out) 98 | } 99 | } 100 | } 101 | --------------------------------------------------------------------------------