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