Home | History | Annotate | Line # | Download | only in libcrypt
bcrypt.c revision 1.6
      1 /*	$NetBSD: bcrypt.c,v 1.6 2005/01/12 03:32:52 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.6 2005/01/12 03:32:52 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 
     58 #include "crypt.h"
     59 #include "blowfish.c"
     60 
     61 /* This implementation is adaptable to current computing power.
     62  * You can have up to 2^31 rounds which should be enough for some
     63  * time to come.
     64  */
     65 
     66 #define BCRYPT_VERSION '2'
     67 #define BCRYPT_MAXSALT 16	/* Precomputation is just so nice */
     68 #define BCRYPT_MAXSALTLEN 	(BCRYPT_MAXSALT * 4 / 3 + 1)
     69 #define BCRYPT_BLOCKS 6		/* Ciphertext blocks */
     70 #define BCRYPT_MINROUNDS 16	/* we have log2(rounds) in salt */
     71 
     72 static void encode_salt(char *, u_int8_t *, u_int16_t, u_int8_t);
     73 static void encode_base64(u_int8_t *, u_int8_t *, u_int16_t);
     74 static void decode_base64(u_int8_t *, u_int16_t, u_int8_t *);
     75 
     76 char *__bcrypt(const char *, const char *);	/* XXX */
     77 
     78 static char    encrypted[_PASSWORD_LEN];
     79 static char    error[] = ":";
     80 
     81 const static u_int8_t Base64Code[] =
     82 "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
     83 
     84 char *bcrypt_gensalt(u_int8_t);
     85 
     86 const static 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 
    152 int
    153 __gensalt_blowfish(char *salt, size_t saltlen, const char *option)
    154 {
    155 	size_t i;
    156 	u_int32_t seed = 0;
    157 	u_int8_t csalt[BCRYPT_MAXSALT];
    158 
    159 	if (saltlen < BCRYPT_MAXSALTLEN) {
    160 		errno = ENOSPC;
    161 		return -1;
    162 	}
    163 
    164 	if (nrounds > 255) {
    165 		errno = EINVAL;
    166 		return -1;
    167 	}
    168 
    169 	if (nrounds < 4)
    170 		nrounds = 4;
    171 
    172 	for (i = 0; i < BCRYPT_MAXSALT; i++) {
    173 		if (i % 4 == 0)
    174 			seed = arc4random();
    175 		csalt[i] = seed & 0xff;
    176 		seed = seed >> 8;
    177 	}
    178 	encode_salt(salt, csalt, BCRYPT_MAXSALT, nrounds);
    179 	return 0;
    180 }
    181 
    182 /* Generates a salt for this version of crypt.
    183    Since versions may change. Keeping this here
    184    seems sensible.
    185    XXX: compat.
    186  */
    187 char *
    188 bcrypt_gensalt(u_int8_t log_rounds)
    189 {
    190 	static char gsalt[BCRYPT_MAXSALTLEN];
    191 	char num[10];
    192 
    193 	(void)snprintf(num, sizeof(num), "%d", log_rounds);
    194 	if (__gensalt_blowfish(gsalt, sizeof(gsalt), num) == -1)
    195 		return NULL;
    196 	return gsalt;
    197 }
    198 
    199 /* We handle $Vers$log2(NumRounds)$salt+passwd$
    200    i.e. $2$04$iwouldntknowwhattosayetKdJ6iFtacBqJdKe6aW7ou */
    201 
    202 char   *
    203 __bcrypt(key, salt)
    204 	const char   *key;
    205 	const char   *salt;
    206 {
    207 	blf_ctx state;
    208 	u_int32_t rounds, i, k;
    209 	u_int16_t j;
    210 	u_int8_t key_len, salt_len, logr, minor;
    211 	u_int8_t ciphertext[4 * BCRYPT_BLOCKS] = "OrpheanBeholderScryDoubt";
    212 	u_int8_t csalt[BCRYPT_MAXSALT];
    213 	u_int32_t cdata[BCRYPT_BLOCKS];
    214 
    215 	/* Discard "$" identifier */
    216 	salt++;
    217 
    218 	if (*salt > BCRYPT_VERSION) {
    219 		/* How do I handle errors ? Return ':' */
    220 		return error;
    221 	}
    222 
    223 	/* Check for minor versions */
    224 	if (salt[1] != '$') {
    225 		 switch (salt[1]) {
    226 		 case 'a':
    227 			 /* 'ab' should not yield the same as 'abab' */
    228 			 minor = salt[1];
    229 			 salt++;
    230 			 break;
    231 		 default:
    232 			 return error;
    233 		 }
    234 	} else
    235 		 minor = 0;
    236 
    237 	/* Discard version + "$" identifier */
    238 	salt += 2;
    239 
    240 	if (salt[2] != '$')
    241 		/* Out of sync with passwd entry */
    242 		return error;
    243 
    244 	/* Computer power doesn't increase linear, 2^x should be fine */
    245 	if ((rounds = (u_int32_t) 1 << (logr = atoi(salt))) < BCRYPT_MINROUNDS)
    246 		return error;
    247 
    248 	/* Discard num rounds + "$" identifier */
    249 	salt += 3;
    250 
    251 	if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT)
    252 		return error;
    253 
    254 	/* We dont want the base64 salt but the raw data */
    255 	decode_base64(csalt, BCRYPT_MAXSALT, (u_int8_t *) salt);
    256 	salt_len = BCRYPT_MAXSALT;
    257 	key_len = strlen(key) + (minor >= 'a' ? 1 : 0);
    258 
    259 	/* Setting up S-Boxes and Subkeys */
    260 	Blowfish_initstate(&state);
    261 	Blowfish_expandstate(&state, csalt, salt_len,
    262 	    (u_int8_t *) key, key_len);
    263 	for (k = 0; k < rounds; k++) {
    264 		Blowfish_expand0state(&state, (u_int8_t *) key, key_len);
    265 		Blowfish_expand0state(&state, csalt, salt_len);
    266 	}
    267 
    268 	/* This can be precomputed later */
    269 	j = 0;
    270 	for (i = 0; i < BCRYPT_BLOCKS; i++)
    271 		cdata[i] = Blowfish_stream2word(ciphertext, 4 * BCRYPT_BLOCKS, &j);
    272 
    273 	/* Now do the encryption */
    274 	for (k = 0; k < 64; k++)
    275 		blf_enc(&state, cdata, BCRYPT_BLOCKS / 2);
    276 
    277 	for (i = 0; i < BCRYPT_BLOCKS; i++) {
    278 		ciphertext[4 * i + 3] = cdata[i] & 0xff;
    279 		cdata[i] = cdata[i] >> 8;
    280 		ciphertext[4 * i + 2] = cdata[i] & 0xff;
    281 		cdata[i] = cdata[i] >> 8;
    282 		ciphertext[4 * i + 1] = cdata[i] & 0xff;
    283 		cdata[i] = cdata[i] >> 8;
    284 		ciphertext[4 * i + 0] = cdata[i] & 0xff;
    285 	}
    286 
    287 
    288 	i = 0;
    289 	encrypted[i++] = '$';
    290 	encrypted[i++] = BCRYPT_VERSION;
    291 	if (minor)
    292 		encrypted[i++] = minor;
    293 	encrypted[i++] = '$';
    294 
    295 	snprintf(encrypted + i, 4, "%2.2u$", logr);
    296 
    297 	encode_base64((u_int8_t *) encrypted + i + 3, csalt, BCRYPT_MAXSALT);
    298 	encode_base64((u_int8_t *) encrypted + strlen(encrypted), ciphertext,
    299 	    4 * BCRYPT_BLOCKS - 1);
    300 	return encrypted;
    301 }
    302 
    303 static void
    304 encode_base64(u_int8_t *buffer, u_int8_t *data, u_int16_t len)
    305 {
    306 	u_int8_t *bp = buffer;
    307 	u_int8_t *p = data;
    308 	u_int8_t c1, c2;
    309 	while (p < data + len) {
    310 		c1 = *p++;
    311 		*bp++ = Base64Code[(c1 >> 2)];
    312 		c1 = (c1 & 0x03) << 4;
    313 		if (p >= data + len) {
    314 			*bp++ = Base64Code[c1];
    315 			break;
    316 		}
    317 		c2 = *p++;
    318 		c1 |= (c2 >> 4) & 0x0f;
    319 		*bp++ = Base64Code[c1];
    320 		c1 = (c2 & 0x0f) << 2;
    321 		if (p >= data + len) {
    322 			*bp++ = Base64Code[c1];
    323 			break;
    324 		}
    325 		c2 = *p++;
    326 		c1 |= (c2 >> 6) & 0x03;
    327 		*bp++ = Base64Code[c1];
    328 		*bp++ = Base64Code[c2 & 0x3f];
    329 	}
    330 	*bp = '\0';
    331 }
    332 #if 0
    333 void
    334 main()
    335 {
    336 	char    blubber[73];
    337 	char    salt[100];
    338 	char   *p;
    339 	salt[0] = '$';
    340 	salt[1] = BCRYPT_VERSION;
    341 	salt[2] = '$';
    342 
    343 	snprintf(salt + 3, 4, "%2.2u$", 5);
    344 
    345 	printf("24 bytes of salt: ");
    346 	fgets(salt + 6, 94, stdin);
    347 	salt[99] = 0;
    348 	printf("72 bytes of password: ");
    349 	fpurge(stdin);
    350 	fgets(blubber, 73, stdin);
    351 	blubber[72] = 0;
    352 
    353 	p = crypt(blubber, salt);
    354 	printf("Passwd entry: %s\n\n", p);
    355 
    356 	p = bcrypt_gensalt(5);
    357 	printf("Generated salt: %s\n", p);
    358 	p = crypt(blubber, p);
    359 	printf("Passwd entry: %s\n", p);
    360 }
    361 #endif
    362