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