xref: /netbsd-src/lib/libcrypt/bcrypt.c (revision 9ddb6ab554e70fb9bbd90c3d96b812bc57755a14)
1 /*	$NetBSD: bcrypt.c,v 1.15 2011/12/28 03:12:38 christos Exp $	*/
2 /*	$OpenBSD: bcrypt.c,v 1.16 2002/02/19 19:39:36 millert Exp $	*/
3 
4 /*
5  * Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by Niels Provos.
19  * 4. The name of the author may not be used to endorse or promote products
20  *    derived from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 /* This password hashing algorithm was designed by David Mazieres
35  * <dm@lcs.mit.edu> and works as follows:
36  *
37  * 1. state := InitState ()
38  * 2. state := ExpandKey (state, salt, password) 3.
39  * REPEAT rounds:
40  *	state := ExpandKey (state, 0, salt)
41  *      state := ExpandKey(state, 0, password)
42  * 4. ctext := "OrpheanBeholderScryDoubt"
43  * 5. REPEAT 64:
44  * 	ctext := Encrypt_ECB (state, ctext);
45  * 6. RETURN Concatenate (salt, ctext);
46  *
47  */
48 #include <sys/cdefs.h>
49 __RCSID("$NetBSD: bcrypt.c,v 1.15 2011/12/28 03:12:38 christos Exp $");
50 
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <sys/types.h>
54 #include <string.h>
55 #include <pwd.h>
56 #include <errno.h>
57 #include <limits.h>
58 
59 #include "crypt.h"
60 #include "blowfish.c"
61 
62 /* This implementation is adaptable to current computing power.
63  * You can have up to 2^31 rounds which should be enough for some
64  * time to come.
65  */
66 
67 #define BCRYPT_VERSION '2'
68 #define BCRYPT_MAXSALT 16	/* Precomputation is just so nice */
69 #define BCRYPT_MAXSALTLEN 	(7 + (BCRYPT_MAXSALT * 4 + 2) / 3 + 1)
70 #define BCRYPT_BLOCKS 6		/* Ciphertext blocks */
71 #define BCRYPT_MINROUNDS 16	/* we have log2(rounds) in salt */
72 
73 static void encode_salt(char *, u_int8_t *, u_int16_t, u_int8_t);
74 static void encode_base64(u_int8_t *, u_int8_t *, u_int16_t);
75 static void decode_base64(u_int8_t *, u_int16_t, const u_int8_t *);
76 
77 char *__bcrypt(const char *, const char *);	/* XXX */
78 
79 static char    encrypted[_PASSWORD_LEN];
80 
81 static const u_int8_t Base64Code[] =
82 "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
83 
84 char *bcrypt_gensalt(u_int8_t);
85 
86 static const u_int8_t index_64[128] =
87 {
88 	255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
89 	255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
90 	255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
91 	255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
92 	255, 255, 255, 255, 255, 255, 0, 1, 54, 55,
93 	56, 57, 58, 59, 60, 61, 62, 63, 255, 255,
94 	255, 255, 255, 255, 255, 2, 3, 4, 5, 6,
95 	7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
96 	17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
97 	255, 255, 255, 255, 255, 255, 28, 29, 30,
98 	31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
99 	41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
100 	51, 52, 53, 255, 255, 255, 255, 255
101 };
102 #define CHAR64(c)  ( (c) > 127 ? 255 : index_64[(c)])
103 
104 static void
105 decode_base64(u_int8_t *buffer, u_int16_t len, const u_int8_t *data)
106 {
107 	u_int8_t *bp = buffer;
108 	const u_int8_t *p = data;
109 	u_int8_t c1, c2, c3, c4;
110 	while (bp < buffer + len) {
111 		c1 = CHAR64(*p);
112 		c2 = CHAR64(*(p + 1));
113 
114 		/* Invalid data */
115 		if (c1 == 255 || c2 == 255)
116 			break;
117 
118 		*bp++ = ((u_int32_t)c1 << 2) | (((u_int32_t)c2 & 0x30) >> 4);
119 		if (bp >= buffer + len)
120 			break;
121 
122 		c3 = CHAR64(*(p + 2));
123 		if (c3 == 255)
124 			break;
125 
126 		*bp++ = (((u_int32_t)c2 & 0x0f) << 4) | (((uint32_t)c3 & 0x3c) >> 2);
127 		if (bp >= buffer + len)
128 			break;
129 
130 		c4 = CHAR64(*(p + 3));
131 		if (c4 == 255)
132 			break;
133 		*bp++ = ((c3 & 0x03) << 6) | c4;
134 
135 		p += 4;
136 	}
137 }
138 
139 static void
140 encode_salt(char *salt, u_int8_t *csalt, u_int16_t clen, u_int8_t logr)
141 {
142 	salt[0] = '$';
143 	salt[1] = BCRYPT_VERSION;
144 	salt[2] = 'a';
145 	salt[3] = '$';
146 
147 	snprintf(salt + 4, 4, "%2.2u$", logr);
148 
149 	encode_base64((u_int8_t *) salt + 7, csalt, clen);
150 }
151 
152 int
153 __gensalt_blowfish(char *salt, size_t saltlen, const char *option)
154 {
155 	size_t i;
156 	u_int32_t seed = 0;
157 	u_int8_t csalt[BCRYPT_MAXSALT];
158 	unsigned long nrounds;
159 	char *ep;
160 
161 	if (saltlen < BCRYPT_MAXSALTLEN) {
162 		errno = ENOSPC;
163 		return -1;
164 	}
165 	if (option == NULL) {
166 		errno = EINVAL;
167 		return -1;
168 	}
169 	nrounds = strtoul(option, &ep, 0);
170 	if (option == ep || *ep) {
171 		errno = EINVAL;
172 		return -1;
173 	}
174 	if (errno == ERANGE && nrounds == ULONG_MAX)
175 		return -1;
176 
177 	if (nrounds < 4)
178 		nrounds = 4;
179 	else if (nrounds > 31)
180 		nrounds = 31;
181 
182 	for (i = 0; i < BCRYPT_MAXSALT; i++) {
183 		if (i % 4 == 0)
184 			seed = arc4random();
185 		csalt[i] = seed & 0xff;
186 		seed = seed >> 8;
187 	}
188 	encode_salt(salt, csalt, BCRYPT_MAXSALT, (u_int8_t)nrounds);
189 	return 0;
190 }
191 
192 /* Generates a salt for this version of crypt.
193    Since versions may change. Keeping this here
194    seems sensible.
195    XXX: compat.
196  */
197 char *
198 bcrypt_gensalt(u_int8_t log_rounds)
199 {
200 	static char gsalt[BCRYPT_MAXSALTLEN];
201 	char num[10];
202 
203 	(void)snprintf(num, sizeof(num), "%d", log_rounds);
204 	if (__gensalt_blowfish(gsalt, sizeof(gsalt), num) == -1)
205 		return NULL;
206 	return gsalt;
207 }
208 
209 /* We handle $Vers$log2(NumRounds)$salt+passwd$
210    i.e. $2$04$iwouldntknowwhattosayetKdJ6iFtacBqJdKe6aW7ou */
211 
212 char   *
213 __bcrypt(key, salt)
214 	const char   *key;
215 	const char   *salt;
216 {
217 	blf_ctx state;
218 	u_int32_t rounds, i, k;
219 	u_int16_t j;
220 	u_int8_t key_len, salt_len, logr, minor;
221 	u_int8_t ciphertext[4 * BCRYPT_BLOCKS] = "OrpheanBeholderScryDoubt";
222 	u_int8_t csalt[BCRYPT_MAXSALT];
223 	u_int32_t cdata[BCRYPT_BLOCKS];
224 	int n;
225 	size_t len;
226 
227 	/* Discard "$" identifier */
228 	salt++;
229 
230 	if (*salt > BCRYPT_VERSION)
231 		return NULL;
232 
233 	/* Check for minor versions */
234 	if (salt[1] != '$') {
235 		switch (salt[1]) {
236 		case 'a':
237 			/* 'ab' should not yield the same as 'abab' */
238 			minor = salt[1];
239 			salt++;
240 			break;
241 		default:
242 			return NULL;
243 		}
244 	} else
245 		 minor = 0;
246 
247 	/* Discard version + "$" identifier */
248 	salt += 2;
249 
250 	if (salt[2] != '$')
251 		/* Out of sync with passwd entry */
252 		return NULL;
253 
254 	/* Computer power doesn't increase linear, 2^x should be fine */
255 	n = atoi(salt);
256 	if (n > 31 || n < 0)
257 		return NULL;
258 	logr = (u_int8_t)n;
259 	if ((rounds = (u_int32_t) 1 << logr) < BCRYPT_MINROUNDS)
260 		return NULL;
261 
262 	/* Discard num rounds + "$" identifier */
263 	salt += 3;
264 
265 	if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT)
266 		return NULL;
267 
268 	/* We dont want the base64 salt but the raw data */
269 	decode_base64(csalt, BCRYPT_MAXSALT, (const u_int8_t *)salt);
270 	salt_len = BCRYPT_MAXSALT;
271 	len = strlen(key);
272 	if (len > 72)
273 		key_len = 72;
274 	else
275 		key_len = (uint8_t)len;
276 	key_len += minor >= 'a' ? 1 : 0;
277 
278 	/* Setting up S-Boxes and Subkeys */
279 	Blowfish_initstate(&state);
280 	Blowfish_expandstate(&state, csalt, salt_len,
281 	    (const u_int8_t *) key, key_len);
282 	for (k = 0; k < rounds; k++) {
283 		Blowfish_expand0state(&state, (const u_int8_t *) key, key_len);
284 		Blowfish_expand0state(&state, csalt, salt_len);
285 	}
286 
287 	/* This can be precomputed later */
288 	j = 0;
289 	for (i = 0; i < BCRYPT_BLOCKS; i++)
290 		cdata[i] = Blowfish_stream2word(ciphertext, 4 * BCRYPT_BLOCKS, &j);
291 
292 	/* Now do the encryption */
293 	for (k = 0; k < 64; k++)
294 		blf_enc(&state, cdata, BCRYPT_BLOCKS / 2);
295 
296 	for (i = 0; i < BCRYPT_BLOCKS; i++) {
297 		ciphertext[4 * i + 3] = cdata[i] & 0xff;
298 		cdata[i] = cdata[i] >> 8;
299 		ciphertext[4 * i + 2] = cdata[i] & 0xff;
300 		cdata[i] = cdata[i] >> 8;
301 		ciphertext[4 * i + 1] = cdata[i] & 0xff;
302 		cdata[i] = cdata[i] >> 8;
303 		ciphertext[4 * i + 0] = cdata[i] & 0xff;
304 	}
305 
306 
307 	i = 0;
308 	encrypted[i++] = '$';
309 	encrypted[i++] = BCRYPT_VERSION;
310 	if (minor)
311 		encrypted[i++] = minor;
312 	encrypted[i++] = '$';
313 
314 	snprintf(encrypted + i, 4, "%2.2u$", logr);
315 
316 	encode_base64((u_int8_t *) encrypted + i + 3, csalt, BCRYPT_MAXSALT);
317 	encode_base64((u_int8_t *) encrypted + strlen(encrypted), ciphertext,
318 	    4 * BCRYPT_BLOCKS - 1);
319 	memset(&state, 0, sizeof(state));
320 	return encrypted;
321 }
322 
323 static void
324 encode_base64(u_int8_t *buffer, u_int8_t *data, u_int16_t len)
325 {
326 	u_int8_t *bp = buffer;
327 	u_int8_t *p = data;
328 	u_int8_t c1, c2;
329 	while (p < data + len) {
330 		c1 = *p++;
331 		*bp++ = Base64Code[((u_int32_t)c1 >> 2)];
332 		c1 = (c1 & 0x03) << 4;
333 		if (p >= data + len) {
334 			*bp++ = Base64Code[c1];
335 			break;
336 		}
337 		c2 = *p++;
338 		c1 |= ((u_int32_t)c2 >> 4) & 0x0f;
339 		*bp++ = Base64Code[c1];
340 		c1 = (c2 & 0x0f) << 2;
341 		if (p >= data + len) {
342 			*bp++ = Base64Code[c1];
343 			break;
344 		}
345 		c2 = *p++;
346 		c1 |= ((u_int32_t)c2 >> 6) & 0x03;
347 		*bp++ = Base64Code[c1];
348 		*bp++ = Base64Code[c2 & 0x3f];
349 	}
350 	*bp = '\0';
351 }
352 #if 0
353 void
354 main()
355 {
356 	char    blubber[73];
357 	char    salt[100];
358 	char   *p;
359 	salt[0] = '$';
360 	salt[1] = BCRYPT_VERSION;
361 	salt[2] = '$';
362 
363 	snprintf(salt + 3, 4, "%2.2u$", 5);
364 
365 	printf("24 bytes of salt: ");
366 	fgets(salt + 6, 94, stdin);
367 	salt[99] = 0;
368 	printf("72 bytes of password: ");
369 	fpurge(stdin);
370 	fgets(blubber, 73, stdin);
371 	blubber[72] = 0;
372 
373 	p = crypt(blubber, salt);
374 	printf("Passwd entry: %s\n\n", p);
375 
376 	p = bcrypt_gensalt(5);
377 	printf("Generated salt: %s\n", p);
378 	p = crypt(blubber, p);
379 	printf("Passwd entry: %s\n", p);
380 }
381 #endif
382