xref: /netbsd-src/lib/libcrypt/bcrypt.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: bcrypt.c,v 1.3 2003/08/06 08:34:32 jdolecek 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 
49 #if 0
50 #include <stdio.h>
51 #endif
52 
53 #include <sys/cdefs.h>
54 __RCSID("$NetBSD: bcrypt.c,v 1.3 2003/08/06 08:34:32 jdolecek Exp $");
55 
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <sys/types.h>
59 #include <string.h>
60 #include <pwd.h>
61 
62 #include "blowfish.c"
63 
64 /* This implementation is adaptable to current computing power.
65  * You can have up to 2^31 rounds which should be enough for some
66  * time to come.
67  */
68 
69 #define BCRYPT_VERSION '2'
70 #define BCRYPT_MAXSALT 16	/* Precomputation is just so nice */
71 #define BCRYPT_BLOCKS 6		/* Ciphertext blocks */
72 #define BCRYPT_MINROUNDS 16	/* we have log2(rounds) in salt */
73 
74 static void encode_salt(char *, u_int8_t *, u_int16_t, u_int8_t);
75 static void encode_base64(u_int8_t *, u_int8_t *, u_int16_t);
76 static void decode_base64(u_int8_t *, u_int16_t, u_int8_t *);
77 
78 char *__bcrypt(const char *, const char *);	/* XXX */
79 
80 static char    encrypted[_PASSWORD_LEN];
81 static char    gsalt[BCRYPT_MAXSALT * 4 / 3 + 1];
82 static char    error[] = ":";
83 
84 const static u_int8_t Base64Code[] =
85 "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
86 
87 const static u_int8_t index_64[128] =
88 {
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, 255, 255, 255, 255,
93 	255, 255, 255, 255, 255, 255, 0, 1, 54, 55,
94 	56, 57, 58, 59, 60, 61, 62, 63, 255, 255,
95 	255, 255, 255, 255, 255, 2, 3, 4, 5, 6,
96 	7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
97 	17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
98 	255, 255, 255, 255, 255, 255, 28, 29, 30,
99 	31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
100 	41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
101 	51, 52, 53, 255, 255, 255, 255, 255
102 };
103 #define CHAR64(c)  ( (c) > 127 ? 255 : index_64[(c)])
104 
105 static void
106 decode_base64(u_int8_t *buffer, u_int16_t len, u_int8_t *data)
107 {
108 	u_int8_t *bp = buffer;
109 	u_int8_t *p = data;
110 	u_int8_t c1, c2, c3, c4;
111 	while (bp < buffer + len) {
112 		c1 = CHAR64(*p);
113 		c2 = CHAR64(*(p + 1));
114 
115 		/* Invalid data */
116 		if (c1 == 255 || c2 == 255)
117 			break;
118 
119 		*bp++ = (c1 << 2) | ((c2 & 0x30) >> 4);
120 		if (bp >= buffer + len)
121 			break;
122 
123 		c3 = CHAR64(*(p + 2));
124 		if (c3 == 255)
125 			break;
126 
127 		*bp++ = ((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2);
128 		if (bp >= buffer + len)
129 			break;
130 
131 		c4 = CHAR64(*(p + 3));
132 		if (c4 == 255)
133 			break;
134 		*bp++ = ((c3 & 0x03) << 6) | c4;
135 
136 		p += 4;
137 	}
138 }
139 
140 static void
141 encode_salt(char *salt, u_int8_t *csalt, u_int16_t clen, u_int8_t logr)
142 {
143 	salt[0] = '$';
144 	salt[1] = BCRYPT_VERSION;
145 	salt[2] = 'a';
146 	salt[3] = '$';
147 
148 	snprintf(salt + 4, 4, "%2.2u$", logr);
149 
150 	encode_base64((u_int8_t *) salt + 7, csalt, clen);
151 }
152 
153 /* Generates a salt for this version of crypt.
154    Since versions may change. Keeping this here
155    seems sensible.
156  */
157 char *
158 bcrypt_gensalt(u_int8_t log_rounds)
159 {
160 	u_int8_t csalt[BCRYPT_MAXSALT];
161 	u_int16_t i;
162 	u_int32_t seed = 0;
163 
164 	for (i = 0; i < BCRYPT_MAXSALT; i++) {
165 		if (i % 4 == 0)
166 			seed = arc4random();
167 		csalt[i] = seed & 0xff;
168 		seed = seed >> 8;
169 	}
170 
171 	if (log_rounds < 4)
172 		log_rounds = 4;
173 
174 	encode_salt(gsalt, csalt, BCRYPT_MAXSALT, log_rounds);
175 	return gsalt;
176 }
177 
178 /* We handle $Vers$log2(NumRounds)$salt+passwd$
179    i.e. $2$04$iwouldntknowwhattosayetKdJ6iFtacBqJdKe6aW7ou */
180 
181 char   *
182 __bcrypt(key, salt)
183 	const char   *key;
184 	const char   *salt;
185 {
186 	blf_ctx state;
187 	u_int32_t rounds, i, k;
188 	u_int16_t j;
189 	u_int8_t key_len, salt_len, logr, minor;
190 	u_int8_t ciphertext[4 * BCRYPT_BLOCKS] = "OrpheanBeholderScryDoubt";
191 	u_int8_t csalt[BCRYPT_MAXSALT];
192 	u_int32_t cdata[BCRYPT_BLOCKS];
193 
194 	/* Discard "$" identifier */
195 	salt++;
196 
197 	if (*salt > BCRYPT_VERSION) {
198 		/* How do I handle errors ? Return ':' */
199 		return error;
200 	}
201 
202 	/* Check for minor versions */
203 	if (salt[1] != '$') {
204 		 switch (salt[1]) {
205 		 case 'a':
206 			 /* 'ab' should not yield the same as 'abab' */
207 			 minor = salt[1];
208 			 salt++;
209 			 break;
210 		 default:
211 			 return error;
212 		 }
213 	} else
214 		 minor = 0;
215 
216 	/* Discard version + "$" identifier */
217 	salt += 2;
218 
219 	if (salt[2] != '$')
220 		/* Out of sync with passwd entry */
221 		return error;
222 
223 	/* Computer power doesn't increase linear, 2^x should be fine */
224 	if ((rounds = (u_int32_t) 1 << (logr = atoi(salt))) < BCRYPT_MINROUNDS)
225 		return error;
226 
227 	/* Discard num rounds + "$" identifier */
228 	salt += 3;
229 
230 	if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT)
231 		return error;
232 
233 	/* We dont want the base64 salt but the raw data */
234 	decode_base64(csalt, BCRYPT_MAXSALT, (u_int8_t *) salt);
235 	salt_len = BCRYPT_MAXSALT;
236 	key_len = strlen(key) + (minor >= 'a' ? 1 : 0);
237 
238 	/* Setting up S-Boxes and Subkeys */
239 	Blowfish_initstate(&state);
240 	Blowfish_expandstate(&state, csalt, salt_len,
241 	    (u_int8_t *) key, key_len);
242 	for (k = 0; k < rounds; k++) {
243 		Blowfish_expand0state(&state, (u_int8_t *) key, key_len);
244 		Blowfish_expand0state(&state, csalt, salt_len);
245 	}
246 
247 	/* This can be precomputed later */
248 	j = 0;
249 	for (i = 0; i < BCRYPT_BLOCKS; i++)
250 		cdata[i] = Blowfish_stream2word(ciphertext, 4 * BCRYPT_BLOCKS, &j);
251 
252 	/* Now do the encryption */
253 	for (k = 0; k < 64; k++)
254 		blf_enc(&state, cdata, BCRYPT_BLOCKS / 2);
255 
256 	for (i = 0; i < BCRYPT_BLOCKS; i++) {
257 		ciphertext[4 * i + 3] = cdata[i] & 0xff;
258 		cdata[i] = cdata[i] >> 8;
259 		ciphertext[4 * i + 2] = cdata[i] & 0xff;
260 		cdata[i] = cdata[i] >> 8;
261 		ciphertext[4 * i + 1] = cdata[i] & 0xff;
262 		cdata[i] = cdata[i] >> 8;
263 		ciphertext[4 * i + 0] = cdata[i] & 0xff;
264 	}
265 
266 
267 	i = 0;
268 	encrypted[i++] = '$';
269 	encrypted[i++] = BCRYPT_VERSION;
270 	if (minor)
271 		encrypted[i++] = minor;
272 	encrypted[i++] = '$';
273 
274 	snprintf(encrypted + i, 4, "%2.2u$", logr);
275 
276 	encode_base64((u_int8_t *) encrypted + i + 3, csalt, BCRYPT_MAXSALT);
277 	encode_base64((u_int8_t *) encrypted + strlen(encrypted), ciphertext,
278 	    4 * BCRYPT_BLOCKS - 1);
279 	return encrypted;
280 }
281 
282 static void
283 encode_base64(u_int8_t *buffer, u_int8_t *data, u_int16_t len)
284 {
285 	u_int8_t *bp = buffer;
286 	u_int8_t *p = data;
287 	u_int8_t c1, c2;
288 	while (p < data + len) {
289 		c1 = *p++;
290 		*bp++ = Base64Code[(c1 >> 2)];
291 		c1 = (c1 & 0x03) << 4;
292 		if (p >= data + len) {
293 			*bp++ = Base64Code[c1];
294 			break;
295 		}
296 		c2 = *p++;
297 		c1 |= (c2 >> 4) & 0x0f;
298 		*bp++ = Base64Code[c1];
299 		c1 = (c2 & 0x0f) << 2;
300 		if (p >= data + len) {
301 			*bp++ = Base64Code[c1];
302 			break;
303 		}
304 		c2 = *p++;
305 		c1 |= (c2 >> 6) & 0x03;
306 		*bp++ = Base64Code[c1];
307 		*bp++ = Base64Code[c2 & 0x3f];
308 	}
309 	*bp = '\0';
310 }
311 #if 0
312 void
313 main()
314 {
315 	char    blubber[73];
316 	char    salt[100];
317 	char   *p;
318 	salt[0] = '$';
319 	salt[1] = BCRYPT_VERSION;
320 	salt[2] = '$';
321 
322 	snprintf(salt + 3, 4, "%2.2u$", 5);
323 
324 	printf("24 bytes of salt: ");
325 	fgets(salt + 6, 94, stdin);
326 	salt[99] = 0;
327 	printf("72 bytes of password: ");
328 	fpurge(stdin);
329 	fgets(blubber, 73, stdin);
330 	blubber[72] = 0;
331 
332 	p = crypt(blubber, salt);
333 	printf("Passwd entry: %s\n\n", p);
334 
335 	p = bcrypt_gensalt(5);
336 	printf("Generated salt: %s\n", p);
337 	p = crypt(blubber, p);
338 	printf("Passwd entry: %s\n", p);
339 }
340 #endif
341