chiark / gitweb /
libuv: Update from 1.20.0 to 1.20.1
[termux-packages] / packages / libcrypt / crypt3.c
1 /**************************************************************************
2 * Implementation of crypt(3) using routines in libcrypto from openssl for
3 * use on Android in Termux.
4 *
5 *  https://www.freebsd.org/cgi/man.cgi?crypt(3)
6 *  http://man7.org/linux/man-pages/man3/crypt.3.html
7 *
8 * Relevant code is from FreeBSD with license given below.
9 **************************************************************************/
10
11 /*
12  * Copyright (c) 2011 The FreeBSD Project. All rights reserved.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35
36 #include <arpa/inet.h>
37 #include <errno.h>
38 #include <stdint.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <stdbool.h>
43 #include <openssl/sha.h>
44 #include <openssl/md5.h>
45
46 /* START: Freebsd compat */
47 typedef unsigned long u_long;
48 #define MIN(a,b) (((a)<(b))?(a):(b))
49 #define MAX(a,b) (((a)>(b))?(a):(b))
50 #define MD5_SIZE 16
51 #define _PASSWORD_EFMT1         '_'
52 #define DES_SALT_ALPHABET \
53         "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
54 #define MD5Init MD5_Init
55 #define MD5Update MD5_Update
56 #define MD5Final MD5_Final
57 /* END: Freebsd compat */
58
59
60 /* START: https://github.com/freebsd/freebsd/blob/master/lib/libcrypt/misc.c */
61 static char itoa64[] =          /* 0 ... 63 => ascii - 64 */
62         "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
63
64 void
65 _crypt_to64(char *s, u_long v, int n)
66 {
67         while (--n >= 0) {
68                 *s++ = itoa64[v&0x3f];
69                 v >>= 6;
70         }
71 }
72
73 void
74 b64_from_24bit(uint8_t B2, uint8_t B1, uint8_t B0, int n, int *buflen, char **cp)
75 {
76         uint32_t w;
77         int i;
78
79         w = (B2 << 16) | (B1 << 8) | B0;
80         for (i = 0; i < n; i++) {
81                 **cp = itoa64[w&0x3f];
82                 (*cp)++;
83                 if ((*buflen)-- < 0)
84                         break;
85                 w >>= 6;
86         }
87 }
88 /* END: https://github.com/freebsd/freebsd/blob/master/lib/libcrypt/misc.c */
89
90
91 /* START: https://github.com/freebsd/freebsd/blob/master/secure/lib/libcrypt/crypt-des.c */
92 #if     defined(__GNUC__) && !defined(lint)
93 #define INLINE inline
94 #else
95 #define INLINE
96 #endif
97
98 static u_char   IP[64] = {
99         58, 50, 42, 34, 26, 18, 10,  2, 60, 52, 44, 36, 28, 20, 12,  4,
100         62, 54, 46, 38, 30, 22, 14,  6, 64, 56, 48, 40, 32, 24, 16,  8,
101         57, 49, 41, 33, 25, 17,  9,  1, 59, 51, 43, 35, 27, 19, 11,  3,
102         61, 53, 45, 37, 29, 21, 13,  5, 63, 55, 47, 39, 31, 23, 15,  7
103 };
104
105 static u_char   inv_key_perm[64];
106 static u_char   key_perm[56] = {
107         57, 49, 41, 33, 25, 17,  9,  1, 58, 50, 42, 34, 26, 18,
108         10,  2, 59, 51, 43, 35, 27, 19, 11,  3, 60, 52, 44, 36,
109         63, 55, 47, 39, 31, 23, 15,  7, 62, 54, 46, 38, 30, 22,
110         14,  6, 61, 53, 45, 37, 29, 21, 13,  5, 28, 20, 12,  4
111 };
112
113 static u_char   key_shifts[16] = {
114         1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
115 };
116
117 static u_char   inv_comp_perm[56];
118 static u_char   comp_perm[48] = {
119         14, 17, 11, 24,  1,  5,  3, 28, 15,  6, 21, 10,
120         23, 19, 12,  4, 26,  8, 16,  7, 27, 20, 13,  2,
121         41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48,
122         44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32
123 };
124
125 /*
126  *      No E box is used, as it's replaced by some ANDs, shifts, and ORs.
127  */
128
129 static u_char   u_sbox[8][64];
130 static u_char   sbox[8][64] = {
131         {
132                 14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7,
133                  0, 15,  7,  4, 14,  2, 13,  1, 10,  6, 12, 11,  9,  5,  3,  8,
134                  4,  1, 14,  8, 13,  6,  2, 11, 15, 12,  9,  7,  3, 10,  5,  0,
135                 15, 12,  8,  2,  4,  9,  1,  7,  5, 11,  3, 14, 10,  0,  6, 13
136         },
137         {
138                 15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10,
139                  3, 13,  4,  7, 15,  2,  8, 14, 12,  0,  1, 10,  6,  9, 11,  5,
140                  0, 14,  7, 11, 10,  4, 13,  1,  5,  8, 12,  6,  9,  3,  2, 15,
141                 13,  8, 10,  1,  3, 15,  4,  2, 11,  6,  7, 12,  0,  5, 14,  9
142         },
143         {
144                 10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8,
145                 13,  7,  0,  9,  3,  4,  6, 10,  2,  8,  5, 14, 12, 11, 15,  1,
146                 13,  6,  4,  9,  8, 15,  3,  0, 11,  1,  2, 12,  5, 10, 14,  7,
147                  1, 10, 13,  0,  6,  9,  8,  7,  4, 15, 14,  3, 11,  5,  2, 12
148         },
149         {
150                  7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15,
151                 13,  8, 11,  5,  6, 15,  0,  3,  4,  7,  2, 12,  1, 10, 14,  9,
152                 10,  6,  9,  0, 12, 11,  7, 13, 15,  1,  3, 14,  5,  2,  8,  4,
153                  3, 15,  0,  6, 10,  1, 13,  8,  9,  4,  5, 11, 12,  7,  2, 14
154         },
155         {
156                  2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9,
157                 14, 11,  2, 12,  4,  7, 13,  1,  5,  0, 15, 10,  3,  9,  8,  6,
158                  4,  2,  1, 11, 10, 13,  7,  8, 15,  9, 12,  5,  6,  3,  0, 14,
159                 11,  8, 12,  7,  1, 14,  2, 13,  6, 15,  0,  9, 10,  4,  5,  3
160         },
161         {
162                 12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11,
163                 10, 15,  4,  2,  7, 12,  9,  5,  6,  1, 13, 14,  0, 11,  3,  8,
164                  9, 14, 15,  5,  2,  8, 12,  3,  7,  0,  4, 10,  1, 13, 11,  6,
165                  4,  3,  2, 12,  9,  5, 15, 10, 11, 14,  1,  7,  6,  0,  8, 13
166         },
167         {
168                  4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1,
169                 13,  0, 11,  7,  4,  9,  1, 10, 14,  3,  5, 12,  2, 15,  8,  6,
170                  1,  4, 11, 13, 12,  3,  7, 14, 10, 15,  6,  8,  0,  5,  9,  2,
171                  6, 11, 13,  8,  1,  4, 10,  7,  9,  5,  0, 15, 14,  2,  3, 12
172         },
173         {
174                 13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7,
175                  1, 15, 13,  8, 10,  3,  7,  4, 12,  5,  6, 11,  0, 14,  9,  2,
176                  7, 11,  4,  1,  9, 12, 14,  2,  0,  6, 10, 13, 15,  3,  5,  8,
177                  2,  1, 14,  7,  4, 10,  8, 13, 15, 12,  9,  0,  3,  5,  6, 11
178         }
179 };
180
181 static u_char   un_pbox[32];
182 static u_char   pbox[32] = {
183         16,  7, 20, 21, 29, 12, 28, 17,  1, 15, 23, 26,  5, 18, 31, 10,
184          2,  8, 24, 14, 32, 27,  3,  9, 19, 13, 30,  6, 22, 11,  4, 25
185 };
186
187 static u_int32_t        bits32[32] =
188 {
189         0x80000000, 0x40000000, 0x20000000, 0x10000000,
190         0x08000000, 0x04000000, 0x02000000, 0x01000000,
191         0x00800000, 0x00400000, 0x00200000, 0x00100000,
192         0x00080000, 0x00040000, 0x00020000, 0x00010000,
193         0x00008000, 0x00004000, 0x00002000, 0x00001000,
194         0x00000800, 0x00000400, 0x00000200, 0x00000100,
195         0x00000080, 0x00000040, 0x00000020, 0x00000010,
196         0x00000008, 0x00000004, 0x00000002, 0x00000001
197 };
198
199 static u_char   bits8[8] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
200
201 static u_int32_t        saltbits;
202 static u_int32_t        old_salt;
203 static u_int32_t        *bits28, *bits24;
204 static u_char           init_perm[64], final_perm[64];
205 static u_int32_t        en_keysl[16], en_keysr[16];
206 static u_int32_t        de_keysl[16], de_keysr[16];
207 static int              des_initialised = 0;
208 static u_char           m_sbox[4][4096];
209 static u_int32_t        psbox[4][256];
210 static u_int32_t        ip_maskl[8][256], ip_maskr[8][256];
211 static u_int32_t        fp_maskl[8][256], fp_maskr[8][256];
212 static u_int32_t        key_perm_maskl[8][128], key_perm_maskr[8][128];
213 static u_int32_t        comp_maskl[8][128], comp_maskr[8][128];
214 static u_int32_t        old_rawkey0, old_rawkey1;
215
216 static u_char   ascii64[] =
217          "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
218 /*        0000000000111111111122222222223333333333444444444455555555556666 */
219 /*        0123456789012345678901234567890123456789012345678901234567890123 */
220
221 static INLINE int
222 ascii_to_bin(char ch)
223 {
224         if (ch > 'z')
225                 return(0);
226         if (ch >= 'a')
227                 return(ch - 'a' + 38);
228         if (ch > 'Z')
229                 return(0);
230         if (ch >= 'A')
231                 return(ch - 'A' + 12);
232         if (ch > '9')
233                 return(0);
234         if (ch >= '.')
235                 return(ch - '.');
236         return(0);
237 }
238
239 static void
240 des_init(void)
241 {
242         int     i, j, b, k, inbit, obit;
243         u_int32_t       *p, *il, *ir, *fl, *fr;
244
245         old_rawkey0 = old_rawkey1 = 0L;
246         saltbits = 0L;
247         old_salt = 0L;
248         bits24 = (bits28 = bits32 + 4) + 4;
249
250         /*
251          * Invert the S-boxes, reordering the input bits.
252          */
253         for (i = 0; i < 8; i++)
254                 for (j = 0; j < 64; j++) {
255                         b = (j & 0x20) | ((j & 1) << 4) | ((j >> 1) & 0xf);
256                         u_sbox[i][j] = sbox[i][b];
257                 }
258
259         /*
260          * Convert the inverted S-boxes into 4 arrays of 8 bits.
261          * Each will handle 12 bits of the S-box input.
262          */
263         for (b = 0; b < 4; b++)
264                 for (i = 0; i < 64; i++)
265                         for (j = 0; j < 64; j++)
266                                 m_sbox[b][(i << 6) | j] =
267                                         (u_char)((u_sbox[(b << 1)][i] << 4) |
268                                         u_sbox[(b << 1) + 1][j]);
269
270         /*
271          * Set up the initial & final permutations into a useful form, and
272          * initialise the inverted key permutation.
273          */
274         for (i = 0; i < 64; i++) {
275                 init_perm[final_perm[i] = IP[i] - 1] = (u_char)i;
276                 inv_key_perm[i] = 255;
277         }
278
279         /*
280          * Invert the key permutation and initialise the inverted key
281          * compression permutation.
282          */
283         for (i = 0; i < 56; i++) {
284                 inv_key_perm[key_perm[i] - 1] = (u_char)i;
285                 inv_comp_perm[i] = 255;
286         }
287
288         /*
289          * Invert the key compression permutation.
290          */
291         for (i = 0; i < 48; i++) {
292                 inv_comp_perm[comp_perm[i] - 1] = (u_char)i;
293         }
294
295         /*
296          * Set up the OR-mask arrays for the initial and final permutations,
297          * and for the key initial and compression permutations.
298          */
299         for (k = 0; k < 8; k++) {
300                 for (i = 0; i < 256; i++) {
301                         *(il = &ip_maskl[k][i]) = 0L;
302                         *(ir = &ip_maskr[k][i]) = 0L;
303                         *(fl = &fp_maskl[k][i]) = 0L;
304                         *(fr = &fp_maskr[k][i]) = 0L;
305                         for (j = 0; j < 8; j++) {
306                                 inbit = 8 * k + j;
307                                 if (i & bits8[j]) {
308                                         if ((obit = init_perm[inbit]) < 32)
309                                                 *il |= bits32[obit];
310                                         else
311                                                 *ir |= bits32[obit-32];
312                                         if ((obit = final_perm[inbit]) < 32)
313                                                 *fl |= bits32[obit];
314                                         else
315                                                 *fr |= bits32[obit - 32];
316                                 }
317                         }
318                 }
319                 for (i = 0; i < 128; i++) {
320                         *(il = &key_perm_maskl[k][i]) = 0L;
321                         *(ir = &key_perm_maskr[k][i]) = 0L;
322                         for (j = 0; j < 7; j++) {
323                                 inbit = 8 * k + j;
324                                 if (i & bits8[j + 1]) {
325                                         if ((obit = inv_key_perm[inbit]) == 255)
326                                                 continue;
327                                         if (obit < 28)
328                                                 *il |= bits28[obit];
329                                         else
330                                                 *ir |= bits28[obit - 28];
331                                 }
332                         }
333                         *(il = &comp_maskl[k][i]) = 0L;
334                         *(ir = &comp_maskr[k][i]) = 0L;
335                         for (j = 0; j < 7; j++) {
336                                 inbit = 7 * k + j;
337                                 if (i & bits8[j + 1]) {
338                                         if ((obit=inv_comp_perm[inbit]) == 255)
339                                                 continue;
340                                         if (obit < 24)
341                                                 *il |= bits24[obit];
342                                         else
343                                                 *ir |= bits24[obit - 24];
344                                 }
345                         }
346                 }
347         }
348
349         /*
350          * Invert the P-box permutation, and convert into OR-masks for
351          * handling the output of the S-box arrays setup above.
352          */
353         for (i = 0; i < 32; i++)
354                 un_pbox[pbox[i] - 1] = (u_char)i;
355
356         for (b = 0; b < 4; b++)
357                 for (i = 0; i < 256; i++) {
358                         *(p = &psbox[b][i]) = 0L;
359                         for (j = 0; j < 8; j++) {
360                                 if (i & bits8[j])
361                                         *p |= bits32[un_pbox[8 * b + j]];
362                         }
363                 }
364
365         des_initialised = 1;
366 }
367
368 static void
369 setup_salt(u_int32_t salt)
370 {
371         u_int32_t       obit, saltbit;
372         int             i;
373
374         if (salt == old_salt)
375                 return;
376         old_salt = salt;
377
378         saltbits = 0L;
379         saltbit = 1;
380         obit = 0x800000;
381         for (i = 0; i < 24; i++) {
382                 if (salt & saltbit)
383                         saltbits |= obit;
384                 saltbit <<= 1;
385                 obit >>= 1;
386         }
387 }
388
389 static int
390 des_setkey(const char *key)
391 {
392         u_int32_t       k0, k1, rawkey0, rawkey1;
393         int             shifts, round;
394
395         if (!des_initialised)
396                 des_init();
397
398         rawkey0 = ntohl(*(const u_int32_t *) key);
399         rawkey1 = ntohl(*(const u_int32_t *) (key + 4));
400
401         if ((rawkey0 | rawkey1)
402             && rawkey0 == old_rawkey0
403             && rawkey1 == old_rawkey1) {
404                 /*
405                  * Already setup for this key.
406                  * This optimisation fails on a zero key (which is weak and
407                  * has bad parity anyway) in order to simplify the starting
408                  * conditions.
409                  */
410                 return(0);
411         }
412         old_rawkey0 = rawkey0;
413         old_rawkey1 = rawkey1;
414
415         /*
416          *      Do key permutation and split into two 28-bit subkeys.
417          */
418         k0 = key_perm_maskl[0][rawkey0 >> 25]
419            | key_perm_maskl[1][(rawkey0 >> 17) & 0x7f]
420            | key_perm_maskl[2][(rawkey0 >> 9) & 0x7f]
421            | key_perm_maskl[3][(rawkey0 >> 1) & 0x7f]
422            | key_perm_maskl[4][rawkey1 >> 25]
423            | key_perm_maskl[5][(rawkey1 >> 17) & 0x7f]
424            | key_perm_maskl[6][(rawkey1 >> 9) & 0x7f]
425            | key_perm_maskl[7][(rawkey1 >> 1) & 0x7f];
426         k1 = key_perm_maskr[0][rawkey0 >> 25]
427            | key_perm_maskr[1][(rawkey0 >> 17) & 0x7f]
428            | key_perm_maskr[2][(rawkey0 >> 9) & 0x7f]
429            | key_perm_maskr[3][(rawkey0 >> 1) & 0x7f]
430            | key_perm_maskr[4][rawkey1 >> 25]
431            | key_perm_maskr[5][(rawkey1 >> 17) & 0x7f]
432            | key_perm_maskr[6][(rawkey1 >> 9) & 0x7f]
433            | key_perm_maskr[7][(rawkey1 >> 1) & 0x7f];
434         /*
435          *      Rotate subkeys and do compression permutation.
436          */
437         shifts = 0;
438         for (round = 0; round < 16; round++) {
439                 u_int32_t       t0, t1;
440
441                 shifts += key_shifts[round];
442
443                 t0 = (k0 << shifts) | (k0 >> (28 - shifts));
444                 t1 = (k1 << shifts) | (k1 >> (28 - shifts));
445
446                 de_keysl[15 - round] =
447                 en_keysl[round] = comp_maskl[0][(t0 >> 21) & 0x7f]
448                                 | comp_maskl[1][(t0 >> 14) & 0x7f]
449                                 | comp_maskl[2][(t0 >> 7) & 0x7f]
450                                 | comp_maskl[3][t0 & 0x7f]
451                                 | comp_maskl[4][(t1 >> 21) & 0x7f]
452                                 | comp_maskl[5][(t1 >> 14) & 0x7f]
453                                 | comp_maskl[6][(t1 >> 7) & 0x7f]
454                                 | comp_maskl[7][t1 & 0x7f];
455
456                 de_keysr[15 - round] =
457                 en_keysr[round] = comp_maskr[0][(t0 >> 21) & 0x7f]
458                                 | comp_maskr[1][(t0 >> 14) & 0x7f]
459                                 | comp_maskr[2][(t0 >> 7) & 0x7f]
460                                 | comp_maskr[3][t0 & 0x7f]
461                                 | comp_maskr[4][(t1 >> 21) & 0x7f]
462                                 | comp_maskr[5][(t1 >> 14) & 0x7f]
463                                 | comp_maskr[6][(t1 >> 7) & 0x7f]
464                                 | comp_maskr[7][t1 & 0x7f];
465         }
466         return(0);
467 }
468
469 static int
470 do_des( u_int32_t l_in, u_int32_t r_in, u_int32_t *l_out, u_int32_t *r_out, int count)
471 {
472         /*
473          *      l_in, r_in, l_out, and r_out are in pseudo-"big-endian" format.
474          */
475         u_int32_t       l, r, *kl, *kr, *kl1, *kr1;
476         u_int32_t       f, r48l, r48r;
477         int             round;
478
479         if (count == 0) {
480                 return(1);
481         } else if (count > 0) {
482                 /*
483                  * Encrypting
484                  */
485                 kl1 = en_keysl;
486                 kr1 = en_keysr;
487         } else {
488                 /*
489                  * Decrypting
490                  */
491                 count = -count;
492                 kl1 = de_keysl;
493                 kr1 = de_keysr;
494         }
495
496         /*
497          *      Do initial permutation (IP).
498          */
499         l = ip_maskl[0][l_in >> 24]
500           | ip_maskl[1][(l_in >> 16) & 0xff]
501           | ip_maskl[2][(l_in >> 8) & 0xff]
502           | ip_maskl[3][l_in & 0xff]
503           | ip_maskl[4][r_in >> 24]
504           | ip_maskl[5][(r_in >> 16) & 0xff]
505           | ip_maskl[6][(r_in >> 8) & 0xff]
506           | ip_maskl[7][r_in & 0xff];
507         r = ip_maskr[0][l_in >> 24]
508           | ip_maskr[1][(l_in >> 16) & 0xff]
509           | ip_maskr[2][(l_in >> 8) & 0xff]
510           | ip_maskr[3][l_in & 0xff]
511           | ip_maskr[4][r_in >> 24]
512           | ip_maskr[5][(r_in >> 16) & 0xff]
513           | ip_maskr[6][(r_in >> 8) & 0xff]
514           | ip_maskr[7][r_in & 0xff];
515
516         while (count--) {
517                 /*
518                  * Do each round.
519                  */
520                 kl = kl1;
521                 kr = kr1;
522                 round = 16;
523                 while (round--) {
524                         /*
525                          * Expand R to 48 bits (simulate the E-box).
526                          */
527                         r48l    = ((r & 0x00000001) << 23)
528                                 | ((r & 0xf8000000) >> 9)
529                                 | ((r & 0x1f800000) >> 11)
530                                 | ((r & 0x01f80000) >> 13)
531                                 | ((r & 0x001f8000) >> 15);
532
533                         r48r    = ((r & 0x0001f800) << 7)
534                                 | ((r & 0x00001f80) << 5)
535                                 | ((r & 0x000001f8) << 3)
536                                 | ((r & 0x0000001f) << 1)
537                                 | ((r & 0x80000000) >> 31);
538                         /*
539                          * Do salting for crypt() and friends, and
540                          * XOR with the permuted key.
541                          */
542                         f = (r48l ^ r48r) & saltbits;
543                         r48l ^= f ^ *kl++;
544                         r48r ^= f ^ *kr++;
545                         /*
546                          * Do sbox lookups (which shrink it back to 32 bits)
547                          * and do the pbox permutation at the same time.
548                          */
549                         f = psbox[0][m_sbox[0][r48l >> 12]]
550                           | psbox[1][m_sbox[1][r48l & 0xfff]]
551                           | psbox[2][m_sbox[2][r48r >> 12]]
552                           | psbox[3][m_sbox[3][r48r & 0xfff]];
553                         /*
554                          * Now that we've permuted things, complete f().
555                          */
556                         f ^= l;
557                         l = r;
558                         r = f;
559                 }
560                 r = l;
561                 l = f;
562         }
563         /*
564          * Do final permutation (inverse of IP).
565          */
566         *l_out  = fp_maskl[0][l >> 24]
567                 | fp_maskl[1][(l >> 16) & 0xff]
568                 | fp_maskl[2][(l >> 8) & 0xff]
569                 | fp_maskl[3][l & 0xff]
570                 | fp_maskl[4][r >> 24]
571                 | fp_maskl[5][(r >> 16) & 0xff]
572                 | fp_maskl[6][(r >> 8) & 0xff]
573                 | fp_maskl[7][r & 0xff];
574         *r_out  = fp_maskr[0][l >> 24]
575                 | fp_maskr[1][(l >> 16) & 0xff]
576                 | fp_maskr[2][(l >> 8) & 0xff]
577                 | fp_maskr[3][l & 0xff]
578                 | fp_maskr[4][r >> 24]
579                 | fp_maskr[5][(r >> 16) & 0xff]
580                 | fp_maskr[6][(r >> 8) & 0xff]
581                 | fp_maskr[7][r & 0xff];
582         return(0);
583 }
584
585 static int
586 des_cipher(const char *in, char *out, u_long salt, int count)
587 {
588         u_int32_t       l_out, r_out, rawl, rawr;
589         int             retval;
590         union {
591                 u_int32_t       *ui32;
592                 const char      *c;
593         } trans;
594
595         if (!des_initialised)
596                 des_init();
597
598         setup_salt(salt);
599
600         trans.c = in;
601         rawl = ntohl(*trans.ui32++);
602         rawr = ntohl(*trans.ui32);
603
604         retval = do_des(rawl, rawr, &l_out, &r_out, count);
605
606         trans.c = out;
607         *trans.ui32++ = htonl(l_out);
608         *trans.ui32 = htonl(r_out);
609         return(retval);
610 }
611
612 char *
613 crypt_des(const char *key, const char *setting)
614 {
615         int             i;
616         u_int32_t       count, salt, l, r0, r1, keybuf[2];
617         u_char          *p, *q;
618         static char     output[21];
619
620         if (!des_initialised)
621                 des_init();
622
623         /*
624          * Copy the key, shifting each character up by one bit
625          * and padding with zeros.
626          */
627         q = (u_char *)keybuf;
628         while (q - (u_char *)keybuf - 8) {
629                 *q++ = *key << 1;
630                 if (*key != '\0')
631                         key++;
632         }
633         if (des_setkey((char *)keybuf))
634                 return(NULL);
635
636         if (*setting == _PASSWORD_EFMT1) {
637                 /*
638                  * "new"-style:
639                  *      setting - underscore, 4 bytes of count, 4 bytes of salt
640                  *      key - unlimited characters
641                  */
642                 for (i = 1, count = 0L; i < 5; i++)
643                         count |= ascii_to_bin(setting[i]) << ((i - 1) * 6);
644
645                 for (i = 5, salt = 0L; i < 9; i++)
646                         salt |= ascii_to_bin(setting[i]) << ((i - 5) * 6);
647
648                 while (*key) {
649                         /*
650                          * Encrypt the key with itself.
651                          */
652                         if (des_cipher((char *)keybuf, (char *)keybuf, 0L, 1))
653                                 return(NULL);
654                         /*
655                          * And XOR with the next 8 characters of the key.
656                          */
657                         q = (u_char *)keybuf;
658                         while (q - (u_char *)keybuf - 8 && *key)
659                                 *q++ ^= *key++ << 1;
660
661                         if (des_setkey((char *)keybuf))
662                                 return(NULL);
663                 }
664                 strncpy(output, setting, 9);
665
666                 /*
667                  * Double check that we weren't given a short setting.
668                  * If we were, the above code will probably have created
669                  * wierd values for count and salt, but we don't really care.
670                  * Just make sure the output string doesn't have an extra
671                  * NUL in it.
672                  */
673                 output[9] = '\0';
674                 p = (u_char *)output + strlen(output);
675         } else {
676                 /*
677                  * "old"-style:
678                  *      setting - 2 bytes of salt
679                  *      key - up to 8 characters
680                  */
681                 count = 25;
682
683                 salt = (ascii_to_bin(setting[1]) << 6)
684                      |  ascii_to_bin(setting[0]);
685
686                 output[0] = setting[0];
687                 /*
688                  * If the encrypted password that the salt was extracted from
689                  * is only 1 character long, the salt will be corrupted.  We
690                  * need to ensure that the output string doesn't have an extra
691                  * NUL in it!
692                  */
693                 output[1] = setting[1] ? setting[1] : output[0];
694
695                 p = (u_char *)output + 2;
696         }
697         setup_salt(salt);
698         /*
699          * Do it.
700          */
701         if (do_des(0L, 0L, &r0, &r1, (int)count))
702                 return(NULL);
703         /*
704          * Now encode the result...
705          */
706         l = (r0 >> 8);
707         *p++ = ascii64[(l >> 18) & 0x3f];
708         *p++ = ascii64[(l >> 12) & 0x3f];
709         *p++ = ascii64[(l >> 6) & 0x3f];
710         *p++ = ascii64[l & 0x3f];
711
712         l = (r0 << 16) | ((r1 >> 16) & 0xffff);
713         *p++ = ascii64[(l >> 18) & 0x3f];
714         *p++ = ascii64[(l >> 12) & 0x3f];
715         *p++ = ascii64[(l >> 6) & 0x3f];
716         *p++ = ascii64[l & 0x3f];
717
718         l = r1 << 2;
719         *p++ = ascii64[(l >> 12) & 0x3f];
720         *p++ = ascii64[(l >> 6) & 0x3f];
721         *p++ = ascii64[l & 0x3f];
722         *p = 0;
723
724         return(output);
725 }
726 /* END: https://github.com/freebsd/freebsd/blob/master/secure/lib/libcrypt/crypt-des.c */
727
728
729 /* START: https://github.com/freebsd/freebsd/blob/master/lib/libcrypt/crypt-md5.c */
730 char *
731 crypt_md5(const char *pw, const char *salt)
732 {
733         MD5_CTX ctx,ctx1;
734         unsigned long l;
735         int sl, pl;
736         u_int i;
737         u_char final[MD5_SIZE];
738         static const char *sp, *ep;
739         static char passwd[120], *p;
740         static const char *magic = "$1$";
741
742         /* Refine the Salt first */
743         sp = salt;
744
745         /* If it starts with the magic string, then skip that */
746         if(!strncmp(sp, magic, strlen(magic)))
747                 sp += strlen(magic);
748
749         /* It stops at the first '$', max 8 chars */
750         for(ep = sp; *ep && *ep != '$' && ep < (sp + 8); ep++)
751                 continue;
752
753         /* get the length of the true salt */
754         sl = ep - sp;
755
756         MD5Init(&ctx);
757
758         /* The password first, since that is what is most unknown */
759         MD5Update(&ctx, (const u_char *)pw, strlen(pw));
760
761         /* Then our magic string */
762         MD5Update(&ctx, (const u_char *)magic, strlen(magic));
763
764         /* Then the raw salt */
765         MD5Update(&ctx, (const u_char *)sp, (u_int)sl);
766
767         /* Then just as many characters of the MD5(pw,salt,pw) */
768         MD5Init(&ctx1);
769         MD5Update(&ctx1, (const u_char *)pw, strlen(pw));
770         MD5Update(&ctx1, (const u_char *)sp, (u_int)sl);
771         MD5Update(&ctx1, (const u_char *)pw, strlen(pw));
772         MD5Final(final, &ctx1);
773         for(pl = (int)strlen(pw); pl > 0; pl -= MD5_SIZE)
774                 MD5Update(&ctx, (const u_char *)final,
775                     (u_int)(pl > MD5_SIZE ? MD5_SIZE : pl));
776
777         /* Don't leave anything around in vm they could use. */
778         memset(final, 0, sizeof(final));
779
780         /* Then something really weird... */
781         for (i = strlen(pw); i; i >>= 1)
782                 if(i & 1)
783                     MD5Update(&ctx, (const u_char *)final, 1);
784                 else
785                     MD5Update(&ctx, (const u_char *)pw, 1);
786
787         /* Now make the output string */
788         strcpy(passwd, magic);
789         strncat(passwd, sp, (u_int)sl);
790         strcat(passwd, "$");
791
792         MD5Final(final, &ctx);
793
794         /*
795          * and now, just to make sure things don't run too fast
796          * On a 60 Mhz Pentium this takes 34 msec, so you would
797          * need 30 seconds to build a 1000 entry dictionary...
798          */
799         for(i = 0; i < 1000; i++) {
800                 MD5Init(&ctx1);
801                 if(i & 1)
802                         MD5Update(&ctx1, (const u_char *)pw, strlen(pw));
803                 else
804                         MD5Update(&ctx1, (const u_char *)final, MD5_SIZE);
805
806                 if(i % 3)
807                         MD5Update(&ctx1, (const u_char *)sp, (u_int)sl);
808
809                 if(i % 7)
810                         MD5Update(&ctx1, (const u_char *)pw, strlen(pw));
811
812                 if(i & 1)
813                         MD5Update(&ctx1, (const u_char *)final, MD5_SIZE);
814                 else
815                         MD5Update(&ctx1, (const u_char *)pw, strlen(pw));
816                 MD5Final(final, &ctx1);
817         }
818
819         p = passwd + strlen(passwd);
820
821         l = (final[ 0]<<16) | (final[ 6]<<8) | final[12];
822         _crypt_to64(p, l, 4); p += 4;
823         l = (final[ 1]<<16) | (final[ 7]<<8) | final[13];
824         _crypt_to64(p, l, 4); p += 4;
825         l = (final[ 2]<<16) | (final[ 8]<<8) | final[14];
826         _crypt_to64(p, l, 4); p += 4;
827         l = (final[ 3]<<16) | (final[ 9]<<8) | final[15];
828         _crypt_to64(p, l, 4); p += 4;
829         l = (final[ 4]<<16) | (final[10]<<8) | final[ 5];
830         _crypt_to64(p, l, 4); p += 4;
831         l = final[11];
832         _crypt_to64(p, l, 2); p += 2;
833         *p = '\0';
834
835         /* Don't leave anything around in vm they could use. */
836         memset(final, 0, sizeof(final));
837
838         return (passwd);
839 }
840 /* END: https://github.com/freebsd/freebsd/blob/master/lib/libcrypt/crypt-md5.c */
841
842
843 /* START: https://github.com/freebsd/freebsd/blob/master/lib/libcrypt/crypt-sha256.c */
844 static const char sha256_salt_prefix[] = "$5$";
845
846 /* Prefix for optional rounds specification. */
847 static const char sha256_rounds_prefix[] = "rounds=";
848
849 /* Maximum salt string length. */
850 #define SALT_LEN_MAX 16
851 /* Default number of rounds if not explicitly specified. */
852 #define ROUNDS_DEFAULT 5000
853 /* Minimum number of rounds. */
854 #define ROUNDS_MIN 1000
855 /* Maximum number of rounds. */
856 #define ROUNDS_MAX 999999999
857
858 static char *
859 crypt_sha256_r(const char *key, const char *salt, char *buffer, int buflen)
860 {
861         u_long srounds;
862         int n;
863         uint8_t alt_result[32], temp_result[32];
864         SHA256_CTX ctx, alt_ctx;
865         size_t salt_len, key_len, cnt, rounds;
866         char *cp, *copied_key, *copied_salt, *p_bytes, *s_bytes, *endp;
867         const char *num;
868         bool rounds_custom;
869
870         copied_key = NULL;
871         copied_salt = NULL;
872
873         /* Default number of rounds. */
874         rounds = ROUNDS_DEFAULT;
875         rounds_custom = false;
876
877         /* Find beginning of salt string. The prefix should normally always
878          * be present. Just in case it is not. */
879         if (strncmp(sha256_salt_prefix, salt, sizeof(sha256_salt_prefix) - 1) == 0)
880                 /* Skip salt prefix. */
881                 salt += sizeof(sha256_salt_prefix) - 1;
882
883         if (strncmp(salt, sha256_rounds_prefix, sizeof(sha256_rounds_prefix) - 1)
884             == 0) {
885                 num = salt + sizeof(sha256_rounds_prefix) - 1;
886                 srounds = strtoul(num, &endp, 10);
887
888                 if (*endp == '$') {
889                         salt = endp + 1;
890                         rounds = MAX(ROUNDS_MIN, MIN(srounds, ROUNDS_MAX));
891                         rounds_custom = true;
892                 }
893         }
894
895         salt_len = MIN(strcspn(salt, "$"), SALT_LEN_MAX);
896         key_len = strlen(key);
897
898         /* Prepare for the real work. */
899         SHA256_Init(&ctx);
900
901         /* Add the key string. */
902         SHA256_Update(&ctx, key, key_len);
903
904         /* The last part is the salt string. This must be at most 8
905          * characters and it ends at the first `$' character (for
906          * compatibility with existing implementations). */
907         SHA256_Update(&ctx, salt, salt_len);
908
909         /* Compute alternate SHA256 sum with input KEY, SALT, and KEY. The
910          * final result will be added to the first context. */
911         SHA256_Init(&alt_ctx);
912
913         /* Add key. */
914         SHA256_Update(&alt_ctx, key, key_len);
915
916         /* Add salt. */
917         SHA256_Update(&alt_ctx, salt, salt_len);
918
919         /* Add key again. */
920         SHA256_Update(&alt_ctx, key, key_len);
921
922         /* Now get result of this (32 bytes) and add it to the other context. */
923         SHA256_Final(alt_result, &alt_ctx);
924
925         /* Add for any character in the key one byte of the alternate sum. */
926         for (cnt = key_len; cnt > 32; cnt -= 32)
927                 SHA256_Update(&ctx, alt_result, 32);
928         SHA256_Update(&ctx, alt_result, cnt);
929
930         /* Take the binary representation of the length of the key and for
931          * every 1 add the alternate sum, for every 0 the key. */
932         for (cnt = key_len; cnt > 0; cnt >>= 1)
933                 if ((cnt & 1) != 0)
934                         SHA256_Update(&ctx, alt_result, 32);
935                 else
936                         SHA256_Update(&ctx, key, key_len);
937
938         /* Create intermediate result. */
939         SHA256_Final(alt_result, &ctx);
940
941         /* Start computation of P byte sequence. */
942         SHA256_Init(&alt_ctx);
943
944         /* For every character in the password add the entire password. */
945         for (cnt = 0; cnt < key_len; ++cnt)
946                 SHA256_Update(&alt_ctx, key, key_len);
947
948         /* Finish the digest. */
949         SHA256_Final(temp_result, &alt_ctx);
950
951         /* Create byte sequence P. */
952         cp = p_bytes = alloca(key_len);
953         for (cnt = key_len; cnt >= 32; cnt -= 32) {
954                 memcpy(cp, temp_result, 32);
955                 cp += 32;
956         }
957         memcpy(cp, temp_result, cnt);
958
959         /* Start computation of S byte sequence. */
960         SHA256_Init(&alt_ctx);
961
962         /* For every character in the password add the entire password. */
963         for (cnt = 0; cnt < 16 + alt_result[0]; ++cnt)
964                 SHA256_Update(&alt_ctx, salt, salt_len);
965
966         /* Finish the digest. */
967         SHA256_Final(temp_result, &alt_ctx);
968
969         /* Create byte sequence S. */
970         cp = s_bytes = alloca(salt_len);
971         for (cnt = salt_len; cnt >= 32; cnt -= 32) {
972                 memcpy(cp, temp_result, 32);
973                 cp += 32;
974         }
975         memcpy(cp, temp_result, cnt);
976
977         /* Repeatedly run the collected hash value through SHA256 to burn CPU
978          * cycles. */
979         for (cnt = 0; cnt < rounds; ++cnt) {
980                 /* New context. */
981                 SHA256_Init(&ctx);
982
983                 /* Add key or last result. */
984                 if ((cnt & 1) != 0)
985                         SHA256_Update(&ctx, p_bytes, key_len);
986                 else
987                         SHA256_Update(&ctx, alt_result, 32);
988
989                 /* Add salt for numbers not divisible by 3. */
990                 if (cnt % 3 != 0)
991                         SHA256_Update(&ctx, s_bytes, salt_len);
992
993                 /* Add key for numbers not divisible by 7. */
994                 if (cnt % 7 != 0)
995                         SHA256_Update(&ctx, p_bytes, key_len);
996
997                 /* Add key or last result. */
998                 if ((cnt & 1) != 0)
999                         SHA256_Update(&ctx, alt_result, 32);
1000                 else
1001                         SHA256_Update(&ctx, p_bytes, key_len);
1002
1003                 /* Create intermediate result. */
1004                 SHA256_Final(alt_result, &ctx);
1005         }
1006
1007         /* Now we can construct the result string. It consists of three
1008          * parts. */
1009         cp = stpncpy(buffer, sha256_salt_prefix, MAX(0, buflen));
1010         buflen -= sizeof(sha256_salt_prefix) - 1;
1011
1012         if (rounds_custom) {
1013                 n = snprintf(cp, MAX(0, buflen), "%s%zu$",
1014                          sha256_rounds_prefix, rounds);
1015
1016                 cp += n;
1017                 buflen -= n;
1018         }
1019
1020         cp = stpncpy(cp, salt, MIN((size_t)MAX(0, buflen), salt_len));
1021         buflen -= MIN((size_t)MAX(0, buflen), salt_len);
1022
1023         if (buflen > 0) {
1024                 *cp++ = '$';
1025                 --buflen;
1026         }
1027
1028         b64_from_24bit(alt_result[0], alt_result[10], alt_result[20], 4, &buflen, &cp);
1029         b64_from_24bit(alt_result[21], alt_result[1], alt_result[11], 4, &buflen, &cp);
1030         b64_from_24bit(alt_result[12], alt_result[22], alt_result[2], 4, &buflen, &cp);
1031         b64_from_24bit(alt_result[3], alt_result[13], alt_result[23], 4, &buflen, &cp);
1032         b64_from_24bit(alt_result[24], alt_result[4], alt_result[14], 4, &buflen, &cp);
1033         b64_from_24bit(alt_result[15], alt_result[25], alt_result[5], 4, &buflen, &cp);
1034         b64_from_24bit(alt_result[6], alt_result[16], alt_result[26], 4, &buflen, &cp);
1035         b64_from_24bit(alt_result[27], alt_result[7], alt_result[17], 4, &buflen, &cp);
1036         b64_from_24bit(alt_result[18], alt_result[28], alt_result[8], 4, &buflen, &cp);
1037         b64_from_24bit(alt_result[9], alt_result[19], alt_result[29], 4, &buflen, &cp);
1038         b64_from_24bit(0, alt_result[31], alt_result[30], 3, &buflen, &cp);
1039         if (buflen <= 0) {
1040                 errno = ERANGE;
1041                 buffer = NULL;
1042         }
1043         else
1044                 *cp = '\0';     /* Terminate the string. */
1045
1046         /* Clear the buffer for the intermediate result so that people
1047          * attaching to processes or reading core dumps cannot get any
1048          * information. We do it in this way to clear correct_words[] inside
1049          * the SHA256 implementation as well. */
1050         SHA256_Init(&ctx);
1051         SHA256_Final(alt_result, &ctx);
1052         memset(temp_result, '\0', sizeof(temp_result));
1053         memset(p_bytes, '\0', key_len);
1054         memset(s_bytes, '\0', salt_len);
1055         memset(&ctx, '\0', sizeof(ctx));
1056         memset(&alt_ctx, '\0', sizeof(alt_ctx));
1057         if (copied_key != NULL)
1058                 memset(copied_key, '\0', key_len);
1059         if (copied_salt != NULL)
1060                 memset(copied_salt, '\0', salt_len);
1061
1062         return buffer;
1063 }
1064
1065 /* This entry point is equivalent to crypt(3). */
1066 char* crypt_sha256(const char *key, const char *salt)
1067 {
1068         /* We don't want to have an arbitrary limit in the size of the
1069          * password. We can compute an upper bound for the size of the
1070          * result in advance and so we can prepare the buffer we pass to
1071          * `crypt_sha256_r'. */
1072         static char *buffer;
1073         static int buflen;
1074         int needed;
1075         char *new_buffer;
1076
1077         needed = (sizeof(sha256_salt_prefix) - 1
1078               + sizeof(sha256_rounds_prefix) + 9 + 1
1079               + strlen(salt) + 1 + 43 + 1);
1080
1081         if (buflen < needed) {
1082                 new_buffer = (char *)realloc(buffer, needed);
1083
1084                 if (new_buffer == NULL)
1085                         return NULL;
1086
1087                 buffer = new_buffer;
1088                 buflen = needed;
1089         }
1090
1091         return crypt_sha256_r(key, salt, buffer, buflen);
1092 }
1093 /* END: https://github.com/freebsd/freebsd/blob/master/lib/libcrypt/crypt-sha256.c */
1094
1095
1096 /* START: https://github.com/freebsd/freebsd/blob/master/lib/libcrypt/crypt-sha512.c */
1097 /* Define our magic string to mark salt for SHA512 "encryption" replacement. */
1098 static const char sha512_salt_prefix[] = "$6$";
1099
1100 /* Prefix for optional rounds specification. */
1101 static const char sha512_rounds_prefix[] = "rounds=";
1102
1103 /* Maximum salt string length. */
1104 #define SALT_LEN_MAX 16
1105 /* Default number of rounds if not explicitly specified. */
1106 #define ROUNDS_DEFAULT 5000
1107 /* Minimum number of rounds. */
1108 #define ROUNDS_MIN 1000
1109 /* Maximum number of rounds. */
1110 #define ROUNDS_MAX 999999999
1111
1112 static char *
1113 crypt_sha512_r(const char *key, const char *salt, char *buffer, int buflen)
1114 {
1115         u_long srounds;
1116         int n;
1117         uint8_t alt_result[64], temp_result[64];
1118         SHA512_CTX ctx, alt_ctx;
1119         size_t salt_len, key_len, cnt, rounds;
1120         char *cp, *copied_key, *copied_salt, *p_bytes, *s_bytes, *endp;
1121         const char *num;
1122         bool rounds_custom;
1123
1124         copied_key = NULL;
1125         copied_salt = NULL;
1126
1127         /* Default number of rounds. */
1128         rounds = ROUNDS_DEFAULT;
1129         rounds_custom = false;
1130
1131         /* Find beginning of salt string. The prefix should normally always
1132          * be present. Just in case it is not. */
1133         if (strncmp(sha512_salt_prefix, salt, sizeof(sha512_salt_prefix) - 1) == 0)
1134                 /* Skip salt prefix. */
1135                 salt += sizeof(sha512_salt_prefix) - 1;
1136
1137         if (strncmp(salt, sha512_rounds_prefix, sizeof(sha512_rounds_prefix) - 1)
1138             == 0) {
1139                 num = salt + sizeof(sha512_rounds_prefix) - 1;
1140                 srounds = strtoul(num, &endp, 10);
1141
1142                 if (*endp == '$') {
1143                         salt = endp + 1;
1144                         rounds = MAX(ROUNDS_MIN, MIN(srounds, ROUNDS_MAX));
1145                         rounds_custom = true;
1146                 }
1147         }
1148
1149         salt_len = MIN(strcspn(salt, "$"), SALT_LEN_MAX);
1150         key_len = strlen(key);
1151
1152         /* Prepare for the real work. */
1153         SHA512_Init(&ctx);
1154
1155         /* Add the key string. */
1156         SHA512_Update(&ctx, key, key_len);
1157
1158         /* The last part is the salt string. This must be at most 8
1159          * characters and it ends at the first `$' character (for
1160          * compatibility with existing implementations). */
1161         SHA512_Update(&ctx, salt, salt_len);
1162
1163         /* Compute alternate SHA512 sum with input KEY, SALT, and KEY. The
1164          * final result will be added to the first context. */
1165         SHA512_Init(&alt_ctx);
1166
1167         /* Add key. */
1168         SHA512_Update(&alt_ctx, key, key_len);
1169
1170         /* Add salt. */
1171         SHA512_Update(&alt_ctx, salt, salt_len);
1172
1173         /* Add key again. */
1174         SHA512_Update(&alt_ctx, key, key_len);
1175
1176         /* Now get result of this (64 bytes) and add it to the other context. */
1177         SHA512_Final(alt_result, &alt_ctx);
1178
1179         /* Add for any character in the key one byte of the alternate sum. */
1180         for (cnt = key_len; cnt > 64; cnt -= 64)
1181                 SHA512_Update(&ctx, alt_result, 64);
1182         SHA512_Update(&ctx, alt_result, cnt);
1183
1184         /* Take the binary representation of the length of the key and for
1185          * every 1 add the alternate sum, for every 0 the key. */
1186         for (cnt = key_len; cnt > 0; cnt >>= 1)
1187                 if ((cnt & 1) != 0)
1188                         SHA512_Update(&ctx, alt_result, 64);
1189                 else
1190                         SHA512_Update(&ctx, key, key_len);
1191
1192         /* Create intermediate result. */
1193         SHA512_Final(alt_result, &ctx);
1194
1195         /* Start computation of P byte sequence. */
1196         SHA512_Init(&alt_ctx);
1197
1198         /* For every character in the password add the entire password. */
1199         for (cnt = 0; cnt < key_len; ++cnt)
1200                 SHA512_Update(&alt_ctx, key, key_len);
1201
1202         /* Finish the digest. */
1203         SHA512_Final(temp_result, &alt_ctx);
1204
1205         /* Create byte sequence P. */
1206         cp = p_bytes = alloca(key_len);
1207         for (cnt = key_len; cnt >= 64; cnt -= 64) {
1208                 memcpy(cp, temp_result, 64);
1209                 cp += 64;
1210         }
1211         memcpy(cp, temp_result, cnt);
1212
1213         /* Start computation of S byte sequence. */
1214         SHA512_Init(&alt_ctx);
1215
1216         /* For every character in the password add the entire password. */
1217         for (cnt = 0; cnt < 16 + alt_result[0]; ++cnt)
1218                 SHA512_Update(&alt_ctx, salt, salt_len);
1219
1220         /* Finish the digest. */
1221         SHA512_Final(temp_result, &alt_ctx);
1222
1223         /* Create byte sequence S. */
1224         cp = s_bytes = alloca(salt_len);
1225         for (cnt = salt_len; cnt >= 64; cnt -= 64) {
1226                 memcpy(cp, temp_result, 64);
1227                 cp += 64;
1228         }
1229         memcpy(cp, temp_result, cnt);
1230
1231         /* Repeatedly run the collected hash value through SHA512 to burn CPU
1232          * cycles. */
1233         for (cnt = 0; cnt < rounds; ++cnt) {
1234                 /* New context. */
1235                 SHA512_Init(&ctx);
1236
1237                 /* Add key or last result. */
1238                 if ((cnt & 1) != 0)
1239                         SHA512_Update(&ctx, p_bytes, key_len);
1240                 else
1241                         SHA512_Update(&ctx, alt_result, 64);
1242
1243                 /* Add salt for numbers not divisible by 3. */
1244                 if (cnt % 3 != 0)
1245                         SHA512_Update(&ctx, s_bytes, salt_len);
1246
1247                 /* Add key for numbers not divisible by 7. */
1248                 if (cnt % 7 != 0)
1249                         SHA512_Update(&ctx, p_bytes, key_len);
1250
1251                 /* Add key or last result. */
1252                 if ((cnt & 1) != 0)
1253                         SHA512_Update(&ctx, alt_result, 64);
1254                 else
1255                         SHA512_Update(&ctx, p_bytes, key_len);
1256
1257                 /* Create intermediate result. */
1258                 SHA512_Final(alt_result, &ctx);
1259         }
1260
1261         /* Now we can construct the result string. It consists of three
1262          * parts. */
1263         cp = stpncpy(buffer, sha512_salt_prefix, MAX(0, buflen));
1264         buflen -= sizeof(sha512_salt_prefix) - 1;
1265
1266         if (rounds_custom) {
1267                 n = snprintf(cp, MAX(0, buflen), "%s%zu$",
1268                          sha512_rounds_prefix, rounds);
1269
1270                 cp += n;
1271                 buflen -= n;
1272         }
1273
1274         cp = stpncpy(cp, salt, MIN((size_t)MAX(0, buflen), salt_len));
1275         buflen -= MIN((size_t)MAX(0, buflen), salt_len);
1276
1277         if (buflen > 0) {
1278                 *cp++ = '$';
1279                 --buflen;
1280         }
1281
1282         b64_from_24bit(alt_result[0], alt_result[21], alt_result[42], 4, &buflen, &cp);
1283         b64_from_24bit(alt_result[22], alt_result[43], alt_result[1], 4, &buflen, &cp);
1284         b64_from_24bit(alt_result[44], alt_result[2], alt_result[23], 4, &buflen, &cp);
1285         b64_from_24bit(alt_result[3], alt_result[24], alt_result[45], 4, &buflen, &cp);
1286         b64_from_24bit(alt_result[25], alt_result[46], alt_result[4], 4, &buflen, &cp);
1287         b64_from_24bit(alt_result[47], alt_result[5], alt_result[26], 4, &buflen, &cp);
1288         b64_from_24bit(alt_result[6], alt_result[27], alt_result[48], 4, &buflen, &cp);
1289         b64_from_24bit(alt_result[28], alt_result[49], alt_result[7], 4, &buflen, &cp);
1290         b64_from_24bit(alt_result[50], alt_result[8], alt_result[29], 4, &buflen, &cp);
1291         b64_from_24bit(alt_result[9], alt_result[30], alt_result[51], 4, &buflen, &cp);
1292         b64_from_24bit(alt_result[31], alt_result[52], alt_result[10], 4, &buflen, &cp);
1293         b64_from_24bit(alt_result[53], alt_result[11], alt_result[32], 4, &buflen, &cp);
1294         b64_from_24bit(alt_result[12], alt_result[33], alt_result[54], 4, &buflen, &cp);
1295         b64_from_24bit(alt_result[34], alt_result[55], alt_result[13], 4, &buflen, &cp);
1296         b64_from_24bit(alt_result[56], alt_result[14], alt_result[35], 4, &buflen, &cp);
1297         b64_from_24bit(alt_result[15], alt_result[36], alt_result[57], 4, &buflen, &cp);
1298         b64_from_24bit(alt_result[37], alt_result[58], alt_result[16], 4, &buflen, &cp);
1299         b64_from_24bit(alt_result[59], alt_result[17], alt_result[38], 4, &buflen, &cp);
1300         b64_from_24bit(alt_result[18], alt_result[39], alt_result[60], 4, &buflen, &cp);
1301         b64_from_24bit(alt_result[40], alt_result[61], alt_result[19], 4, &buflen, &cp);
1302         b64_from_24bit(alt_result[62], alt_result[20], alt_result[41], 4, &buflen, &cp);
1303         b64_from_24bit(0, 0, alt_result[63], 2, &buflen, &cp);
1304
1305         if (buflen <= 0) {
1306                 errno = ERANGE;
1307                 buffer = NULL;
1308         }
1309         else
1310                 *cp = '\0';     /* Terminate the string. */
1311
1312         /* Clear the buffer for the intermediate result so that people
1313          * attaching to processes or reading core dumps cannot get any
1314          * information. We do it in this way to clear correct_words[] inside
1315          * the SHA512 implementation as well. */
1316         SHA512_Init(&ctx);
1317         SHA512_Final(alt_result, &ctx);
1318         memset(temp_result, '\0', sizeof(temp_result));
1319         memset(p_bytes, '\0', key_len);
1320         memset(s_bytes, '\0', salt_len);
1321         memset(&ctx, '\0', sizeof(ctx));
1322         memset(&alt_ctx, '\0', sizeof(alt_ctx));
1323         if (copied_key != NULL)
1324                 memset(copied_key, '\0', key_len);
1325         if (copied_salt != NULL)
1326                 memset(copied_salt, '\0', salt_len);
1327
1328         return buffer;
1329 }
1330
1331 /* This entry point is equivalent to crypt(3). */
1332 char *
1333 crypt_sha512(const char *key, const char *salt)
1334 {
1335         /* We don't want to have an arbitrary limit in the size of the
1336          * password. We can compute an upper bound for the size of the
1337          * result in advance and so we can prepare the buffer we pass to
1338          * `crypt_sha512_r'. */
1339         static char *buffer;
1340         static int buflen;
1341         int needed;
1342         char *new_buffer;
1343
1344         needed = (sizeof(sha512_salt_prefix) - 1
1345               + sizeof(sha512_rounds_prefix) + 9 + 1
1346               + strlen(salt) + 1 + 86 + 1);
1347
1348         if (buflen < needed) {
1349                 new_buffer = (char *)realloc(buffer, needed);
1350
1351                 if (new_buffer == NULL)
1352                         return NULL;
1353
1354                 buffer = new_buffer;
1355                 buflen = needed;
1356         }
1357
1358         return crypt_sha512_r(key, salt, buffer, buflen);
1359 }
1360 /* END: https://github.com/freebsd/freebsd/blob/master/lib/libcrypt/crypt-sha512.c */
1361
1362
1363 /** From https://github.com/freebsd/freebsd/blob/master/lib/libcrypt/crypt.c */
1364 static const struct crypt_format {
1365         const char* const name;
1366         const char* const magic;
1367         char* (*const func)(char const*, char const*);
1368 } crypt_formats[] = {
1369         { "des", "_", crypt_des },
1370         { "md5", "$1$", crypt_md5 },
1371         { "sha256", "$5$", crypt_sha256 },
1372         { "sha512", "$6$", crypt_sha512 },
1373         { NULL, NULL, NULL }
1374 };
1375
1376
1377 char* crypt(const char* key, const char* salt)
1378 {
1379         size_t len;
1380         const struct crypt_format *cf;
1381
1382         for (cf = crypt_formats; cf->name != NULL; ++cf) {
1383                 if (cf->magic != NULL && strstr(salt, cf->magic) == salt) {
1384                         return cf->func(key, salt);
1385                 }
1386         }
1387
1388         len = strlen(salt);
1389         if ((len == 13 || len == 2) && strspn(salt, DES_SALT_ALPHABET) == len) {
1390                 return (crypt_des(key, salt));
1391         }
1392
1393         return crypt_formats[0].func(key, salt);
1394 }