Home | History | Annotate | Line # | Download | only in libcrypt
bcrypt.c revision 1.20
      1 /*	$NetBSD: bcrypt.c,v 1.20 2020/03/25 18:36:29 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.20 2020/03/25 18:36:29 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 	(7 + (BCRYPT_MAXSALT * 4 + 2) / 3 + 2)
     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 u_int8_t *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 
     81 static const u_int8_t Base64Code[] =
     82 "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
     83 
     84 char *bcrypt_gensalt(u_int8_t);
     85 
     86 static const u_int8_t index_64[128] =
     87 {
     88 	255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
     89 	255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
     90 	255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
     91 	255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
     92 	255, 255, 255, 255, 255, 255, 0, 1, 54, 55,
     93 	56, 57, 58, 59, 60, 61, 62, 63, 255, 255,
     94 	255, 255, 255, 255, 255, 2, 3, 4, 5, 6,
     95 	7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
     96 	17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
     97 	255, 255, 255, 255, 255, 255, 28, 29, 30,
     98 	31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
     99 	41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
    100 	51, 52, 53, 255, 255, 255, 255, 255
    101 };
    102 #define CHAR64(c)  ( (c) > 127 ? 255 : index_64[(c)])
    103 
    104 static void
    105 decode_base64(u_int8_t *buffer, u_int16_t len, const u_int8_t *data)
    106 {
    107 	u_int8_t *bp = buffer;
    108 	const 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++ = ((u_int32_t)c1 << 2) | (((u_int32_t)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++ = (((u_int32_t)c2 & 0x0f) << 4) | (((uint32_t)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 	csalt = encode_base64((u_int8_t *) salt + 7, csalt, clen);
    150 	*csalt++ = '$';
    151 	*csalt = '\0';
    152 }
    153 
    154 int
    155 __gensalt_blowfish(char *salt, size_t saltlen, const char *option)
    156 {
    157 	size_t i;
    158 	u_int32_t seed = 0;
    159 	u_int8_t csalt[BCRYPT_MAXSALT];
    160 	unsigned long nrounds;
    161 	char *ep;
    162 
    163 	if (saltlen < BCRYPT_MAXSALTLEN) {
    164 		errno = ENOSPC;
    165 		return -1;
    166 	}
    167 	if (option == NULL) {
    168 		errno = EINVAL;
    169 		return -1;
    170 	}
    171 	nrounds = strtoul(option, &ep, 0);
    172 	if (option == ep || *ep) {
    173 		errno = EINVAL;
    174 		return -1;
    175 	}
    176 	if (errno == ERANGE && nrounds == ULONG_MAX)
    177 		return -1;
    178 
    179 	if (nrounds < 4)
    180 		nrounds = 4;
    181 	else if (nrounds > 31)
    182 		nrounds = 31;
    183 
    184 	for (i = 0; i < BCRYPT_MAXSALT; i++) {
    185 		if (i % 4 == 0)
    186 			seed = arc4random();
    187 		csalt[i] = seed & 0xff;
    188 		seed = seed >> 8;
    189 	}
    190 	encode_salt(salt, csalt, BCRYPT_MAXSALT, (u_int8_t)nrounds);
    191 	return 0;
    192 }
    193 
    194 /* Generates a salt for this version of crypt.
    195    Since versions may change. Keeping this here
    196    seems sensible.
    197    XXX: compat.
    198  */
    199 char *
    200 bcrypt_gensalt(u_int8_t log_rounds)
    201 {
    202 	static char gsalt[BCRYPT_MAXSALTLEN];
    203 	char num[10];
    204 
    205 	(void)snprintf(num, sizeof(num), "%d", log_rounds);
    206 	if (__gensalt_blowfish(gsalt, sizeof(gsalt), num) == -1)
    207 		return NULL;
    208 	return gsalt;
    209 }
    210 
    211 /* We handle $Vers$log2(NumRounds)$salt+passwd$
    212    i.e. $2$04$iwouldntknowwhattosayetKdJ6iFtacBqJdKe6aW7ou */
    213 
    214 char   *
    215 __bcrypt(const char *key, 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 	int n;
    225 	size_t len;
    226 
    227 	/* Discard "$" identifier */
    228 	salt++;
    229 
    230 	if (*salt > BCRYPT_VERSION)
    231 		return NULL;
    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 NULL;
    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 NULL;
    253 
    254 	/* Computer power doesn't increase linear, 2^x should be fine */
    255 	n = atoi(salt);
    256 	if (n > 31 || n < 0)
    257 		return NULL;
    258 	logr = (u_int8_t)n;
    259 	if ((rounds = (u_int32_t) 1 << logr) < BCRYPT_MINROUNDS)
    260 		return NULL;
    261 
    262 	/* Discard num rounds + "$" identifier */
    263 	salt += 3;
    264 
    265 	if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT)
    266 		return NULL;
    267 
    268 	/* We dont want the base64 salt but the raw data */
    269 	decode_base64(csalt, BCRYPT_MAXSALT, (const u_int8_t *)salt);
    270 	salt_len = BCRYPT_MAXSALT;
    271 	len = strlen(key);
    272 	if (len > 72)
    273 		key_len = 72;
    274 	else
    275 		key_len = (uint8_t)len;
    276 	key_len += minor >= 'a' ? 1 : 0;
    277 
    278 	/* Setting up S-Boxes and Subkeys */
    279 	Blowfish_initstate(&state);
    280 	Blowfish_expandstate(&state, csalt, salt_len,
    281 	    (const u_int8_t *) key, key_len);
    282 	for (k = 0; k < rounds; k++) {
    283 		Blowfish_expand0state(&state, (const u_int8_t *) key, key_len);
    284 		Blowfish_expand0state(&state, csalt, salt_len);
    285 	}
    286 
    287 	/* This can be precomputed later */
    288 	j = 0;
    289 	for (i = 0; i < BCRYPT_BLOCKS; i++)
    290 		cdata[i] = Blowfish_stream2word(ciphertext, 4 * BCRYPT_BLOCKS, &j);
    291 
    292 	/* Now do the encryption */
    293 	for (k = 0; k < 64; k++)
    294 		blf_enc(&state, cdata, BCRYPT_BLOCKS / 2);
    295 
    296 	for (i = 0; i < BCRYPT_BLOCKS; i++) {
    297 		ciphertext[4 * i + 3] = cdata[i] & 0xff;
    298 		cdata[i] = cdata[i] >> 8;
    299 		ciphertext[4 * i + 2] = cdata[i] & 0xff;
    300 		cdata[i] = cdata[i] >> 8;
    301 		ciphertext[4 * i + 1] = cdata[i] & 0xff;
    302 		cdata[i] = cdata[i] >> 8;
    303 		ciphertext[4 * i + 0] = cdata[i] & 0xff;
    304 	}
    305 
    306 
    307 	i = 0;
    308 	encrypted[i++] = '$';
    309 	encrypted[i++] = BCRYPT_VERSION;
    310 	if (minor)
    311 		encrypted[i++] = minor;
    312 	encrypted[i++] = '$';
    313 
    314 	snprintf(encrypted + i, 4, "%2.2u$", logr);
    315 
    316 	encode_base64((u_int8_t *) encrypted + i + 3, csalt, BCRYPT_MAXSALT);
    317 	encode_base64((u_int8_t *) encrypted + strlen(encrypted), ciphertext,
    318 	    4 * BCRYPT_BLOCKS - 1);
    319 	explicit_memset(&state, 0, sizeof(state));
    320 	return encrypted;
    321 }
    322 
    323 static u_int8_t *
    324 encode_base64(u_int8_t *buffer, u_int8_t *data, u_int16_t len)
    325 {
    326 	u_int8_t *bp = buffer;
    327 	u_int8_t *p = data;
    328 	u_int8_t c1, c2;
    329 	while (p < data + len) {
    330 		c1 = *p++;
    331 		*bp++ = Base64Code[((u_int32_t)c1 >> 2)];
    332 		c1 = (c1 & 0x03) << 4;
    333 		if (p >= data + len) {
    334 			*bp++ = Base64Code[c1];
    335 			break;
    336 		}
    337 		c2 = *p++;
    338 		c1 |= ((u_int32_t)c2 >> 4) & 0x0f;
    339 		*bp++ = Base64Code[c1];
    340 		c1 = (c2 & 0x0f) << 2;
    341 		if (p >= data + len) {
    342 			*bp++ = Base64Code[c1];
    343 			break;
    344 		}
    345 		c2 = *p++;
    346 		c1 |= ((u_int32_t)c2 >> 6) & 0x03;
    347 		*bp++ = Base64Code[c1];
    348 		*bp++ = Base64Code[c2 & 0x3f];
    349 	}
    350 	*bp = '\0';
    351 	return bp;
    352 }
    353 #if 0
    354 void
    355 main()
    356 {
    357 	char    blubber[73];
    358 	char    salt[100];
    359 	char   *p;
    360 	salt[0] = '$';
    361 	salt[1] = BCRYPT_VERSION;
    362 	salt[2] = '$';
    363 
    364 	snprintf(salt + 3, 4, "%2.2u$", 5);
    365 
    366 	printf("24 bytes of salt: ");
    367 	fgets(salt + 6, 94, stdin);
    368 	salt[99] = 0;
    369 	printf("72 bytes of password: ");
    370 	fpurge(stdin);
    371 	fgets(blubber, 73, stdin);
    372 	blubber[72] = 0;
    373 
    374 	p = crypt(blubber, salt);
    375 	printf("Passwd entry: %s\n\n", p);
    376 
    377 	p = bcrypt_gensalt(5);
    378 	printf("Generated salt: %s\n", p);
    379 	p = crypt(blubber, p);
    380 	printf("Passwd entry: %s\n", p);
    381 }
    382 #endif
    383