Fix formatting
[platform/upstream/glibc.git] / crypt / sha256-crypt.c
1 /* One way encryption based on SHA256 sum.
2    Copyright (C) 2007-2014 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4    Contributed by Ulrich Drepper <drepper@redhat.com>, 2007.
5
6    The GNU C Library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Lesser General Public
8    License as published by the Free Software Foundation; either
9    version 2.1 of the License, or (at your option) any later version.
10
11    The GNU C Library is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    Lesser General Public License for more details.
15
16    You should have received a copy of the GNU Lesser General Public
17    License along with the GNU C Library; if not, see
18    <http://www.gnu.org/licenses/>.  */
19
20 #include <assert.h>
21 #include <errno.h>
22 #include <stdbool.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <stdint.h>
26 #include <sys/param.h>
27
28 #include "sha256.h"
29
30
31 #ifdef USE_NSS
32 typedef int PRBool;
33 # include <hasht.h>
34 # include <nsslowhash.h>
35
36 # define sha256_init_ctx(ctxp, nss_ctxp) \
37   do                                                                          \
38     {                                                                         \
39       if (((nss_ctxp = NSSLOWHASH_NewContext (nss_ictx, HASH_AlgSHA256))      \
40            == NULL))                                                          \
41         {                                                                     \
42           if (nss_ctx != NULL)                                                \
43             NSSLOWHASH_Destroy (nss_ctx);                                     \
44           if (nss_alt_ctx != NULL)                                            \
45             NSSLOWHASH_Destroy (nss_alt_ctx);                                 \
46           return NULL;                                                        \
47         }                                                                     \
48       NSSLOWHASH_Begin (nss_ctxp);                                            \
49     }                                                                         \
50   while (0)
51
52 # define sha256_process_bytes(buf, len, ctxp, nss_ctxp) \
53   NSSLOWHASH_Update (nss_ctxp, (const unsigned char *) buf, len)
54
55 # define sha256_finish_ctx(ctxp, nss_ctxp, result) \
56   do                                                                          \
57     {                                                                         \
58       unsigned int ret;                                                       \
59       NSSLOWHASH_End (nss_ctxp, result, &ret, sizeof (result));               \
60       assert (ret == sizeof (result));                                        \
61       NSSLOWHASH_Destroy (nss_ctxp);                                          \
62       nss_ctxp = NULL;                                                        \
63     }                                                                         \
64   while (0)
65 #else
66 # define sha256_init_ctx(ctxp, nss_ctxp) \
67   __sha256_init_ctx (ctxp)
68
69 # define sha256_process_bytes(buf, len, ctxp, nss_ctxp) \
70   __sha256_process_bytes(buf, len, ctxp)
71
72 # define sha256_finish_ctx(ctxp, nss_ctxp, result) \
73   __sha256_finish_ctx (ctxp, result)
74 #endif
75
76
77 /* Define our magic string to mark salt for SHA256 "encryption"
78    replacement.  */
79 static const char sha256_salt_prefix[] = "$5$";
80
81 /* Prefix for optional rounds specification.  */
82 static const char sha256_rounds_prefix[] = "rounds=";
83
84 /* Maximum salt string length.  */
85 #define SALT_LEN_MAX 16
86 /* Default number of rounds if not explicitly specified.  */
87 #define ROUNDS_DEFAULT 5000
88 /* Minimum number of rounds.  */
89 #define ROUNDS_MIN 1000
90 /* Maximum number of rounds.  */
91 #define ROUNDS_MAX 999999999
92
93 /* Table with characters for base64 transformation.  */
94 static const char b64t[64] =
95 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
96
97
98 /* Prototypes for local functions.  */
99 extern char *__sha256_crypt_r (const char *key, const char *salt,
100                                char *buffer, int buflen);
101 extern char *__sha256_crypt (const char *key, const char *salt);
102
103
104 char *
105 __sha256_crypt_r (key, salt, buffer, buflen)
106      const char *key;
107      const char *salt;
108      char *buffer;
109      int buflen;
110 {
111   unsigned char alt_result[32]
112     __attribute__ ((__aligned__ (__alignof__ (uint32_t))));
113   unsigned char temp_result[32]
114     __attribute__ ((__aligned__ (__alignof__ (uint32_t))));
115   size_t salt_len;
116   size_t key_len;
117   size_t cnt;
118   char *cp;
119   char *copied_key = NULL;
120   char *copied_salt = NULL;
121   char *p_bytes;
122   char *s_bytes;
123   /* Default number of rounds.  */
124   size_t rounds = ROUNDS_DEFAULT;
125   bool rounds_custom = false;
126   size_t alloca_used = 0;
127   char *free_key = NULL;
128   char *free_pbytes = NULL;
129
130   /* Find beginning of salt string.  The prefix should normally always
131      be present.  Just in case it is not.  */
132   if (strncmp (sha256_salt_prefix, salt, sizeof (sha256_salt_prefix) - 1) == 0)
133     /* Skip salt prefix.  */
134     salt += sizeof (sha256_salt_prefix) - 1;
135
136   if (strncmp (salt, sha256_rounds_prefix, sizeof (sha256_rounds_prefix) - 1)
137       == 0)
138     {
139       const char *num = salt + sizeof (sha256_rounds_prefix) - 1;
140       char *endp;
141       unsigned long int srounds = strtoul (num, &endp, 10);
142       if (*endp == '$')
143         {
144           salt = endp + 1;
145           rounds = MAX (ROUNDS_MIN, MIN (srounds, ROUNDS_MAX));
146           rounds_custom = true;
147         }
148     }
149
150   salt_len = MIN (strcspn (salt, "$"), SALT_LEN_MAX);
151   key_len = strlen (key);
152
153   if ((key - (char *) 0) % __alignof__ (uint32_t) != 0)
154     {
155       char *tmp;
156
157       if (__libc_use_alloca (alloca_used + key_len + __alignof__ (uint32_t)))
158         tmp = alloca_account (key_len + __alignof__ (uint32_t), alloca_used);
159       else
160         {
161           free_key = tmp = (char *) malloc (key_len + __alignof__ (uint32_t));
162           if (tmp == NULL)
163             return NULL;
164         }
165
166       key = copied_key =
167         memcpy (tmp + __alignof__ (uint32_t)
168                 - (tmp - (char *) 0) % __alignof__ (uint32_t),
169                 key, key_len);
170       assert ((key - (char *) 0) % __alignof__ (uint32_t) == 0);
171     }
172
173   if ((salt - (char *) 0) % __alignof__ (uint32_t) != 0)
174     {
175       char *tmp = (char *) alloca (salt_len + __alignof__ (uint32_t));
176       alloca_used += salt_len + __alignof__ (uint32_t);
177       salt = copied_salt =
178         memcpy (tmp + __alignof__ (uint32_t)
179                 - (tmp - (char *) 0) % __alignof__ (uint32_t),
180                 salt, salt_len);
181       assert ((salt - (char *) 0) % __alignof__ (uint32_t) == 0);
182     }
183
184 #ifdef USE_NSS
185   /* Initialize libfreebl3.  */
186   NSSLOWInitContext *nss_ictx = NSSLOW_Init ();
187   if (nss_ictx == NULL)
188     {
189       free (free_key);
190       return NULL;
191     }
192   NSSLOWHASHContext *nss_ctx = NULL;
193   NSSLOWHASHContext *nss_alt_ctx = NULL;
194 #else
195   struct sha256_ctx ctx;
196   struct sha256_ctx alt_ctx;
197 #endif
198
199   /* Prepare for the real work.  */
200   sha256_init_ctx (&ctx, nss_ctx);
201
202   /* Add the key string.  */
203   sha256_process_bytes (key, key_len, &ctx, nss_ctx);
204
205   /* The last part is the salt string.  This must be at most 16
206      characters and it ends at the first `$' character.  */
207   sha256_process_bytes (salt, salt_len, &ctx, nss_ctx);
208
209
210   /* Compute alternate SHA256 sum with input KEY, SALT, and KEY.  The
211      final result will be added to the first context.  */
212   sha256_init_ctx (&alt_ctx, nss_alt_ctx);
213
214   /* Add key.  */
215   sha256_process_bytes (key, key_len, &alt_ctx, nss_alt_ctx);
216
217   /* Add salt.  */
218   sha256_process_bytes (salt, salt_len, &alt_ctx, nss_alt_ctx);
219
220   /* Add key again.  */
221   sha256_process_bytes (key, key_len, &alt_ctx, nss_alt_ctx);
222
223   /* Now get result of this (32 bytes) and add it to the other
224      context.  */
225   sha256_finish_ctx (&alt_ctx, nss_alt_ctx, alt_result);
226
227   /* Add for any character in the key one byte of the alternate sum.  */
228   for (cnt = key_len; cnt > 32; cnt -= 32)
229     sha256_process_bytes (alt_result, 32, &ctx, nss_ctx);
230   sha256_process_bytes (alt_result, cnt, &ctx, nss_ctx);
231
232   /* Take the binary representation of the length of the key and for every
233      1 add the alternate sum, for every 0 the key.  */
234   for (cnt = key_len; cnt > 0; cnt >>= 1)
235     if ((cnt & 1) != 0)
236       sha256_process_bytes (alt_result, 32, &ctx, nss_ctx);
237     else
238       sha256_process_bytes (key, key_len, &ctx, nss_ctx);
239
240   /* Create intermediate result.  */
241   sha256_finish_ctx (&ctx, nss_ctx, alt_result);
242
243   /* Start computation of P byte sequence.  */
244   sha256_init_ctx (&alt_ctx, nss_alt_ctx);
245
246   /* For every character in the password add the entire password.  */
247   for (cnt = 0; cnt < key_len; ++cnt)
248     sha256_process_bytes (key, key_len, &alt_ctx, nss_alt_ctx);
249
250   /* Finish the digest.  */
251   sha256_finish_ctx (&alt_ctx, nss_alt_ctx, temp_result);
252
253   /* Create byte sequence P.  */
254   if (__libc_use_alloca (alloca_used + key_len))
255     cp = p_bytes = (char *) alloca (key_len);
256   else
257     {
258       free_pbytes = cp = p_bytes = (char *)malloc (key_len);
259       if (free_pbytes == NULL)
260         {
261           free (free_key);
262           return NULL;
263         }
264     }
265
266   for (cnt = key_len; cnt >= 32; cnt -= 32)
267     cp = mempcpy (cp, temp_result, 32);
268   memcpy (cp, temp_result, cnt);
269
270   /* Start computation of S byte sequence.  */
271   sha256_init_ctx (&alt_ctx, nss_alt_ctx);
272
273   /* For every character in the password add the entire password.  */
274   for (cnt = 0; cnt < 16 + alt_result[0]; ++cnt)
275     sha256_process_bytes (salt, salt_len, &alt_ctx, nss_alt_ctx);
276
277   /* Finish the digest.  */
278   sha256_finish_ctx (&alt_ctx, nss_alt_ctx, temp_result);
279
280   /* Create byte sequence S.  */
281   cp = s_bytes = alloca (salt_len);
282   for (cnt = salt_len; cnt >= 32; cnt -= 32)
283     cp = mempcpy (cp, temp_result, 32);
284   memcpy (cp, temp_result, cnt);
285
286   /* Repeatedly run the collected hash value through SHA256 to burn
287      CPU cycles.  */
288   for (cnt = 0; cnt < rounds; ++cnt)
289     {
290       /* New context.  */
291       sha256_init_ctx (&ctx, nss_ctx);
292
293       /* Add key or last result.  */
294       if ((cnt & 1) != 0)
295         sha256_process_bytes (p_bytes, key_len, &ctx, nss_ctx);
296       else
297         sha256_process_bytes (alt_result, 32, &ctx, nss_ctx);
298
299       /* Add salt for numbers not divisible by 3.  */
300       if (cnt % 3 != 0)
301         sha256_process_bytes (s_bytes, salt_len, &ctx, nss_ctx);
302
303       /* Add key for numbers not divisible by 7.  */
304       if (cnt % 7 != 0)
305         sha256_process_bytes (p_bytes, key_len, &ctx, nss_ctx);
306
307       /* Add key or last result.  */
308       if ((cnt & 1) != 0)
309         sha256_process_bytes (alt_result, 32, &ctx, nss_ctx);
310       else
311         sha256_process_bytes (p_bytes, key_len, &ctx, nss_ctx);
312
313       /* Create intermediate result.  */
314       sha256_finish_ctx (&ctx, nss_ctx, alt_result);
315     }
316
317 #ifdef USE_NSS
318   /* Free libfreebl3 resources. */
319   NSSLOW_Shutdown (nss_ictx);
320 #endif
321
322   /* Now we can construct the result string.  It consists of three
323      parts.  */
324   cp = __stpncpy (buffer, sha256_salt_prefix, MAX (0, buflen));
325   buflen -= sizeof (sha256_salt_prefix) - 1;
326
327   if (rounds_custom)
328     {
329       int n = snprintf (cp, MAX (0, buflen), "%s%zu$",
330                         sha256_rounds_prefix, rounds);
331       cp += n;
332       buflen -= n;
333     }
334
335   cp = __stpncpy (cp, salt, MIN ((size_t) MAX (0, buflen), salt_len));
336   buflen -= MIN ((size_t) MAX (0, buflen), salt_len);
337
338   if (buflen > 0)
339     {
340       *cp++ = '$';
341       --buflen;
342     }
343
344   void b64_from_24bit (unsigned int b2, unsigned int b1, unsigned int b0,
345                        int n)
346   {
347     unsigned int w = (b2 << 16) | (b1 << 8) | b0;
348     while (n-- > 0 && buflen > 0)
349       {
350         *cp++ = b64t[w & 0x3f];
351         --buflen;
352         w >>= 6;
353       }
354   }
355
356   b64_from_24bit (alt_result[0], alt_result[10], alt_result[20], 4);
357   b64_from_24bit (alt_result[21], alt_result[1], alt_result[11], 4);
358   b64_from_24bit (alt_result[12], alt_result[22], alt_result[2], 4);
359   b64_from_24bit (alt_result[3], alt_result[13], alt_result[23], 4);
360   b64_from_24bit (alt_result[24], alt_result[4], alt_result[14], 4);
361   b64_from_24bit (alt_result[15], alt_result[25], alt_result[5], 4);
362   b64_from_24bit (alt_result[6], alt_result[16], alt_result[26], 4);
363   b64_from_24bit (alt_result[27], alt_result[7], alt_result[17], 4);
364   b64_from_24bit (alt_result[18], alt_result[28], alt_result[8], 4);
365   b64_from_24bit (alt_result[9], alt_result[19], alt_result[29], 4);
366   b64_from_24bit (0, alt_result[31], alt_result[30], 3);
367   if (buflen <= 0)
368     {
369       __set_errno (ERANGE);
370       buffer = NULL;
371     }
372   else
373     *cp = '\0';         /* Terminate the string.  */
374
375   /* Clear the buffer for the intermediate result so that people
376      attaching to processes or reading core dumps cannot get any
377      information.  We do it in this way to clear correct_words[]
378      inside the SHA256 implementation as well.  */
379 #ifndef USE_NSS
380   __sha256_init_ctx (&ctx);
381   __sha256_finish_ctx (&ctx, alt_result);
382   memset (&ctx, '\0', sizeof (ctx));
383   memset (&alt_ctx, '\0', sizeof (alt_ctx));
384 #endif
385   memset (temp_result, '\0', sizeof (temp_result));
386   memset (p_bytes, '\0', key_len);
387   memset (s_bytes, '\0', salt_len);
388   if (copied_key != NULL)
389     memset (copied_key, '\0', key_len);
390   if (copied_salt != NULL)
391     memset (copied_salt, '\0', salt_len);
392
393   free (free_key);
394   free (free_pbytes);
395   return buffer;
396 }
397
398 #ifndef _LIBC
399 # define libc_freeres_ptr(decl) decl
400 #endif
401 libc_freeres_ptr (static char *buffer);
402
403 /* This entry point is equivalent to the `crypt' function in Unix
404    libcs.  */
405 char *
406 __sha256_crypt (const char *key, const char *salt)
407 {
408   /* We don't want to have an arbitrary limit in the size of the
409      password.  We can compute an upper bound for the size of the
410      result in advance and so we can prepare the buffer we pass to
411      `sha256_crypt_r'.  */
412   static int buflen;
413   int needed = (sizeof (sha256_salt_prefix) - 1
414                 + sizeof (sha256_rounds_prefix) + 9 + 1
415                 + strlen (salt) + 1 + 43 + 1);
416
417   if (buflen < needed)
418     {
419       char *new_buffer = (char *) realloc (buffer, needed);
420       if (new_buffer == NULL)
421         return NULL;
422
423       buffer = new_buffer;
424       buflen = needed;
425     }
426
427   return __sha256_crypt_r (key, salt, buffer, buflen);
428 }
429
430 #ifndef _LIBC
431 static void
432 __attribute__ ((__destructor__))
433 free_mem (void)
434 {
435   free (buffer);
436 }
437 #endif