Validator::reverseIpv4()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 10
cts 10
cp 1
rs 9.6333
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Badcow DNS Library.
7
 *
8
 * (c) Samuel Williams <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Badcow\DNS;
15
16
use Badcow\DNS\Rdata\CNAME;
17
use Badcow\DNS\Rdata\NS;
18
use Badcow\DNS\Rdata\SOA;
19
20
class Validator
21
{
22
    const ZONE_OKAY = 0;
23
24
    const ZONE_NO_SOA = 1;
25
26
    const ZONE_TOO_MANY_SOA = 2;
27
28
    const ZONE_NO_NS = 4;
29
30
    const ZONE_NO_CLASS = 8;
31
32
    const ZONE_TOO_MANY_CLASSES = 16;
33
34
    /**
35
     * Validate the string as a valid hostname in accordance with RFC 952 {@link https://tools.ietf.org/html/rfc952}
36
     * and RFC 1123 {@link https://tools.ietf.org/html/rfc1123}.
37
     */
38 112
    public static function hostName(string $name): bool
39
    {
40 112
        return (bool) filter_var($name, FILTER_VALIDATE_DOMAIN, [
41 112
            'flags' => FILTER_FLAG_HOSTNAME,
42
        ]);
43
    }
44
45
    /**
46
     * Validate the string is a Fully Qualified Domain Name.
47
     */
48 114
    public static function fullyQualifiedDomainName(string $name): bool
49
    {
50 114
        if ('.' !== substr($name, -1, 1)) {
51 5
            return false;
52
        }
53
54 111
        return self::hostName($name);
55
    }
56
57
    /**
58
     * Validate the name for a Resource Record. This is distinct from validating a hostname in that this function
59
     * will permit '@' and wildcards as well as underscores used in SRV records.
60
     */
61 44
    public static function resourceRecordName(string $name): bool
62
    {
63 44
        return strlen($name) < 254 &&
64 44
            (1 === preg_match('/(?:^(?:\*\.)?((?!-)[a-z0-9_\-]{1,63}(?<!-)\.?){1,127}$)|^@$|^\*$/i', $name));
65
    }
66
67
    /**
68
     * Validates an IPv4 Address.
69
     *
70
     * @static
71
     */
72 70
    public static function ipv4(string $address): bool
73
    {
74 70
        return (bool) filter_var($address, FILTER_VALIDATE_IP, [
75 70
            'flags' => FILTER_FLAG_IPV4,
76
        ]);
77
    }
78
79
    /**
80
     * Validates an IPv6 Address.
81
     *
82
     * @static
83
     */
84 67
    public static function ipv6(string $address): bool
85
    {
86 67
        return (bool) filter_var($address, FILTER_VALIDATE_IP, [
87 67
            'flags' => FILTER_FLAG_IPV6,
88
        ]);
89
    }
90
91
    /**
92
     * Validates an IPv4 or IPv6 address.
93
     *
94
     * @static
95
     */
96 12
    public static function ipAddress(string $address): bool
97
    {
98 12
        return (bool) filter_var($address, FILTER_VALIDATE_IP);
99
    }
100
101
    /**
102
     * Validates that the zone meets
103
     * RFC-1035 especially that:
104
     *   1) 5.2.1 All RRs in the file should be of the same class.
105
     *   2) 5.2.2 Exactly one SOA RR should be present at the top of the zone.
106
     *   3) There is at least one NS record.
107
     *
108
     * Return values are:
109
     *   - ZONE_NO_SOA
110
     *   - ZONE_TOO_MANY_SOA
111
     *   - ZONE_NO_NS
112
     *   - ZONE_NO_CLASS
113
     *   - ZONE_TOO_MANY_CLASSES
114
     *   - ZONE_OKAY
115
     *
116
     * You SHOULD compare these return values to the defined constants of this
117
     * class rather than against integers directly.
118
     */
119 4
    public static function zone(Zone $zone): int
120
    {
121 4
        $n_soa = self::countResourceRecords($zone, SOA::TYPE);
122 4
        $n_ns = self::countResourceRecords($zone, NS::TYPE);
123 4
        $n_class = self::countClasses($zone);
124
125 4
        $totalError = 0;
126
127 4
        $incrementError = function (bool $errorCondition, int $errorOrdinal) use (&$totalError): void {
128 4
            $totalError += $errorCondition ? $errorOrdinal : 0;
129 4
        };
130
131 4
        $incrementError($n_soa < 1, self::ZONE_NO_SOA);
132 4
        $incrementError($n_soa > 1, self::ZONE_TOO_MANY_SOA);
133 4
        $incrementError($n_ns < 1, self::ZONE_NO_NS);
134 4
        $incrementError($n_class < 1, self::ZONE_NO_CLASS);
135 4
        $incrementError($n_class > 1, self::ZONE_TOO_MANY_CLASSES);
136
137 4
        return $totalError;
138
    }
139
140
    /**
141
     * Counts the number of Resource Records of a particular type ($type) in a Zone.
142
     *
143
     * @param string $type The ResourceRecord type to be counted. If NULL, then the method will return
144
     *                     the number of records without RData.
145
     *
146
     * @return int the number of records to be counted
147
     */
148 4
    public static function countResourceRecords(Zone $zone, ?string $type = null): int
149
    {
150 4
        $n = 0;
151 4
        foreach ($zone as $rr) {
152 4
            $n += (int) ($type === $rr->getType());
153
        }
154
155 4
        return $n;
156
    }
157
158
    /**
159
     * Validates a reverse IPv4 address. Ensures that all octets are in the range [0-255].
160
     */
161 15
    public static function reverseIpv4(string $address): bool
162
    {
163 15
        $pattern = '/^((?:[0-9]+\.){1,4})in\-addr\.arpa\.$/i';
164
165 15
        if (1 !== preg_match($pattern, $address, $matches)) {
166 4
            return false;
167
        }
168
169 11
        $octets = explode('.', $matches[1]);
170 11
        array_pop($octets); //Remove the last decimal from the array
171
172 11
        foreach ($octets as $octet) {
173 11
            if ((int) $octet > 255) {
174 1
                return false;
175
            }
176
        }
177
178 10
        return true;
179
    }
180
181
    /**
182
     * Validates a reverse IPv6 address.
183
     */
184 3
    public static function reverseIpv6(string $address): bool
185
    {
186 3
        $pattern = '/^(?:[0-9a-f]\.){1,32}ip6\.arpa\.$/i';
187
188 3
        return 1 === preg_match($pattern, $address);
189
    }
190
191
    /**
192
     * Determine the number of unique non-null classes in a Zone. In a valid zone this MUST be 1.
193
     */
194 4
    private static function countClasses(Zone $zone): int
195
    {
196 4
        $classes = [];
197
198 4
        foreach ($zone as $rr) {
199 4
            if (null !== $rr->getClass()) {
200 4
                $classes[$rr->getClass()] = null;
201
            }
202
        }
203
204 4
        return count($classes);
205
    }
206
207
    /**
208
     * Ensure $zone does not contain existing CNAME alias corresponding to $newRecord's name.
209
     *
210
     * E.g.
211
     *      www IN CNAME example.com.
212
     *      www IN TXT "This is a violation of DNS specifications."
213
     *
214
     * @see https://tools.ietf.org/html/rfc1034#section-3.6.2
215
     */
216 1
    public static function noAliasInZone(Zone $zone, ResourceRecord $newRecord): bool
217
    {
218 1
        foreach ($zone as $rr) {
219 1
            if (CNAME::TYPE === $rr->getType()
220 1
                && $newRecord->getName() === $rr->getName()) {
221 1
                return false;
222
            }
223
        }
224
225 1
        return true;
226
    }
227
228
    /**
229
     * Determine if string is a base64 encoded string.
230
     *
231
     * @param string $string A base64 encoded string
232
     */
233 1
    public static function isBase64Encoded(string $string): bool
234
    {
235 1
        if (1 !== preg_match('/^[a-zA-Z0-9\/\r\n+ ]*={0,2}$/', $string)) {
236 1
            return false;
237
        }
238
239 1
        if (null === $string = preg_replace('/[^a-zA-Z0-9\/+=]/', '', $string)) {
240
            return false;
241
        }
242
243 1
        if (false === $decoded = base64_decode($string, true)) {
244 1
            return false;
245
        }
246
247 1
        return $string === base64_encode($decoded);
248
    }
249
250
    /**
251
     * Determine if string is a base32 encoded string.
252
     */
253 1
    public static function isBase32Encoded(string $string): bool
254
    {
255 1
        return 1 === preg_match('/^[A-Z2-7]+=*$/', $string);
256
    }
257
258
    /**
259
     * Determine if string is a base32hex (extended hex) encoded string.
260
     */
261
    public static function isBase32HexEncoded(string $string): bool
262
    {
263
        return 1 === preg_match('/^[a-zA-Z0-9]+=*$/', $string);
264
    }
265
266
    /**
267
     * Determine if string is a base16 encoded string.
268
     */
269
    public static function isBase16Encoded(string $string): bool
270
    {
271
        return 1 === preg_match('/^[0-9a-f]+$/i', $string);
272
    }
273
274
    /**
275
     * Determine if $integer is an unsigned integer less than 2^$numberOfBits.
276
     *
277
     * @param int $integer      The integer to test
278
     * @param int $numberOfBits The upper limit that the integer can be expressed as an exponent of 2
279
     */
280 122
    public static function isUnsignedInteger(int $integer, int $numberOfBits): bool
281
    {
282 122
        $maxBits = PHP_INT_SIZE * 8 - 1;
283
284 122
        if ($numberOfBits > $maxBits) {
285 1
            throw new \RuntimeException(sprintf('Number of bits "%d" exceeds maximum binary exponent of "%d".', $numberOfBits, $maxBits));
286
        }
287
288 122
        return (0 <= $integer) && ($integer < (2 ** $numberOfBits));
289
    }
290
}
291