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