Commit 93ae4bfb authored by Adam Brown's avatar Adam Brown

Initial commit

parents
; This file is for unifying the coding style for different editors and IDEs.
; More information at http://editorconfig.org
root = true
[*]
charset = utf-8
indent_size = 4
indent_style = space
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.yml]
indent_style = space
indent_size = 2
# Path-based git attributes
# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
# Ignore all test and documentation with "export-ignore".
/.gitattributes export-ignore
/.gitignore export-ignore
/.travis.yml export-ignore
/phpunit.xml.dist export-ignore
/.scrutinizer.yml export-ignore
/tests export-ignore
/.editorconfig export-ignore
build
composer.lock
docs
vendor
coverage
\ No newline at end of file
wfilter:
excluded_paths: [tests/*]
checks:
php:
remove_extra_empty_lines: true
remove_php_closing_tag: true
remove_trailing_whitespace: true
fix_use_statements:
remove_unused: true
preserve_multiple: false
preserve_blanklines: true
order_alphabetically: true
fix_php_opening_tag: true
fix_linefeed: true
fix_line_ending: true
fix_identation_4spaces: true
fix_doc_comments: true
preset: laravel
disabled:
- single_class_element_per_statement
- self_accessor
language: php
php:
- 7.1
- 7.2
env:
matrix:
- COMPOSER_FLAGS="--prefer-lowest"
- COMPOSER_FLAGS=""
before_script:
- travis_retry composer self-update
- travis_retry composer update ${COMPOSER_FLAGS} --no-interaction --prefer-source
script:
- vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover
after_script:
- php vendor/bin/ocular code-coverage:upload --format=php-clover coverage.clover
# Changelog
All notable changes to `techendeavors/dnsoverhttps` will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [1.0.0] - 2018-07-08
### Added
-
### Changed
-
### Removed
-
# Contributing
Contributions are **welcome** and will be fully **credited**.
Please read and understand the contribution guide before creating an issue or pull request.
## Etiquette
This project is open source, and as such, the maintainers give their free time to build and maintain the source code
held within. They make the code freely available in the hope that it will be of use to other developers. It would be
extremely unfair for them to suffer abuse or anger for their hard work.
Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the
world that developers are civilized and selfless people.
It's the duty of the maintainer to ensure that all submissions to the project are of sufficient
quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used.
## Viability
When requesting or submitting new features, first consider whether it might be useful to others. Open
source projects are used by many developers, who may have entirely different needs to your own. Think about
whether or not your feature is likely to be used by other users of the project.
## Procedure
Before filing an issue:
- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident.
- Check to make sure your feature suggestion isn't already present within the project.
- Check the pull requests tab to ensure that the bug doesn't have a fix in progress.
- Check the pull requests tab to ensure that the feature isn't already in progress.
Before submitting a pull request:
- Check the codebase to ensure that your feature doesn't already exist.
- Check the pull requests to ensure that another person hasn't already submitted the feature or fix.
## Requirements
If the project maintainer has any additional requirements, you will find them listed here.
- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer).
- **Add tests!** - Your patch won't be accepted if it doesn't have tests.
- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option.
- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.
**Happy coding**!
# Contributing
Contributions are **welcome** and will be fully **credited**.
Please read and understand the [contribution guide](CONTRIBUTING.MD) before creating an issue or pull request.
## Contributors
The MIT License (MIT)
Copyright (c) Techendeavors Startup Cooperative <hello@techendeavors.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# DNSOverHttps
## DNSOverHttps allows you to query DNS records over an HTTPS connection rather than interacting with your local DNS server
[![Latest Version on Packagist](https://img.shields.io/packagist/v/techendeavors/dnsoverhttps.svg?style=flat-square)](https://packagist.org/packages/techendeavors/dnsoverhttps)
[![Total Downloads](https://img.shields.io/packagist/dt/techendeavors/dnsoverhttps.svg?style=flat-square)](https://packagist.org/packages/techendeavors/dnsoverhttps)
DNSOverHttps allows you to query DNS records over an HTTPS connection rather than interacting with your local DNS server. Supports the public Mozilla, Cloudflare, and Google API servers.
The DnsOverHttps servers only support requesting a single record type at a time, but we handle that for you. Just pass an array of record types that you want and the package will query them all and merge them back together into one single object.
While the DNS Over Https servers do a lot of the work, we've also bundled a few extra client-side utilities that might be helpful.
### To Do
- [ ] Build 'techendeavors/tldverify` package and integrate it
- [ ] Allow overriding the DNS Over Https host in the builder
- [ ] Make returned data a little easier to work with.
- [X] Set Guzzle to query in parallel use promises when more than one RR is requested rather than making the request in a serial fashion
- [X] Combine all guzzle promise responses into one single object
- [ ] Allow for distributing requests across multiple hosts rather than just using the primary host
- [X] Allow for package configuration to override constants.
- [ ] Build some validators (DnsHasA, DnsHasAAAA, DnsHasMX, DnsHasSoa, DnsHasNs, etc)
- [ ] Write Tests
- [ ] If Guzzle is not installed, fall back to Curl. Change guzzle requirement to a suggested package.
### Installation
You can install the package via composer:
```bash
composer require techendeavors/dnsoverhttps
```
### Usage
The most basic. `A` and `AAAA` records are assumed unless overridden.
```
$domain = new DNSOverHttps;
$domain->domain('example.com');
$domain->check();
=> [
[
"domain" => "example.com",
"records" => [
"A" => [
"93.184.216.34",
],
"AAAA" => [
"2606:2800:220:1:248:1893:25c8:1946",
],
],
],
]
```
A bit more advanced.
```
$domain = new DNSOverHttps();
$domain->domains(['example.com', 'techendeavors.com', 'packagist.org']);
$domain->records(['A', 'AAAA', 'MX', 'CNAME', 'TXT']);
$domain->check();
=> [
[
"domain" => "example.com",
"records" => [
"A" => [
"93.184.216.34",
],
"MX" => [],
"TXT" => [
""v=spf1 -all"",
""$Id: example.com 4415 2015-08-24 20:12:23Z davids $"",
],
"AAAA" => [
"2606:2800:220:1:248:1893:25c8:1946",
],
],
],
[
"domain" => "packagist.org",
"records" => [
"A" => [
"142.44.164.255",
],
"MX" => [
"10 aspmx2.googlemail.com.",
"5 alt2.aspmx.l.google.com.",
"5 alt1.aspmx.l.google.com.",
"10 aspmx3.googlemail.com.",
"10 aspmx4.googlemail.com.",
"10 aspmx5.googlemail.com.",
"1 aspmx.l.google.com.",
],
"TXT" => [
""v=spf1 a mx mx:ns373883.ip-5-196-92.eu include:_spf.google.com include:amazonses.com ~all"",
""google-site-verification=u1ogg4eabdx_nFHnTHC0s4KfKUkSzaME6FIbDj9NU1Y"",
],
"AAAA" => [
"2607:5300:201:2100::7:2274",
],
],
],
[
"domain" => "techendeavors.com",
"records" => [
"A" => [
"104.28.3.33",
"104.28.2.33",
],
"MX" => [
"20 eagle-relay.mxlogin.com.",
"10 eagle.mxlogin.com.",
],
"TXT" => [
""keybase-site-verification=qUHhd_PYnbKj0SQIzOZuv-LIhPW8wLoCgMZ3Z6nf8A0"",
""keybase-site-verification=5sU4NgQQ1slHOkwKahEVR19_TFm6XQULunmqbtTIXgc"",
""v=spf1 include:mxlogin.com -all"",
],
"AAAA" => [
"2400:cb00:2048:1::681c:221",
"2400:cb00:2048:1::681c:321",
],
],
],
]
```
### Testing
``` bash
composer test
```
### Changelog
Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.
### Contributing
Please see [CONTRIBUTING](CONTRIBUTING.md) for details.
### Security
If you discover any security related issues, please use the [issue tracker](https://gitlab.com/techendeavors/dnsoverhttps)
### Credits
- [Techendeavors](https://gitlab.com/techendeavors)
- [Contributors and Credits](CONTRIBUTORS.md)
### License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
{
"name": "techendeavors/dnsoverhttps",
"description": "DNSOverHttps allows you to query DNS records over an HTTPS connection rather than interacting with your local DNS server. Supports the public Mozilla, Cloudflare, and Google API servers.",
"keywords": [
"techendeavors",
"laravel",
"dnsoverhttps"
],
"homepage": "https://techendeavors.com/packages",
"license": "MIT",
"authors": [
{
"name": "Techendeavors",
"email": "hello@techendeavors.com",
"homepage": "https://techendeavors.com",
"role": "Organization"
},
{
"name": "Adam Brown",
"email": "adam@techendeavors.com",
"homepage": "https://deftnerd.com",
"role": "Developer"
}
],
"repositories": [
{
"type": "git",
"url": "https://gitlab.com/techendeavors/dnsoverhttps"
}
],
"require": {
"php": "^7.1.3",
"illuminate/support": "^5.6",
"illuminate/contracts": "^5.6"
},
"require-dev": {
"orchestra/testbench": "~3.0",
"phpunit/phpunit": "^7.0"
},
"suggest": {
"guzzlehttp/guzzle": "If installed, requests will be made in parallel."
},
"autoload": {
"psr-4": {
"Techendeavors\\DNSOverHttps\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Techendeavors\\DNSOverHttps\\Tests\\": "tests"
}
},
"support" : {
"source" : "https://gitlab.com/techendeavors/dnsoverhttps",
"issues" : "https://gitlab.com/techendeavors/dnsoverhttps/issues"
},
"scripts": {
"test": "vendor/bin/phpunit",
"test-coverage": "vendor/bin/phpunit --coverage-html coverage"
},
"config": {
"sort-packages": true
},
"extra": {
"laravel": {
"providers": [
"Techendeavors\\DNSOverHttps\\DNSOverHttpsServiceProvider"
],
"aliases": {
"DNSOverHttps": "Techendeavors\\DNSOverHttps\\DNSOverHttpsFacade"
}
}
}
}
<?php
return [
/**
* DNSOverHttps Settings
*/
// Array of DNS-Over-HTTPS APIs available
'hosts' => [
'cloudflare' => 'https://cloudflare-dns.com/dns-query',
'mozilla' => 'https://mozilla.cloudflare-dns.com/dns-query',
'google' => 'https://dns.google.com/resolve'
],
// Which DNS-Over-HTTPS API to use for queries
'hostDefault' => 'mozilla',
// If the DNS-Over-HTTPS APi doesn't reply quickly enough, should we try the query again with another host?
'hostFallback' => true,
'hostConnectTimeout' => 10,
'hostReplyTimeout' => 10,
'hostFollowRedirects' => true,
// Resource Records available through the API
'recordsAvailable' => [
'a',
'aaaa',
'cname',
'dnskey',
'ds',
'mx',
'ns',
'ptr',
'soa',
'srv',
'txt'
],
// If a record type isn't specified, what resource records should we query?
'recordsDefault' => [
'a',
'aaaa'
],
// DNS servers sometimes give different results depending on your IP address and apparent geographic location
'geoTargeting' => true,
// We can append random data to your request to make it difficult for network snoopers to try to guess what
// domain you are querying simply because of the request size.
'padding' => [
'enabled' => true,
'characters' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._',
'minimum' => 10,
'maximum' => 50
],
// Verify host SSL certificate
'verifySslCert' => true,
// User agent to report to the host API
'userAgent' => 'Techendeavors-DNSOverHttps-Package',
// If Debugging is enabled, information about the object is returned in a Tinker session while you build it.
'debug' => true,
];
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Spatie Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
<logging>
<log type="tap" target="build/report.tap"/>
<log type="junit" target="build/report.junit.xml"/>
<log type="coverage-html" target="build/coverage"/>
<log type="coverage-text" target="build/coverage.txt"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
</logging>
</phpunit>
<?php
namespace Techendeavors\DNSOverHttps;
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
use Illuminate\Support\Collection;
use Techendeavors\DNSOverHttps\Traits\Builder;
use Techendeavors\DNSOverHttps\Traits\Domain;
class DNSOverHttps
{
use Builder, Domain;
private const HOSTDEFAULT = "https://mozilla.cloudflare-dns.com/dns-query";
private const RECORDSDEFAULT = [
'A',
'AAAA',
];
private const GEOTARGETING = true;
private const PADDING = [
true,
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._',
10,
50
];
private const VERIFYSSLCERT = true;
private const USERAGENT = 'Techendeavors-DNSOverHttps-Package';
private const RECORD_IDS = [
1 => 'A',
2 => 'NS',
5 => 'CNAME',
6 => 'SOA',
12 => 'PTR',
15 => 'MX',
16 => 'TXT',
17 => 'RP',
24 => 'SIG',
25 => 'KEY',
28 => 'AAAA',
33 => 'SRV',
35 => 'NAPTR',
37 => 'CERT',
39 => 'DNAME',
43 => 'DS',
44 => 'SSHFP',
45 => 'IPSECKEY',
46 => 'RRSIG',
47 => 'NSEC',
48 => 'DNSKEY',
50 => 'NSEC3',
51 => 'NSEC3PARAM',
52 => 'TLSA',
59 => 'CDS',
250 => 'TSIG',
257 => 'CAA',
];
protected $config;
protected $dnsServer;
protected $domains;
protected $geoTargeting;
protected $host;
protected $padding;
protected $records;
protected $requests;
protected $responses;
protected $result;
protected $userAgent;
protected $verifySslCert;
/**
* Classes which have a constructor method call this method on each newly-created object,
* so it is suitable for any initialization that the object may need before it is used.
*/
public function __construct()
{
$this->domains = [];
$this->config = config('dnsoverhttps');
$this->geoTargeting = $this->config['geoTargeting'] ?: self::GEOTARGETING;
$this->host = $this->config['hosts'][$this->config['hostDefault']] ?: self::HOSTDEFAULT;
$this->padding = [ 'enabled' => $this->config['padding']['enabled'] ?: self::PADDING[0],
'characters' => $this->config['padding']['characters'] ?: self::PADDING[1],
'minimum' => $this->config['padding']['minimum'] ?: self::PADDING[2],
'maximum' => $this->config['padding']['maximum'] ?: self::PADDING[3]
];
$this->records = $this->config['recordsDefault'] ?: self::RECORDSDEFAULT;
$this->userAgent = $this->config['userAgent'] ?: self::USERAGENT;
$this->verifySslCert = $this->config['verifySslCert'] ?: self::VERIFYSSLCERT;
$this->requests = [];
$this->responses = [];
$this->result = [];
}
/**
* The __invoke() method is called when a script tries to call an object as a function.
* https://secure.php.net/manual/en/language.oop5.magic.php#object.invoke
*/
public function __invoke($domains)
{
var_dump($domains); // example
}
/**
* The __toString() method allows a class to decide how it will react when it is treated like a string. For
* example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR
* level error is emitted.
* https://secure.php.net/manual/en/language.oop5.magic.php#object.tostring
*/
public function __toString()
{
return (string) implode(",", $this->domains);
}
public function generateQuery(string $domain, string $record)
{
$query['name'] = $domain;
$query['type'] = strtoupper($record);
if ($this->geoTargeting == false) {
$query['edns_client_subnet'] = '0.0.0.0/0';
}
if ($this->padding['enabled'] == true) {
$query['random_padding'] = static::randomPadding();
}
$fullquery = $this->host."?".http_build_query($query);
return (string) $fullquery;
}
public function check()
{
$clientConfig = [
'base_uri' => $this->host,
'allow_redirects' => $this->config['hostFollowRedirects'] ?: true,
'connect_timeout' => $this->config['hostConnectTimeout'] ?: 10,
'force_ip_resolve' => 'v4',
'headers' => [
'accept' => 'application/dns-json',
'User-Agent' => $this->userAgent,
],
'timeout' => $this->config['hostReplyTimeout'] ?: 10,
'verify' => $this->verifySslCert,
];
$client = new Client($clientConfig);
reset($this->domains);
reset($this->records);
$promises = [];
foreach ($this->domains as $domain) {
foreach ($this->records as $record) {
$query = self::generateQuery($domain, $record);
$this->requests[] = $query;
$promises[] = $client->requestAsync('GET', $query);
}
}
Promise\all($promises)->then(function (array $responses) {
foreach ($responses as $response) {
$this->responses[] = json_decode($response->getBody(), true);
}
})->wait();
$combined = collect(array_collapse(array_pluck($this->responses, 'Answer')))
->sortBy('type')
->sortBy('name')
->unique(function ($item) {
return $item['name'].$item['type'].$item['data'];
});
return self::buildResult($combined);
}
/**
* This method is called by var_dump() when dumping an object to get the properties that should be shown.
* If the method isn't defined on an object, then all public, protected and private properties will be shown.
*/
public function __debugInfo()
{
$debugInfo = [
'dnsServer' => $this->dnsServer,
'domains' => $this->domains,
'geoTargeting' => $this->geoTargeting,
'host' => $this->host,
'padding' => $this->padding,
'records' => $this->records,
'requests' => $this->requests,
'responses' => $this->responses,
'result' => $this->result,
'userAgent' => $this->userAgent,
'verifySslCert' => $this->verifySslCert,
];
if ($this->config['debug']) {
return $debugInfo;
}
return null;
}
/**
* __call() is triggered when invoking inaccessible methods in an object context.
* $obj = new MethodTest;
* $obj->runTest('in object context');
*
* Returns: Calling object method 'runTest' in object context
*/
public function __call($name, $arguments)
{
// Note: value of $name is case sensitive.
echo "Calling object method '$name' "
. implode(', ', $arguments). "\n";
}
/**
* __call() is triggered when invoking inaccessible methods in a static context.
* MethodTest::runTest('in static context');
*
* Returns: Calling static method 'runTest' in static context
*/
public static function __callStatic($name, $arguments)
{
// Note: value of $name is case sensitive.