xref: /freebsd/crypto/openssl/crypto/punycode.c (revision 22d7dd834bc5cd189810e414701e3ad1e98102e4)
1 /*
2  * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include <stddef.h>
11 #include <string.h>
12 #include <stdio.h>
13 #include <openssl/e_os2.h>
14 #include "crypto/punycode.h"
15 
16 static const unsigned int base = 36;
17 static const unsigned int tmin = 1;
18 static const unsigned int tmax = 26;
19 static const unsigned int skew = 38;
20 static const unsigned int damp = 700;
21 static const unsigned int initial_bias = 72;
22 static const unsigned int initial_n = 0x80;
23 static const unsigned int maxint = 0xFFFFFFFF;
24 static const char delimiter = '-';
25 
26 #define LABEL_BUF_SIZE 512
27 
28 /*-
29  * Pseudocode:
30  *
31  * function adapt(delta,numpoints,firsttime):
32  *  if firsttime then let delta = delta div damp
33  *  else let delta = delta div 2
34  *  let delta = delta + (delta div numpoints)
35  *  let k = 0
36  *  while delta > ((base - tmin) * tmax) div 2 do begin
37  *    let delta = delta div (base - tmin)
38  *    let k = k + base
39  *  end
40  *  return k + (((base - tmin + 1) * delta) div (delta + skew))
41  */
42 
43 static int adapt(unsigned int delta, unsigned int numpoints,
44                  unsigned int firsttime)
45 {
46     unsigned int k = 0;
47 
48     delta = (firsttime) ? delta / damp : delta / 2;
49     delta = delta + delta / numpoints;
50 
51     while (delta > ((base - tmin) * tmax) / 2) {
52         delta = delta / (base - tmin);
53         k = k + base;
54     }
55 
56     return k + (((base - tmin + 1) * delta) / (delta + skew));
57 }
58 
59 static ossl_inline int is_basic(unsigned int a)
60 {
61     return (a < 0x80) ? 1 : 0;
62 }
63 
64 /*-
65  * code points    digit-values
66  * ------------   ----------------------
67  * 41..5A (A-Z) =  0 to 25, respectively
68  * 61..7A (a-z) =  0 to 25, respectively
69  * 30..39 (0-9) = 26 to 35, respectively
70  */
71 static ossl_inline int digit_decoded(const unsigned char a)
72 {
73     if (a >= 0x41 && a <= 0x5A)
74         return a - 0x41;
75 
76     if (a >= 0x61 && a <= 0x7A)
77         return a - 0x61;
78 
79     if (a >= 0x30 && a <= 0x39)
80         return a - 0x30 + 26;
81 
82     return -1;
83 }
84 
85 /*-
86  * Pseudocode:
87  *
88  * function ossl_punycode_decode
89  *  let n = initial_n
90  *  let i = 0
91  *  let bias = initial_bias
92  *  let output = an empty string indexed from 0
93  *  consume all code points before the last delimiter (if there is one)
94  *    and copy them to output, fail on any non-basic code point
95  *  if more than zero code points were consumed then consume one more
96  *    (which will be the last delimiter)
97  *  while the input is not exhausted do begin
98  *    let oldi = i
99  *    let w = 1
100  *    for k = base to infinity in steps of base do begin
101  *      consume a code point, or fail if there was none to consume
102  *      let digit = the code point's digit-value, fail if it has none
103  *      let i = i + digit * w, fail on overflow
104  *      let t = tmin if k <= bias {+ tmin}, or
105  *              tmax if k >= bias + tmax, or k - bias otherwise
106  *      if digit < t then break
107  *      let w = w * (base - t), fail on overflow
108  *    end
109  *    let bias = adapt(i - oldi, length(output) + 1, test oldi is 0?)
110  *    let n = n + i div (length(output) + 1), fail on overflow
111  *    let i = i mod (length(output) + 1)
112  *    {if n is a basic code point then fail}
113  *    insert n into output at position i
114  *    increment i
115  *  end
116  */
117 
118 int ossl_punycode_decode(const char *pEncoded, const size_t enc_len,
119                          unsigned int *pDecoded, unsigned int *pout_length)
120 {
121     unsigned int n = initial_n;
122     unsigned int i = 0;
123     unsigned int bias = initial_bias;
124     size_t processed_in = 0, written_out = 0;
125     unsigned int max_out = *pout_length;
126     unsigned int basic_count = 0;
127     unsigned int loop;
128 
129     for (loop = 0; loop < enc_len; loop++) {
130         if (pEncoded[loop] == delimiter)
131             basic_count = loop;
132     }
133 
134     if (basic_count > 0) {
135         if (basic_count > max_out)
136             return 0;
137 
138         for (loop = 0; loop < basic_count; loop++) {
139             if (is_basic(pEncoded[loop]) == 0)
140                 return 0;
141 
142             pDecoded[loop] = pEncoded[loop];
143             written_out++;
144         }
145         processed_in = basic_count + 1;
146     }
147 
148     for (loop = processed_in; loop < enc_len;) {
149         unsigned int oldi = i;
150         unsigned int w = 1;
151         unsigned int k, t;
152         int digit;
153 
154         for (k = base;; k += base) {
155             if (loop >= enc_len)
156                 return 0;
157 
158             digit = digit_decoded(pEncoded[loop]);
159             loop++;
160 
161             if (digit < 0)
162                 return 0;
163             if ((unsigned int)digit > (maxint - i) / w)
164                 return 0;
165 
166             i = i + digit * w;
167             t = (k <= bias) ? tmin : (k >= bias + tmax) ? tmax : k - bias;
168 
169             if ((unsigned int)digit < t)
170                 break;
171 
172             if (w > maxint / (base - t))
173                 return 0;
174             w = w * (base - t);
175         }
176 
177         bias = adapt(i - oldi, written_out + 1, (oldi == 0));
178         if (i / (written_out + 1) > maxint - n)
179             return 0;
180         n = n + i / (written_out + 1);
181         i %= (written_out + 1);
182 
183         if (written_out >= max_out)
184             return 0;
185 
186         memmove(pDecoded + i + 1, pDecoded + i,
187                 (written_out - i) * sizeof(*pDecoded));
188         pDecoded[i] = n;
189         i++;
190         written_out++;
191     }
192 
193     *pout_length = written_out;
194     return 1;
195 }
196 
197 /*
198  * Encode a code point using UTF-8
199  * return number of bytes on success, 0 on failure
200  * (also produces U+FFFD, which uses 3 bytes on failure)
201  */
202 static int codepoint2utf8(unsigned char *out, unsigned long utf)
203 {
204     if (utf <= 0x7F) {
205         /* Plain ASCII */
206         out[0] = (unsigned char)utf;
207         out[1] = 0;
208         return 1;
209     } else if (utf <= 0x07FF) {
210         /* 2-byte unicode */
211         out[0] = (unsigned char)(((utf >> 6) & 0x1F) | 0xC0);
212         out[1] = (unsigned char)(((utf >> 0) & 0x3F) | 0x80);
213         out[2] = 0;
214         return 2;
215     } else if (utf <= 0xFFFF) {
216         /* 3-byte unicode */
217         out[0] = (unsigned char)(((utf >> 12) & 0x0F) | 0xE0);
218         out[1] = (unsigned char)(((utf >> 6) & 0x3F) | 0x80);
219         out[2] = (unsigned char)(((utf >> 0) & 0x3F) | 0x80);
220         out[3] = 0;
221         return 3;
222     } else if (utf <= 0x10FFFF) {
223         /* 4-byte unicode */
224         out[0] = (unsigned char)(((utf >> 18) & 0x07) | 0xF0);
225         out[1] = (unsigned char)(((utf >> 12) & 0x3F) | 0x80);
226         out[2] = (unsigned char)(((utf >> 6) & 0x3F) | 0x80);
227         out[3] = (unsigned char)(((utf >> 0) & 0x3F) | 0x80);
228         out[4] = 0;
229         return 4;
230     } else {
231         /* error - use replacement character */
232         out[0] = (unsigned char)0xEF;
233         out[1] = (unsigned char)0xBF;
234         out[2] = (unsigned char)0xBD;
235         out[3] = 0;
236         return 0;
237     }
238 }
239 
240 /*-
241  * Return values:
242  * 1 - ok, *outlen contains valid buf length
243  * 0 - ok but buf was too short, *outlen contains valid buf length
244  * -1 - bad string passed
245  */
246 
247 int ossl_a2ulabel(const char *in, char *out, size_t *outlen)
248 {
249     /*-
250      * Domain name has some parts consisting of ASCII chars joined with dot.
251      * If a part is shorter than 5 chars, it becomes U-label as is.
252      * If it does not start with xn--,    it becomes U-label as is.
253      * Otherwise we try to decode it.
254      */
255     char *outptr = out;
256     const char *inptr = in;
257     size_t size = 0, maxsize;
258     int result = 1;
259     unsigned int i, j;
260     unsigned int buf[LABEL_BUF_SIZE];      /* It's a hostname */
261 
262     if (out == NULL) {
263         result = 0;
264         maxsize = 0;
265     } else {
266         maxsize = *outlen;
267     }
268 
269 #define PUSHC(c)                    \
270     do                              \
271         if (size++ < maxsize)       \
272             *outptr++ = c;          \
273         else                        \
274             result = 0;             \
275     while (0)
276 
277     while (1) {
278         char *tmpptr = strchr(inptr, '.');
279         size_t delta = tmpptr != NULL ? (size_t)(tmpptr - inptr) : strlen(inptr);
280 
281         if (strncmp(inptr, "xn--", 4) != 0) {
282             for (i = 0; i < delta + 1; i++)
283                 PUSHC(inptr[i]);
284         } else {
285             unsigned int bufsize = LABEL_BUF_SIZE;
286 
287             if (ossl_punycode_decode(inptr + 4, delta - 4, buf, &bufsize) <= 0)
288                 return -1;
289 
290             for (i = 0; i < bufsize; i++) {
291                 unsigned char seed[6];
292                 size_t utfsize = codepoint2utf8(seed, buf[i]);
293 
294                 if (utfsize == 0)
295                     return -1;
296 
297                 for (j = 0; j < utfsize; j++)
298                     PUSHC(seed[j]);
299             }
300 
301             PUSHC(tmpptr != NULL ? '.' : '\0');
302         }
303 
304         if (tmpptr == NULL)
305             break;
306 
307         inptr = tmpptr + 1;
308     }
309 #undef PUSHC
310 
311     *outlen = size;
312     return result;
313 }
314 
315 /*-
316  * a MUST be A-label
317  * u MUST be U-label
318  * Returns 0 if compared values are equal
319  * 1 if not
320  * -1 in case of errors
321  */
322 
323 int ossl_a2ucompare(const char *a, const char *u)
324 {
325     char a_ulabel[LABEL_BUF_SIZE + 1];
326     size_t a_size = sizeof(a_ulabel);
327 
328     if (ossl_a2ulabel(a, a_ulabel, &a_size) <= 0)
329         return -1;
330 
331     return strcmp(a_ulabel, u) != 0;
332 }
333