Home | History | Annotate | Line # | Download | only in libcrypt
bcrypt.c revision 1.7
      1 /*	$NetBSD: bcrypt.c,v 1.7 2005/01/12 05:27:35 christos Exp $	*/
      2 /*	$OpenBSD: bcrypt.c,v 1.16 2002/02/19 19:39:36 millert Exp $	*/
      3 
      4 /*
      5  * Copyright 1997 Niels Provos <provos (at) physnet.uni-hamburg.de>
      6  * All rights reserved.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. All advertising materials mentioning features or use of this software
     17  *    must display the following acknowledgement:
     18  *      This product includes software developed by Niels Provos.
     19  * 4. The name of the author may not be used to endorse or promote products
     20  *    derived from this software without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     32  */
     33 
     34 /* This password hashing algorithm was designed by David Mazieres
     35  * <dm (at) 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 #include <sys/cdefs.h>
     49 __RCSID("$NetBSD: bcrypt.c,v 1.7 2005/01/12 05:27:35 christos Exp $");
     50 
     51 #include <stdio.h>
     52 #include <stdlib.h>
     53 #include <sys/types.h>
     54 #include <string.h>
     55 #include <pwd.h>
     56 #include <errno.h>
     57 #include <limits.h>
     58 
     59 #include "crypt.h"
     60 #include "blowfish.c"
     61 
     62 /* This implementation is adaptable to current computing power.
     63  * You can have up to 2^31 rounds which should be enough for some
     64  * time to come.
     65  */
     66 
     67 #define BCRYPT_VERSION '2'
     68 #define BCRYPT_MAXSALT 16	/* Precomputation is just so nice */
     69 #define BCRYPT_MAXSALTLEN 	(BCRYPT_MAXSALT * 4 / 3 + 1)
     70 #define BCRYPT_BLOCKS 6		/* Ciphertext blocks */
     71 #define BCRYPT_MINROUNDS 16	/* we have log2(rounds) in salt */
     72 
     73 static void encode_salt(char *, u_int8_t *, u_int16_t, u_int8_t);
     74 static void encode_base64(u_int8_t *, u_int8_t *, u_int16_t);
     75 static void decode_base64(u_int8_t *, u_int16_t, const u_int8_t *);
     76 
     77 char *__bcrypt(const char *, const char *);	/* XXX */
     78 
     79 static char    encrypted[_PASSWORD_LEN];
     80 static char    error[] = ":";
     81 
     82 const static u_int8_t Base64Code[] =
     83 "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
     84 
     85 char *bcrypt_gensalt(u_int8_t);
     86 
     87 const static u_int8_t index_64[128] =
     88 {
     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, 255, 255, 255, 255,
     93 	255, 255, 255, 255, 255, 255, 0, 1, 54, 55,
     94 	56, 57, 58, 59, 60, 61, 62, 63, 255, 255,
     95 	255, 255, 255, 255, 255, 2, 3, 4, 5, 6,
     96 	7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
     97 	17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
     98 	255, 255, 255, 255, 255, 255, 28, 29, 30,
     99 	31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    100 	41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
    101 	51, 52, 53, 255, 255, 255, 255, 255
    102 };
    103 #define CHAR64(c)  ( (c) > 127 ? 255 : index_64[(c)])
    104 
    105 static void
    106 decode_base64(u_int8_t *buffer, u_int16_t len, const u_int8_t *data)
    107 {
    108 	u_int8_t *bp = buffer;
    109 	const u_int8_t *p = data;
    110 	u_int8_t c1, c2, c3, c4;
    111 	while (bp < buffer + len) {
    112 		c1 = CHAR64(*p);
    113 		c2 = CHAR64(*(p + 1));
    114 
    115 		/* Invalid data */
    116 		if (c1 == 255 || c2 == 255)
    117 			break;
    118 
    119 		*bp++ = ((u_int32_t)c1 << 2) | (((u_int32_t)c2 & 0x30) >> 4);
    120 		if (bp >= buffer + len)
    121 			break;
    122 
    123 		c3 = CHAR64(*(p + 2));
    124 		if (c3 == 255)
    125 			break;
    126 
    127 		*bp++ = (((u_int32_t)c2 & 0x0f) << 4) | (((uint32_t)c3 & 0x3c) >> 2);
    128 		if (bp >= buffer + len)
    129 			break;
    130 
    131 		c4 = CHAR64(*(p + 3));
    132 		if (c4 == 255)
    133 			break;
    134 		*bp++ = ((c3 & 0x03) << 6) | c4;
    135 
    136 		p += 4;
    137 	}
    138 }
    139 
    140 static void
    141 encode_salt(char *salt, u_int8_t *csalt, u_int16_t clen, u_int8_t logr)
    142 {
    143 	salt[0] = '$';
    144 	salt[1] = BCRYPT_VERSION;
    145 	salt[2] = 'a';
    146 	salt[3] = '$';
    147 
    148 	snprintf(salt + 4, 4, "%2.2u$", logr);
    149 
    150 	encode_base64((u_int8_t *) salt + 7, csalt, clen);
    151 }
    152 
    153 int
    154 __gensalt_blowfish(char *salt, size_t saltlen, const char *option)
    155 {
    156 	size_t i;
    157 	u_int32_t seed = 0;
    158 	u_int8_t csalt[BCRYPT_MAXSALT];
    159 	unsigned long nrounds;
    160 	char *ep;
    161 
    162 	if (saltlen < BCRYPT_MAXSALTLEN) {
    163 		errno = ENOSPC;
    164 		return -1;
    165 	}
    166 	nrounds = strtoul(option, &ep, 0);
    167 	if (option == ep || *ep) {
    168 		errno = EINVAL;
    169 		return -1;
    170 	}
    171 	if (errno == ERANGE && nrounds == ULONG_MAX)
    172 		return -1;
    173 
    174 	if (nrounds > 255) {
    175 		errno = EINVAL;
    176 		return -1;
    177 	}
    178 
    179 	if (nrounds < 4)
    180 		nrounds = 4;
    181 
    182 	for (i = 0; i < BCRYPT_MAXSALT; i++) {
    183 		if (i % 4 == 0)
    184 			seed = arc4random();
    185 		csalt[i] = seed & 0xff;
    186 		seed = seed >> 8;
    187 	}
    188 	encode_salt(salt, csalt, BCRYPT_MAXSALT, (u_int8_t)nrounds);
    189 	return 0;
    190 }
    191 
    192 /* Generates a salt for this version of crypt.
    193    Since versions may change. Keeping this here
    194    seems sensible.
    195    XXX: compat.
    196  */
    197 char *
    198 bcrypt_gensalt(u_int8_t log_rounds)
    199 {
    200 	static char gsalt[BCRYPT_MAXSALTLEN];
    201 	char num[10];
    202 
    203 	(void)snprintf(num, sizeof(num), "%d", log_rounds);
    204 	if (__gensalt_blowfish(gsalt, sizeof(gsalt), num) == -1)
    205 		return NULL;
    206 	return gsalt;
    207 }
    208 
    209 /* We handle $Vers$log2(NumRounds)$salt+passwd$
    210    i.e. $2$04$iwouldntknowwhattosayetKdJ6iFtacBqJdKe6aW7ou */
    211 
    212 char   *
    213 __bcrypt(key, salt)
    214 	const char   *key;
    215 	const char   *salt;
    216 {
    217 	blf_ctx state;
    218 	u_int32_t rounds, i, k;
    219 	u_int16_t j;
    220 	u_int8_t key_len, salt_len, logr, minor;
    221 	u_int8_t ciphertext[4 * BCRYPT_BLOCKS] = "OrpheanBeholderScryDoubt";
    222 	u_int8_t csalt[BCRYPT_MAXSALT];
    223 	u_int32_t cdata[BCRYPT_BLOCKS];
    224 
    225 	/* Discard "$" identifier */
    226 	salt++;
    227 
    228 	if (*salt > BCRYPT_VERSION) {
    229 		/* How do I handle errors ? Return ':' */
    230 		return error;
    231 	}
    232 
    233 	/* Check for minor versions */
    234 	if (salt[1] != '$') {
    235 		 switch (salt[1]) {
    236 		 case 'a':
    237 			 /* 'ab' should not yield the same as 'abab' */
    238 			 minor = salt[1];
    239 			 salt++;
    240 			 break;
    241 		 default:
    242 			 return error;
    243 		 }
    244 	} else
    245 		 minor = 0;
    246 
    247 	/* Discard version + "$" identifier */
    248 	salt += 2;
    249 
    250 	if (salt[2] != '$')
    251 		/* Out of sync with passwd entry */
    252 		return error;
    253 
    254 	/* Computer power doesn't increase linear, 2^x should be fine */
    255 	if ((rounds = (u_int32_t) 1 << (logr = atoi(salt))) < BCRYPT_MINROUNDS)
    256 		return error;
    257 
    258 	/* Discard num rounds + "$" identifier */
    259 	salt += 3;
    260 
    261 	if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT)
    262 		return error;
    263 
    264 	/* We dont want the base64 salt but the raw data */
    265 	decode_base64(csalt, BCRYPT_MAXSALT, (const u_int8_t *)salt);
    266 	salt_len = BCRYPT_MAXSALT;
    267 	key_len = strlen(key) + (minor >= 'a' ? 1 : 0);
    268 
    269 	/* Setting up S-Boxes and Subkeys */
    270 	Blowfish_initstate(&state);
    271 	Blowfish_expandstate(&state, csalt, salt_len,
    272 	    (const u_int8_t *) key, key_len);
    273 	for (k = 0; k < rounds; k++) {
    274 		Blowfish_expand0state(&state, (const u_int8_t *) key, key_len);
    275 		Blowfish_expand0state(&state, csalt, salt_len);
    276 	}
    277 
    278 	/* This can be precomputed later */
    279 	j = 0;
    280 	for (i = 0; i < BCRYPT_BLOCKS; i++)
    281 		cdata[i] = Blowfish_stream2word(ciphertext, 4 * BCRYPT_BLOCKS, &j);
    282 
    283 	/* Now do the encryption */
    284 	for (k = 0; k < 64; k++)
    285 		blf_enc(&state, cdata, BCRYPT_BLOCKS / 2);
    286 
    287 	for (i = 0; i < BCRYPT_BLOCKS; i++) {
    288 		ciphertext[4 * i + 3] = cdata[i] & 0xff;
    289 		cdata[i] = cdata[i] >> 8;
    290 		ciphertext[4 * i + 2] = cdata[i] & 0xff;
    291 		cdata[i] = cdata[i] >> 8;
    292 		ciphertext[4 * i + 1] = cdata[i] & 0xff;
    293 		cdata[i] = cdata[i] >> 8;
    294 		ciphertext[4 * i + 0] = cdata[i] & 0xff;
    295 	}
    296 
    297 
    298 	i = 0;
    299 	encrypted[i++] = '$';
    300 	encrypted[i++] = BCRYPT_VERSION;
    301 	if (minor)
    302 		encrypted[i++] = minor;
    303 	encrypted[i++] = '$';
    304 
    305 	snprintf(encrypted + i, 4, "%2.2u$", logr);
    306 
    307 	encode_base64((u_int8_t *) encrypted + i + 3, csalt, BCRYPT_MAXSALT);
    308 	encode_base64((u_int8_t *) encrypted + strlen(encrypted), ciphertext,
    309 	    4 * BCRYPT_BLOCKS - 1);
    310 	return encrypted;
    311 }
    312 
    313 static void
    314 encode_base64(u_int8_t *buffer, u_int8_t *data, u_int16_t len)
    315 {
    316 	u_int8_t *bp = buffer;
    317 	u_int8_t *p = data;
    318 	u_int8_t c1, c2;
    319 	while (p < data + len) {
    320 		c1 = *p++;
    321 		*bp++ = Base64Code[((u_int32_t)c1 >> 2)];
    322 		c1 = (c1 & 0x03) << 4;
    323 		if (p >= data + len) {
    324 			*bp++ = Base64Code[c1];
    325 			break;
    326 		}
    327 		c2 = *p++;
    328 		c1 |= ((u_int32_t)c2 >> 4) & 0x0f;
    329 		*bp++ = Base64Code[c1];
    330 		c1 = (c2 & 0x0f) << 2;
    331 		if (p >= data + len) {
    332 			*bp++ = Base64Code[c1];
    333 			break;
    334 		}
    335 		c2 = *p++;
    336 		c1 |= ((u_int32_t)c2 >> 6) & 0x03;
    337 		*bp++ = Base64Code[c1];
    338 		*bp++ = Base64Code[c2 & 0x3f];
    339 	}
    340 	*bp = '\0';
    341 }
    342 #if 0
    343 void
    344 main()
    345 {
    346 	char    blubber[73];
    347 	char    salt[100];
    348 	char   *p;
    349 	salt[0] = '$';
    350 	salt[1] = BCRYPT_VERSION;
    351 	salt[2] = '$';
    352 
    353 	snprintf(salt + 3, 4, "%2.2u$", 5);
    354 
    355 	printf("24 bytes of salt: ");
    356 	fgets(salt + 6, 94, stdin);
    357 	salt[99] = 0;
    358 	printf("72 bytes of password: ");
    359 	fpurge(stdin);
    360 	fgets(blubber, 73, stdin);
    361 	blubber[72] = 0;
    362 
    363 	p = crypt(blubber, salt);
    364 	printf("Passwd entry: %s\n\n", p);
    365 
    366 	p = bcrypt_gensalt(5);
    367 	printf("Generated salt: %s\n", p);
    368 	p = crypt(blubber, p);
    369 	printf("Passwd entry: %s\n", p);
    370 }
    371 #endif
    372