xref: /freebsd/lib/libc/net/base64.c (revision 2f9966ff63d65bd474478888c9088eeae3f9c669)
1 /*
2  * Copyright (c) 1996, 1998 by Internet Software Consortium.
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
9  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
10  * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
11  * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
12  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
13  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
14  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
15  * SOFTWARE.
16  */
17 
18 /*
19  * Portions Copyright (c) 1995 by International Business Machines, Inc.
20  *
21  * International Business Machines, Inc. (hereinafter called IBM) grants
22  * permission under its copyrights to use, copy, modify, and distribute this
23  * Software with or without fee, provided that the above copyright notice and
24  * all paragraphs of this notice appear in all copies, and that the name of IBM
25  * not be used in connection with the marketing of any product incorporating
26  * the Software or modifications thereof, without specific, written prior
27  * permission.
28  *
29  * To the extent it has a right to do so, IBM grants an immunity from suit
30  * under its patents, if any, for the use, sale or manufacture of products to
31  * the extent that such products are used for performing Domain Name System
32  * dynamic updates in TCP/IP networks by means of the Software.  No immunity is
33  * granted for any product per se or for any other function of any product.
34  *
35  * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES,
36  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
37  * PARTICULAR PURPOSE.  IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL,
38  * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING
39  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN
40  * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES.
41  */
42 
43 #include <sys/param.h>
44 #include <sys/socket.h>
45 
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48 #include <arpa/nameser.h>
49 
50 #include <ctype.h>
51 #include <resolv.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 
56 #define Assert(Cond) if (!(Cond)) abort()
57 
58 static const char Base64[] =
59 	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
60 static const char Pad64 = '=';
61 
62 /* (From RFC1521 and draft-ietf-dnssec-secext-03.txt)
63    The following encoding technique is taken from RFC 1521 by Borenstein
64    and Freed.  It is reproduced here in a slightly edited form for
65    convenience.
66 
67    A 65-character subset of US-ASCII is used, enabling 6 bits to be
68    represented per printable character. (The extra 65th character, "=",
69    is used to signify a special processing function.)
70 
71    The encoding process represents 24-bit groups of input bits as output
72    strings of 4 encoded characters. Proceeding from left to right, a
73    24-bit input group is formed by concatenating 3 8-bit input groups.
74    These 24 bits are then treated as 4 concatenated 6-bit groups, each
75    of which is translated into a single digit in the base64 alphabet.
76 
77    Each 6-bit group is used as an index into an array of 64 printable
78    characters. The character referenced by the index is placed in the
79    output string.
80 
81                          Table 1: The Base64 Alphabet
82 
83       Value Encoding  Value Encoding  Value Encoding  Value Encoding
84           0 A            17 R            34 i            51 z
85           1 B            18 S            35 j            52 0
86           2 C            19 T            36 k            53 1
87           3 D            20 U            37 l            54 2
88           4 E            21 V            38 m            55 3
89           5 F            22 W            39 n            56 4
90           6 G            23 X            40 o            57 5
91           7 H            24 Y            41 p            58 6
92           8 I            25 Z            42 q            59 7
93           9 J            26 a            43 r            60 8
94          10 K            27 b            44 s            61 9
95          11 L            28 c            45 t            62 +
96          12 M            29 d            46 u            63 /
97          13 N            30 e            47 v
98          14 O            31 f            48 w         (pad) =
99          15 P            32 g            49 x
100          16 Q            33 h            50 y
101 
102    Special processing is performed if fewer than 24 bits are available
103    at the end of the data being encoded.  A full encoding quantum is
104    always completed at the end of a quantity.  When fewer than 24 input
105    bits are available in an input group, zero bits are added (on the
106    right) to form an integral number of 6-bit groups.  Padding at the
107    end of the data is performed using the '=' character.
108 
109    Since all base64 input is an integral number of octets, only the
110          -------------------------------------------------
111    following cases can arise:
112 
113        (1) the final quantum of encoding input is an integral
114            multiple of 24 bits; here, the final unit of encoded
115 	   output will be an integral multiple of 4 characters
116 	   with no "=" padding,
117        (2) the final quantum of encoding input is exactly 8 bits;
118            here, the final unit of encoded output will be two
119 	   characters followed by two "=" padding characters, or
120        (3) the final quantum of encoding input is exactly 16 bits;
121            here, the final unit of encoded output will be three
122 	   characters followed by one "=" padding character.
123    */
124 
125 int
126 b64_ntop(u_char const *src, size_t srclength, char *target, size_t targsize) {
127 	size_t datalength = 0;
128 	u_char input[3];
129 	u_char output[4];
130 	size_t i;
131 
132 	while (2 < srclength) {
133 		input[0] = *src++;
134 		input[1] = *src++;
135 		input[2] = *src++;
136 		srclength -= 3;
137 
138 		output[0] = input[0] >> 2;
139 		output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4);
140 		output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6);
141 		output[3] = input[2] & 0x3f;
142 		Assert(output[0] < 64);
143 		Assert(output[1] < 64);
144 		Assert(output[2] < 64);
145 		Assert(output[3] < 64);
146 
147 		if (datalength + 4 > targsize)
148 			return (-1);
149 		target[datalength++] = Base64[output[0]];
150 		target[datalength++] = Base64[output[1]];
151 		target[datalength++] = Base64[output[2]];
152 		target[datalength++] = Base64[output[3]];
153 	}
154 
155 	/* Now we worry about padding. */
156 	if (0 != srclength) {
157 		/* Get what's left. */
158 		input[0] = input[1] = input[2] = '\0';
159 		for (i = 0; i < srclength; i++)
160 			input[i] = *src++;
161 
162 		output[0] = input[0] >> 2;
163 		output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4);
164 		output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6);
165 		Assert(output[0] < 64);
166 		Assert(output[1] < 64);
167 		Assert(output[2] < 64);
168 
169 		if (datalength + 4 > targsize)
170 			return (-1);
171 		target[datalength++] = Base64[output[0]];
172 		target[datalength++] = Base64[output[1]];
173 		if (srclength == 1)
174 			target[datalength++] = Pad64;
175 		else
176 			target[datalength++] = Base64[output[2]];
177 		target[datalength++] = Pad64;
178 	}
179 	if (datalength >= targsize)
180 		return (-1);
181 	target[datalength] = '\0';	/* Returned value doesn't count \0. */
182 	return (datalength);
183 }
184 
185 /* skips all whitespace anywhere.
186    converts characters, four at a time, starting at (or after)
187    src from base - 64 numbers into three 8 bit bytes in the target area.
188    it returns the number of data bytes stored at the target, or -1 on error.
189  */
190 
191 int
192 b64_pton(const char *src, u_char *target, size_t targsize)
193 {
194 	int tarindex, state, ch;
195 	u_char nextbyte;
196 	char *pos;
197 
198 	state = 0;
199 	tarindex = 0;
200 
201 	while ((ch = *src++) != '\0') {
202 		if (isspace((unsigned char)ch))        /* Skip whitespace anywhere. */
203 			continue;
204 
205 		if (ch == Pad64)
206 			break;
207 
208 		pos = strchr(Base64, ch);
209 		if (pos == NULL)		/* A non-base64 character. */
210 			return (-1);
211 
212 		switch (state) {
213 		case 0:
214 			if (target) {
215 				if ((size_t)tarindex >= targsize)
216 					return (-1);
217 				target[tarindex] = (pos - Base64) << 2;
218 			}
219 			state = 1;
220 			break;
221 		case 1:
222 			if (target) {
223 				if ((size_t)tarindex >= targsize)
224 					return (-1);
225 				target[tarindex]   |=  (pos - Base64) >> 4;
226 				nextbyte = ((pos - Base64) & 0x0f) << 4;
227 				if ((size_t)tarindex + 1 < targsize)
228 					target[tarindex + 1] = nextbyte;
229 				else if (nextbyte)
230 					return (-1);
231 			}
232 			tarindex++;
233 			state = 2;
234 			break;
235 		case 2:
236 			if (target) {
237 				if ((size_t)tarindex >= targsize)
238 					return (-1);
239 				target[tarindex]   |=  (pos - Base64) >> 2;
240 				nextbyte = ((pos - Base64) & 0x03) << 6;
241 				if ((size_t)tarindex + 1 < targsize)
242 					target[tarindex + 1] = nextbyte;
243 				else if (nextbyte)
244 					return (-1);
245 			}
246 			tarindex++;
247 			state = 3;
248 			break;
249 		case 3:
250 			if (target) {
251 				if ((size_t)tarindex >= targsize)
252 					return (-1);
253 				target[tarindex] |= (pos - Base64);
254 			}
255 			tarindex++;
256 			state = 0;
257 			break;
258 		default:
259 			abort();
260 		}
261 	}
262 
263 	/*
264 	 * We are done decoding Base-64 chars.  Let's see if we ended
265 	 * on a byte boundary, and/or with erroneous trailing characters.
266 	 */
267 
268 	if (ch == Pad64) {		/* We got a pad char. */
269 		ch = *src++;		/* Skip it, get next. */
270 		switch (state) {
271 		case 0:		/* Invalid = in first position */
272 		case 1:		/* Invalid = in second position */
273 			return (-1);
274 
275 		case 2:		/* Valid, means one byte of info */
276 			/* Skip any number of spaces. */
277 			for ((void)NULL; ch != '\0'; ch = *src++)
278 				if (!isspace((unsigned char)ch))
279 					break;
280 			/* Make sure there is another trailing = sign. */
281 			if (ch != Pad64)
282 				return (-1);
283 			ch = *src++;		/* Skip the = */
284 			/* Fall through to "single trailing =" case. */
285 			/* FALLTHROUGH */
286 
287 		case 3:		/* Valid, means two bytes of info */
288 			/*
289 			 * We know this char is an =.  Is there anything but
290 			 * whitespace after it?
291 			 */
292 			for ((void)NULL; ch != '\0'; ch = *src++)
293 				if (!isspace((unsigned char)ch))
294 					return (-1);
295 
296 			/*
297 			 * Now make sure for cases 2 and 3 that the "extra"
298 			 * bits that slopped past the last full byte were
299 			 * zeros.  If we don't check them, they become a
300 			 * subliminal channel.
301 			 */
302 			if (target && (size_t)tarindex < targsize &&
303 			    target[tarindex] != 0)
304 				return (-1);
305 		}
306 	} else {
307 		/*
308 		 * We ended by seeing the end of the string.  Make sure we
309 		 * have no partial bytes lying around.
310 		 */
311 		if (state != 0)
312 			return (-1);
313 	}
314 
315 	return (tarindex);
316 }
317