Botan 3.14.1
Crypto and TLS for C&
dns_name.cpp
Go to the documentation of this file.
1/*
2* (C) 2026 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#include <botan/dns_name.h>
8
9#include <algorithm>
10
11namespace Botan {
12
13namespace {
14
15/*
16* Validate @p name as an RFC 1035 / 1123 DNS name and return its
17* lowercased canonical form. Throws Decoding_Error if @p name is not
18* a valid DNS name. A "*" label is accepted so SAN wildcard entries
19* round-trip through this validator unchanged.
20*/
21std::optional<std::string> check_and_canonicalize_dns_name(std::string_view name) {
22 /*
23 * RFC 1035 limits names to "255 octets or less", but that is in the wire
24 * encoding, which includes a length octet per label plus the root label.
25 * In presentation form (without a trailing dot) the limit is 253.
26 */
27 if(name.size() > 253) {
28 return {};
29 }
30
31 // DNS names are not empty
32 if(name.empty()) {
33 return {};
34 }
35
36 // DNS names do not start with or end with a dot
37 if(name.starts_with('.') || name.ends_with('.')) {
38 return {};
39 }
40
41 /*
42 * Table mapping uppercase to lowercase and only including values valid for
43 * DNS names: A-Z, a-z, 0-9, '-', '.', plus '*' for wildcarding (RFC 1035)
44 */
45 // clang-format off
46 constexpr uint8_t DNS_CHAR_MAPPING[128] = {
47 '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
48 '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
49 '\0', '\0', '\0', '\0', '*', '\0', '\0', '-', '.', '\0', '0', '1', '2', '3', '4', '5', '6', '7', '8',
50 '9', '\0', '\0', '\0', '\0', '\0', '\0', '\0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
51 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '\0', '\0', '\0', '\0',
52 '\0', '\0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
53 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '\0', '\0', '\0', '\0', '\0',
54 };
55 // clang-format on
56
57 std::string canon;
58 canon.reserve(name.size());
59
60 // RFC 1035: DNS labels must not exceed 63 characters
61 size_t current_label_length = 0;
62
63 // Tracks if the name consists only of digits and dots
64 bool all_numeric = true;
65
66 for(size_t i = 0; i != name.size(); ++i) {
67 const char c = name[i];
68
69 if(c == '.') {
70 // Sequential dot (.) characters are not allowed
71 if(i > 0 && name[i - 1] == '.') {
72 return {};
73 }
74
75 // Empty labels are not allowed
76 if(current_label_length == 0) {
77 return {};
78 }
79 current_label_length = 0; // Reset for next label
80 } else {
81 current_label_length++;
82
83 // Labels cannot exceed maximum DNS label length
84 if(current_label_length > 63) {
85 return {};
86 }
87 }
88
89 const uint8_t cu = static_cast<uint8_t>(c);
90 // DNS names are not allowed to include any high-bit set characters
91 if(cu >= 128) {
92 return {};
93 }
94 const uint8_t mapped = DNS_CHAR_MAPPING[cu];
95 // DNS names are from a restricted character set
96 if(mapped == 0) {
97 return {};
98 }
99
100 if(mapped != '.' && (mapped < '0' || mapped > '9')) {
101 all_numeric = false;
102 }
103
104 if(mapped == '-') {
105 // DNS labels are not allowed to include a leading or trailing hyphen
106 if(i == 0 || (i > 0 && name[i - 1] == '.')) {
107 return {}; // leading hyphen
108 }
109
110 if(i == name.size() - 1 || (i < name.size() - 1 && name[i + 1] == '.')) {
111 return {}; // trailing hyphen
112 }
113 }
114 canon.push_back(static_cast<char>(mapped));
115 }
116
117 // This should never be hit, due to earlier validation steps
118 if(current_label_length == 0) {
119 return {};
120 }
121
122 // An entirely numeric name ("1.2.3.4") is either a misplaced IP address
123 // or an attempt at confusing some other system; reject outright
124 if(all_numeric) {
125 return {};
126 }
127
128 return canon;
129}
130
131} // namespace
132
133//static
134std::optional<DNSName> DNSName::from_string(std::string_view name) {
135 if(auto canon = check_and_canonicalize_dns_name(name)) {
136 // TODO(C++23) std::string::contains
137 if(canon->find('*') != std::string::npos) {
138 return {};
139 }
140 return DNSName(std::move(*canon));
141 } else {
142 return {};
143 }
144}
145
146//static
147std::optional<DNSName> DNSName::from_san_string(std::string_view name) {
148 if(auto canon = check_and_canonicalize_dns_name(name)) {
149 /*
150 Validate the wildcard shape: at most one "*", and if present it must be in
151 the leftmost label (no "." before it). This matches the RFC 6125 6.4.3
152 form that host_wildcard_match accepts and rejects eg "*.*.example.com" or
153 "foo.*.example.com"
154 */
155 const auto first_star = canon->find('*');
156 if(first_star != std::string::npos) {
157 if(canon->find('*', first_star + 1) != std::string::npos) {
158 return std::nullopt;
159 }
160 const auto first_dot = canon->find('.');
161 if(first_dot != std::string::npos && first_dot < first_star) {
162 return std::nullopt;
163 }
164 /*
165 RFC 6125 6.4.3: "the client SHOULD NOT attempt to match a presented
166 identifier where the wildcard character is embedded within an
167 A-label or U-label"
168 */
169 if(canon->starts_with("xn--")) {
170 return std::nullopt;
171 }
172 // A wildcard match requires at least three labels, so shorter
173 // patterns ("*", "*.com") could never match any host
174 if(std::count(canon->begin(), canon->end(), '.') < 2) {
175 return std::nullopt;
176 }
177 }
178 return DNSName(std::move(*canon));
179 } else {
180 return {};
181 }
182}
183
184bool DNSName::matches_wildcard(std::string_view wildcard) const {
185 return host_wildcard_match(wildcard, m_name);
186}
187
188//static
189bool DNSName::host_wildcard_match(std::string_view issued, std::string_view host) {
190 if(host.empty() || issued.empty()) {
191 return false;
192 }
193
194 // Maximum valid DNS name
195 if(host.size() > 253) {
196 return false;
197 }
198
199 /*
200 The wildcard if existing absorbs (host.size() - issued.size() + 1) chars,
201 which must be non-negative. So issued cannot possibly exceed host.size() + 1.
202 */
203 if(issued.size() > host.size() + 1) {
204 return false;
205 }
206
207 /*
208 If there are embedded nulls in your issued name
209 Well I feel bad for you son
210 */
211 if(issued.find('\0') != std::string_view::npos || host.find('\0') != std::string_view::npos) {
212 return false;
213 }
214
215 // '*' is not a valid character in DNS names so should not appear on the host side
216 if(host.find('*') != std::string_view::npos) {
217 return false;
218 }
219
220 // Similarly a DNS name can't end in .
221 if(host.back() == '.') {
222 return false;
223 }
224
225 // Nor can it start with one
226 if(host.front() == '.') {
227 return false;
228 }
229
230 // And a host can't have an empty name component, so reject that
231 if(host.find("..") != std::string_view::npos) {
232 return false;
233 }
234
235 // ASCII-only case-insensitive char equality, avoids locale overhead from tolower
236 auto dns_char_eq = [](char a, char b) -> bool {
237 if(a == b) {
238 return true;
239 }
240 const auto la = static_cast<unsigned char>(a | 0x20);
241 const auto lb = static_cast<unsigned char>(b | 0x20);
242 return la == lb && la >= 'a' && la <= 'z';
243 };
244
245 auto dns_char_eq_range = [&](std::string_view a, std::string_view b) -> bool {
246 if(a.size() != b.size()) {
247 return false;
248 }
249 for(size_t i = 0; i != a.size(); ++i) {
250 if(!dns_char_eq(a[i], b[i])) {
251 return false;
252 }
253 }
254 return true;
255 };
256
257 // Exact match: accept
258 if(dns_char_eq_range(issued, host)) {
259 return true;
260 }
261
262 // First detect offset of wildcard '*' if included
263 const size_t first_star = issued.find('*');
264 const bool has_wildcard = (first_star != std::string_view::npos);
265
266 // At most one wildcard is allowed
267 if(has_wildcard && issued.find('*', first_star + 1) != std::string_view::npos) {
268 return false;
269 }
270
271 // If no * at all then not a wildcard, and so not a match
272 if(!has_wildcard) {
273 return false;
274 }
275
276 /*
277 RFC 6125 6.4.3: "the client SHOULD NOT attempt to match a presented
278 identifier where the wildcard character is embedded within an
279 A-label or U-label"
280
281 The host side check rejects a partial wildcard absorbing part of an
282 A-label of the host, which would otherwise allow the same confusion.
283 */
284 const auto is_idna_prefixed = [&](std::string_view label) {
285 return label.size() >= 4 && dns_char_eq_range(label.substr(0, 4), "xn--");
286 };
287 const auto issued_label = issued.substr(0, issued.find('.'));
288 if(is_idna_prefixed(issued_label)) {
289 return false;
290 }
291 if(issued_label != "*" && is_idna_prefixed(host.substr(0, host.find('.')))) {
292 return false;
293 }
294
295 /*
296 Now walk through the issued string, making sure every character
297 matches. When we come to the (singular) '*', jump forward in the
298 hostname by the corresponding amount. We know exactly how much
299 space the wildcard takes because it must be exactly `len(host) -
300 len(issued) + 1 chars`.
301
302 We also verify that the '*' comes in the leftmost component, and
303 doesn't skip over any '.' in the hostname.
304 */
305 size_t dots_seen = 0;
306 size_t host_idx = 0;
307
308 for(size_t i = 0; i != issued.size(); ++i) {
309 if(issued[i] == '.') {
310 dots_seen += 1;
311 }
312
313 if(issued[i] == '*') {
314 // Fail: wildcard can only come in leftmost component
315 if(dots_seen > 0) {
316 return false;
317 }
318
319 /*
320 Since there is only one * we know the tail of the issued and
321 hostname must be an exact match. In this case advance host_idx
322 to match.
323 */
324 const size_t advance = (host.size() - issued.size() + 1);
325
326 if(host_idx + advance > host.size()) { // shouldn't happen
327 return false;
328 }
329
330 // Can't be any intervening .s that we would have skipped
331 for(size_t k = host_idx; k != host_idx + advance; ++k) {
332 if(host[k] == '.') {
333 return false;
334 }
335 }
336
337 host_idx += advance;
338 } else {
339 if(!dns_char_eq(issued[i], host[host_idx])) {
340 return false;
341 }
342
343 host_idx += 1;
344 }
345 }
346
347 // Wildcard issued name must have at least 3 components
348 if(dots_seen < 2) {
349 return false;
350 }
351
352 return true;
353}
354
355} // namespace Botan
bool matches_wildcard(std::string_view wildcard) const
Definition dns_name.cpp:184
static bool host_wildcard_match(std::string_view issued, std::string_view host)
Definition dns_name.cpp:189
static std::optional< DNSName > from_san_string(std::string_view name)
Definition dns_name.cpp:147
static std::optional< DNSName > from_string(std::string_view name)
Definition dns_name.cpp:134
const std::string & name() const
Definition dns_name.h:57
const char * name
Definition ffi_tls.h:59