drm/linux: Add list_for_each_entry_safe_reverse()
[dragonfly.git] / lib / libcrypt / crypt-blowfish.c
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  * $FreeBSD: src/secure/lib/libcrypt/crypt-blowfish.c,v 1.1.2.1 2001/05/24 12:20:03 markm Exp $
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 /*
49  * FreeBSD implementation by Paul Herman <pherman@frenchfries.net>
50  */
51
52 #if 0
53 #include <stdio.h>
54 #endif
55
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <sys/types.h>
59 #include <string.h>
60 #include <pwd.h>
61 #include "blowfish.h"
62 #include "crypt.h"
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 char   *bcrypt_gensalt (u_int8_t);
75
76 static void encode_salt (char *, u_int8_t *, u_int16_t, u_int8_t);
77 static void encode_base64 (u_int8_t *, u_int8_t *, u_int16_t);
78 static void decode_base64 (u_int8_t *, u_int16_t, u_int8_t *);
79
80 static char    encrypted[_PASSWORD_LEN];
81 static char    gsalt[BCRYPT_MAXSALT * 4 / 3 + 1];
82
83 static const u_int8_t Base64Code[] =
84 "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
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, u_int8_t *data)
106 {
107         u_int8_t *bp = buffer;
108         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++ = (c1 << 2) | ((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++ = ((c2 & 0x0f) << 4) | ((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 /* Generates a salt for this version of crypt.
152    Since versions may change. Keeping this here
153    seems sensible.
154  */
155
156 char *
157 bcrypt_gensalt(u_int8_t log_rounds)
158 {
159         u_int8_t csalt[BCRYPT_MAXSALT];
160         u_int16_t i;
161         u_int32_t seed = 0;
162
163         for (i = 0; i < BCRYPT_MAXSALT; i++) {
164                 if (i % 4 == 0)
165                         seed = arc4random();
166                 csalt[i] = seed & 0xff;
167                 seed = seed >> 8;
168         }
169
170         if (log_rounds < 4)
171                 log_rounds = 4;
172
173         encode_salt(gsalt, csalt, BCRYPT_MAXSALT, log_rounds);
174         return gsalt;
175 }
176 /* We handle $Vers$log2(NumRounds)$salt+passwd$
177    i.e. $2$04$iwouldntknowwhattosayetKdJ6iFtacBqJdKe6aW7ou */
178
179 char   *
180 crypt_blowfish(const char *key, const char *salt)
181 {
182         blf_ctx state;
183         u_int32_t rounds, i, k;
184         u_int16_t j;
185         u_int8_t key_len, salt_len, logr, minor;
186         u_int8_t ciphertext[4 * BCRYPT_BLOCKS] = "OrpheanBeholderScryDoubt";
187         u_int8_t csalt[BCRYPT_MAXSALT];
188         u_int32_t cdata[BCRYPT_BLOCKS];
189         static const char *magic = "$2a$04$";
190
191                 /* Defaults */
192         minor = 'a';
193         logr = 4;
194         rounds = 1 << logr;
195
196         /* If it starts with the magic string, then skip that */
197         if(!strncmp(salt, magic, strlen(magic))) {
198                 salt += strlen(magic);
199         }
200         else if (*salt == '$') {
201
202                 /* Discard "$" identifier */
203                 salt++;
204
205                 if (*salt > BCRYPT_VERSION) {
206                         /* How do I handle errors ? Return NULL according to
207                            crypt(3) */
208                         return NULL;
209                 }
210
211                 /* Check for minor versions */
212                 if (salt[1] != '$') {
213                          switch (salt[1]) {
214                          case 'a':
215                                  /* 'ab' should not yield the same as 'abab' */
216                                  minor = salt[1];
217                                  salt++;
218                                  break;
219                          default:
220                                  return NULL;
221                          }
222                 } else
223                          minor = 0;
224
225                 /* Discard version + "$" identifier */
226                 salt += 2;
227
228                 if (salt[2] != '$')
229                         /* Out of sync with passwd entry */
230                         return NULL;
231
232                 /* Computer power doesnt increase linear, 2^x should be fine */
233                 if ((rounds = (u_int32_t) 1 << (logr = atoi(salt))) < BCRYPT_MINROUNDS)
234                         return NULL;
235
236                 /* Discard num rounds + "$" identifier */
237                 salt += 3;
238         }
239
240
241         /* We dont want the base64 salt but the raw data */
242         decode_base64(csalt, BCRYPT_MAXSALT, (u_int8_t *) salt);
243         salt_len = BCRYPT_MAXSALT;
244         key_len = strlen(key) + (minor >= 'a' ? 1 : 0);
245
246         /* Setting up S-Boxes and Subkeys */
247         Blowfish_initstate(&state);
248         Blowfish_expandstate(&state, csalt, salt_len,
249             (u_int8_t *) key, key_len);
250         for (k = 0; k < rounds; k++) {
251                 Blowfish_expand0state(&state, (u_int8_t *) key, key_len);
252                 Blowfish_expand0state(&state, csalt, salt_len);
253         }
254
255         /* This can be precomputed later */
256         j = 0;
257         for (i = 0; i < BCRYPT_BLOCKS; i++)
258                 cdata[i] = Blowfish_stream2word(ciphertext, 4 * BCRYPT_BLOCKS, &j);
259
260         /* Now do the encryption */
261         for (k = 0; k < 64; k++)
262                 blf_enc(&state, cdata, BCRYPT_BLOCKS / 2);
263
264         for (i = 0; i < BCRYPT_BLOCKS; i++) {
265                 ciphertext[4 * i + 3] = cdata[i] & 0xff;
266                 cdata[i] = cdata[i] >> 8;
267                 ciphertext[4 * i + 2] = cdata[i] & 0xff;
268                 cdata[i] = cdata[i] >> 8;
269                 ciphertext[4 * i + 1] = cdata[i] & 0xff;
270                 cdata[i] = cdata[i] >> 8;
271                 ciphertext[4 * i + 0] = cdata[i] & 0xff;
272         }
273
274
275         i = 0;
276         encrypted[i++] = '$';
277         encrypted[i++] = BCRYPT_VERSION;
278         if (minor)
279                 encrypted[i++] = minor;
280         encrypted[i++] = '$';
281
282         snprintf(encrypted + i, 4, "%2.2u$", logr);
283
284         encode_base64((u_int8_t *) encrypted + i + 3, csalt, BCRYPT_MAXSALT);
285         encode_base64((u_int8_t *) encrypted + strlen(encrypted), ciphertext,
286             4 * BCRYPT_BLOCKS - 1);
287         return encrypted;
288 }
289
290 static void
291 encode_base64(u_int8_t *buffer, u_int8_t *data, u_int16_t len)
292 {
293         u_int8_t *bp = buffer;
294         u_int8_t *p = data;
295         u_int8_t c1, c2;
296         while (p < data + len) {
297                 c1 = *p++;
298                 *bp++ = Base64Code[(c1 >> 2)];
299                 c1 = (c1 & 0x03) << 4;
300                 if (p >= data + len) {
301                         *bp++ = Base64Code[c1];
302                         break;
303                 }
304                 c2 = *p++;
305                 c1 |= (c2 >> 4) & 0x0f;
306                 *bp++ = Base64Code[c1];
307                 c1 = (c2 & 0x0f) << 2;
308                 if (p >= data + len) {
309                         *bp++ = Base64Code[c1];
310                         break;
311                 }
312                 c2 = *p++;
313                 c1 |= (c2 >> 6) & 0x03;
314                 *bp++ = Base64Code[c1];
315                 *bp++ = Base64Code[c2 & 0x3f];
316         }
317         *bp = '\0';
318 }
319 #if 0
320 void
321 main()
322 {
323         char    blubber[73];
324         char    salt[100];
325         char   *p;
326         salt[0] = '$';
327         salt[1] = BCRYPT_VERSION;
328         salt[2] = '$';
329
330         snprintf(salt + 3, 4, "%2.2u$", 5);
331
332         printf("24 bytes of salt: ");
333         fgets(salt + 6, 94, stdin);
334         salt[99] = 0;
335         printf("72 bytes of password: ");
336         fpurge(stdin);
337         fgets(blubber, 73, stdin);
338         blubber[72] = 0;
339
340         p = crypt(blubber, salt);
341         printf("Passwd entry: %s\n\n", p);
342
343         p = bcrypt_gensalt(5);
344         printf("Generated salt: %s\n", p);
345         p = crypt(blubber, p);
346         printf("Passwd entry: %s\n", p);
347 }
348 #endif