1 /*
2  * Copyright (c) 2013 Ted Unangst <tedu@openbsd.org>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 
17 #include <sys/types.h>
18 #include <stdlib.h>
19 #include <string.h>
20 
21 #include "openbsd-blowfish.h"
22 #include "bcrypt.h"
23 #include "crypto.h"
24 
25 #define	MINIMUM(a,b) (((a) < (b)) ? (a) : (b))
26 
27 /*
28  * pkcs #5 pbkdf2 implementation using the "bcrypt" hash
29  *
30  * The bcrypt hash function is derived from the bcrypt password hashing
31  * function with the following modifications:
32  * 1. The input password and salt are preprocessed with SHA512.
33  * 2. The output length is expanded to 256 bits.
34  * 3. Subsequently the magic string to be encrypted is lengthened and modifed
35  *    to "OxychromaticBlowfishSwatDynamite"
36  * 4. The hash function is defined to perform 64 rounds of initial state
37  *    expansion. (More rounds are performed by iterating the hash.)
38  *
39  * Note that this implementation pulls the SHA512 operations into the caller
40  * as a performance optimization.
41  *
42  * One modification from official pbkdf2. Instead of outputting key material
43  * linearly, we mix it. pbkdf2 has a known weakness where if one uses it to
44  * generate (e.g.) 512 bits of key material for use as two 256 bit keys, an
45  * attacker can merely run once through the outer loop, but the user
46  * always runs it twice. Shuffling output bytes requires computing the
47  * entirety of the key material to assemble any subkey. This is something a
48  * wise caller could do; we just do it for you.
49  */
50 
51 #define BCRYPT_WORDS 8
52 #define BCRYPT_HASHSIZE (BCRYPT_WORDS * 4)
53 
54 static void
bcrypt_hash(uint8_t * sha2pass,uint8_t * sha2salt,uint8_t * out)55 bcrypt_hash(uint8_t *sha2pass, uint8_t *sha2salt, uint8_t *out)
56 {
57 	blf_ctx state;
58 	uint8_t ciphertext[BCRYPT_HASHSIZE] =
59 	    "OxychromaticBlowfishSwatDynamite";
60 	uint32_t cdata[BCRYPT_WORDS];
61 	int i;
62 	uint16_t j;
63 	size_t shalen = SHA512_DIGEST_LENGTH;
64 
65 	/* key expansion */
66 	Blowfish_initstate(&state);
67 	Blowfish_expandstate(&state, sha2salt, shalen, sha2pass, shalen);
68 	for (i = 0; i < 64; i++) {
69 		Blowfish_expand0state(&state, sha2salt, shalen);
70 		Blowfish_expand0state(&state, sha2pass, shalen);
71 	}
72 
73 	/* encryption */
74 	j = 0;
75 	for (i = 0; i < BCRYPT_WORDS; i++)
76 		cdata[i] = Blowfish_stream2word(ciphertext, sizeof(ciphertext),
77 		    &j);
78 	for (i = 0; i < 64; i++)
79 		blf_enc(&state, cdata, sizeof(cdata) / sizeof(uint64_t));
80 
81 	/* copy out */
82 	for (i = 0; i < BCRYPT_WORDS; i++) {
83 		out[4 * i + 3] = (cdata[i] >> 24) & 0xff;
84 		out[4 * i + 2] = (cdata[i] >> 16) & 0xff;
85 		out[4 * i + 1] = (cdata[i] >> 8) & 0xff;
86 		out[4 * i + 0] = cdata[i] & 0xff;
87 	}
88 
89 	/* zap */
90 	pr_memscrub(ciphertext, sizeof(ciphertext));
91 	pr_memscrub(cdata, sizeof(cdata));
92 	pr_memscrub(&state, sizeof(state));
93 }
94 
95 static int
bcrypt_pbkdf(const char * pass,size_t passlen,const uint8_t * salt,size_t saltlen,uint8_t * key,size_t keylen,unsigned int rounds)96 bcrypt_pbkdf(const char *pass, size_t passlen, const uint8_t *salt, size_t saltlen,
97     uint8_t *key, size_t keylen, unsigned int rounds)
98 {
99 	SHA512_CTX ctx;
100 	uint8_t sha2pass[SHA512_DIGEST_LENGTH];
101 	uint8_t sha2salt[SHA512_DIGEST_LENGTH];
102 	uint8_t out[BCRYPT_HASHSIZE];
103 	uint8_t tmpout[BCRYPT_HASHSIZE];
104 	uint8_t countsalt[4];
105 	size_t i, j, amt, stride;
106 	uint32_t count;
107 	size_t origkeylen = keylen;
108 
109 	/* nothing crazy */
110 	if (rounds < 1)
111 		return -1;
112 	if (passlen == 0 || saltlen == 0 || keylen == 0 ||
113 	    keylen > sizeof(out) * sizeof(out))
114 		return -1;
115 	stride = (keylen + sizeof(out) - 1) / sizeof(out);
116 	amt = (keylen + stride - 1) / stride;
117 
118 	/* collapse password */
119 	SHA512_Init(&ctx);
120 	SHA512_Update(&ctx, pass, passlen);
121 	SHA512_Final(sha2pass, &ctx);
122 
123 
124 	/* generate key, sizeof(out) at a time */
125 	for (count = 1; keylen > 0; count++) {
126 		countsalt[0] = (count >> 24) & 0xff;
127 		countsalt[1] = (count >> 16) & 0xff;
128 		countsalt[2] = (count >> 8) & 0xff;
129 		countsalt[3] = count & 0xff;
130 
131 		/* first round, salt is salt */
132 		SHA512_Init(&ctx);
133 		SHA512_Update(&ctx, salt, saltlen);
134 		SHA512_Update(&ctx, countsalt, sizeof(countsalt));
135 		SHA512_Final(sha2salt, &ctx);
136 		bcrypt_hash(sha2pass, sha2salt, tmpout);
137 		memcpy(out, tmpout, sizeof(out));
138 
139 		for (i = 1; i < rounds; i++) {
140 			/* subsequent rounds, salt is previous output */
141 			SHA512_Init(&ctx);
142 			SHA512_Update(&ctx, tmpout, sizeof(tmpout));
143 			SHA512_Final(sha2salt, &ctx);
144 			bcrypt_hash(sha2pass, sha2salt, tmpout);
145 			for (j = 0; j < sizeof(out); j++)
146 				out[j] ^= tmpout[j];
147 		}
148 
149 		/*
150 		 * pbkdf2 deviation: output the key material non-linearly.
151 		 */
152 		amt = MINIMUM(amt, keylen);
153 		for (i = 0; i < amt; i++) {
154 			size_t dest = i * stride + (count - 1);
155 			if (dest >= origkeylen)
156 				break;
157 			key[dest] = out[i];
158 		}
159 		keylen -= i;
160 	}
161 
162 	/* zap */
163 	pr_memscrub(&ctx, sizeof(ctx));
164 	pr_memscrub(out, sizeof(out));
165 
166 	return 0;
167 }
168 
169 static const char *trace_channel = "sftp.bcrypt";
170 
sftp_bcrypt_pbkdf2(pool * p,const char * passphrase,size_t passphrase_len,unsigned char * salt,uint32_t salt_len,uint32_t rounds,unsigned char * key,uint32_t key_len)171 int sftp_bcrypt_pbkdf2(pool *p, const char *passphrase,
172     size_t passphrase_len, unsigned char *salt, uint32_t salt_len,
173     uint32_t rounds, unsigned char *key, uint32_t key_len) {
174   int res = 0;
175 
176   if (p == NULL ||
177       passphrase == NULL ||
178       salt == NULL) {
179     errno = EINVAL;
180     return -1;
181   }
182 
183   if (rounds < 1) {
184     pr_trace_msg(trace_channel, 4, "invalid rounds (%lu) for bcrypt KDF",
185       (unsigned long) rounds);
186     errno = EINVAL;
187     return -1;
188   }
189 
190   if (passphrase_len == 0 ||
191       salt_len == 0 ||
192       key_len == 0) {
193     pr_trace_msg(trace_channel, 4,
194       "invalid bcrypt KDF data: passphrase (%lu bytes), salt (%lu bytes), "
195       "or key (%lu bytes)", (unsigned long) passphrase_len,
196       (unsigned long) salt_len, (unsigned long) key_len);
197     errno = EINVAL;
198     return -1;
199   }
200 
201   if (key_len < SFTP_BCRYPT_DIGEST_LEN) {
202     pr_trace_msg(trace_channel, 4,
203       "invalid bcrypt KDF data: key (%lu bytes) too short; need at "
204       "least %lu bytes", (unsigned long) key_len,
205       (unsigned long) SFTP_BCRYPT_DIGEST_LEN);
206     errno = EINVAL;
207     return -1;
208   }
209 
210   res = bcrypt_pbkdf(passphrase, passphrase_len, salt, salt_len, key, key_len,
211     rounds);
212   if (res < 0) {
213     errno = EINVAL;
214     return -1;
215   }
216 
217   return 0;
218 }
219