1 /*
2 * libwebsockets - small server side websockets and web server implementation
3 *
4 * Copyright (C) 2010 - 2019 Andy Green <andy@warmcat.com>
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 * IN THE SOFTWARE.
23 */
24
25 #include "libwebsockets.h"
26 #include "lws-ssh.h"
27
28 #include <string.h>
29
30 /*
31 * ssh-keygen -t ed25519
32 * head -n-1 srv-key-25519 | tail -n +2 | base64 -d | hexdump -C
33 */
34
35 static void
lws_sized_blob(uint8_t ** p,void * blob,uint32_t len)36 lws_sized_blob(uint8_t **p, void *blob, uint32_t len)
37 {
38 lws_p32((*p), len);
39 *p += 4;
40 memcpy(*p, blob, len);
41 *p += len;
42 }
43
44 static const char key_leadin[] = "openssh-key-v1\x00\x00\x00\x00\x04none"
45 "\x00\x00\x00\x04none\x00"
46 "\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x33"
47 "\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20",
48 key_sep[] = "\x00\x00\x00\x90\xb1\x4f\xa7\x28"
49 "\xb1\x4f\xa7\x28\x00\x00\x00\x0bssh-ed25519"
50 "\x00\x00\x00\x20",
51 key_privl[] = "\x00\x00\x00\x40",
52 key_trail[] = "\x00\x00\x00\x0cself-gen@cbl\x01";
53
54 static size_t
lws_gen_server_key_ed25519(struct lws_context * context,uint8_t * buf256,size_t max_len)55 lws_gen_server_key_ed25519(struct lws_context *context, uint8_t *buf256,
56 size_t max_len)
57 {
58 uint8_t *p = buf256 + sizeof(key_leadin) - 1;
59
60 if (max_len < sizeof(key_leadin) - 1 + 32 + sizeof(key_sep) - 1 + 32 +
61 sizeof(key_privl) - 1 + 64 + sizeof(key_trail) - 1)
62 return 0;
63
64 memcpy(buf256, key_leadin, sizeof(key_leadin) - 1);
65 crypto_sign_ed25519_keypair(context, p, p + 32 + sizeof(key_sep) - 1 +
66 32 + sizeof(key_privl) - 1);
67 memcpy(p + 32 + sizeof(key_sep) - 1, p, 32);
68 p += 32;
69 memcpy(p, key_sep, sizeof(key_sep) - 1);
70 p += sizeof(key_sep) - 1 + 32;
71 memcpy(p, key_privl, sizeof(key_privl) - 1);
72 p += sizeof(key_privl) - 1 + 64;
73 memcpy(p, key_trail, sizeof(key_trail) - 1);
74 p += sizeof(key_trail) - 1;
75
76 lwsl_notice("%s: Generated key len %ld\n", __func__, (long)(p - buf256));
77
78 return p - buf256;
79 }
80
81 static int
lws_mpint_rfc4251(uint8_t * dest,const uint8_t * src,int bytes,int uns)82 lws_mpint_rfc4251(uint8_t *dest, const uint8_t *src, int bytes, int uns)
83 {
84 uint8_t *odest = dest;
85
86 while (!*src && bytes > 1) {
87 src++;
88 bytes--;
89 }
90
91 if (!*src) {
92 *dest++ = 0;
93 *dest++ = 0;
94 *dest++ = 0;
95 *dest++ = 0;
96
97 return 4;
98 }
99
100 if (uns && (*src) & 0x80)
101 bytes++;
102
103 *dest++ = bytes >> 24;
104 *dest++ = bytes >> 16;
105 *dest++ = bytes >> 8;
106 *dest++ = bytes;
107
108 if (uns && (*src) & 0x80) {
109 *dest++ = 0;
110 bytes--;
111 }
112
113 while (bytes--)
114 *dest++ = *src++;
115
116 return lws_ptr_diff(dest, odest);
117 }
118
119 int
ed25519_key_parse(uint8_t * p,size_t len,char * type,size_t type_len,uint8_t * pub,uint8_t * pri)120 ed25519_key_parse(uint8_t *p, size_t len, char *type, size_t type_len,
121 uint8_t *pub, uint8_t *pri)
122 {
123 uint32_t l, publ, m;
124 uint8_t *op = p;
125
126 if (len < 180)
127 return 1;
128
129 if (memcmp(p, "openssh-key-v1", 14))
130 return 2;
131
132 p += 15;
133
134 l = lws_g32(&p); /* ciphername */
135 if (l != 4 || memcmp(p, "none", 4))
136 return 3;
137 p += l;
138
139 l = lws_g32(&p); /* kdfname */
140 if (l != 4 || memcmp(p, "none", 4))
141 return 4;
142 p += l;
143
144 l = lws_g32(&p); /* kdfoptions */
145 if (l)
146 return 5;
147
148 l = lws_g32(&p); /* number of keys */
149 if (l != 1)
150 return 6;
151
152 publ = lws_g32(&p); /* length of pubkey block */
153 if ((size_t)((p - op) + publ) >= len)
154 return 7;
155
156 l = lws_g32(&p); /* key type length */
157 if (l > 31)
158 return 8;
159 m = l;
160 if (m >= type_len)
161 m = (uint32_t)type_len -1 ;
162 lws_strncpy(type, (const char *)p, m + 1);
163
164 p += l;
165 l = lws_g32(&p); /* pub key length */
166 if (l != 32)
167 return 10;
168
169 p += l;
170
171 publ = lws_g32(&p); /* length of private key block */
172 if ((size_t)((p - op) + publ) != len)
173 return 11;
174
175 l = lws_g32(&p); /* checkint 1 */
176 if (lws_g32(&p) != l) /* must match checkint 2 */
177 return 12;
178
179 l = lws_g32(&p); /* key type length */
180
181 p += l;
182 l = lws_g32(&p); /* public key part length */
183 if (l != LWS_SIZE_EC25519_PUBKEY)
184 return 15;
185
186 if (pub)
187 memcpy(pub, p, LWS_SIZE_EC25519_PUBKEY);
188 p += l;
189 l = lws_g32(&p); /* private key part length */
190 if (l != LWS_SIZE_EC25519_PRIKEY)
191 return 16;
192
193 if (pri)
194 memcpy(pri, p, LWS_SIZE_EC25519_PRIKEY);
195
196 return 0;
197 }
198
199 static int
_genhash_update_len(struct lws_genhash_ctx * ctx,const void * input,size_t ilen)200 _genhash_update_len(struct lws_genhash_ctx *ctx, const void *input, size_t ilen)
201 {
202 uint32_t be;
203
204 lws_p32((uint8_t *)&be, (uint32_t)ilen);
205
206 if (lws_genhash_update(ctx, (uint8_t *)&be, 4))
207 return 1;
208 if (lws_genhash_update(ctx, input, ilen))
209 return 1;
210
211 return 0;
212 }
213
214 static int
kex_ecdh_dv(uint8_t * dest,int dest_len,const uint8_t * kbi,int kbi_len,const uint8_t * H,char c,const uint8_t * session_id)215 kex_ecdh_dv(uint8_t *dest, int dest_len, const uint8_t *kbi, int kbi_len,
216 const uint8_t *H, char c, const uint8_t *session_id)
217 {
218 uint8_t pool[LWS_SIZE_SHA256];
219 struct lws_genhash_ctx ctx;
220 int n = 0, m;
221
222 /*
223 * Key data MUST be taken from the beginning of the hash output.
224 * As many bytes as needed are taken from the beginning of the hash
225 * value.
226 *
227 * If the key length needed is longer than the output of the HASH,
228 * the key is extended by computing HASH of the concatenation of K
229 * and H and the entire key so far, and appending the resulting
230 * bytes (as many as HASH generates) to the key. This process is
231 * repeated until enough key material is available; the key is taken
232 * from the beginning of this value. In other words:
233 *
234 * K1 = HASH(K || H || X || session_id) (X is e.g., "A")
235 * K2 = HASH(K || H || K1)
236 * K3 = HASH(K || H || K1 || K2)
237 * ...
238 * key = K1 || K2 || K3 || ...
239 */
240
241 while (n < dest_len) {
242
243 if (lws_genhash_init(&ctx, LWS_GENHASH_TYPE_SHA256))
244 return 1;
245
246 if (lws_genhash_update(&ctx, kbi, kbi_len))
247 goto hash_failed;
248 if (lws_genhash_update(&ctx, H, LWS_SIZE_SHA256))
249 goto hash_failed;
250
251 if (!n) {
252 if (lws_genhash_update(&ctx, (void *)&c, 1))
253 goto hash_failed;
254 if (lws_genhash_update(&ctx, session_id,
255 LWS_SIZE_EC25519))
256 goto hash_failed;
257 } else
258 if (lws_genhash_update(&ctx, pool, LWS_SIZE_EC25519))
259 goto hash_failed;
260
261 lws_genhash_destroy(&ctx, pool);
262
263 m = LWS_SIZE_EC25519;
264 if (m > (dest_len - n))
265 m = dest_len - n;
266
267 memcpy(dest, pool, m);
268 n += m;
269 dest += m;
270 }
271
272 return 0;
273
274 hash_failed:
275 lws_genhash_destroy(&ctx, NULL);
276
277 return 1;
278 }
279
280
281 static const unsigned char basepoint[32] = { 9 };
282
283 size_t
get_gen_server_key_25519(struct per_session_data__sshd * pss,uint8_t * b,size_t len)284 get_gen_server_key_25519(struct per_session_data__sshd *pss, uint8_t *b,
285 size_t len)
286 {
287 size_t s, mylen;
288
289 mylen = pss->vhd->ops->get_server_key(pss->wsi, b, len);
290 if (mylen)
291 return mylen;
292
293 /* create one then */
294 lwsl_notice("Generating server hostkey\n");
295 s = lws_gen_server_key_ed25519(pss->vhd->context, b, len);
296 lwsl_notice(" gen key len %ld\n", (long)s);
297 if (!s)
298 return 0;
299 /* set the key */
300 if (!pss->vhd->ops->set_server_key(pss->wsi, b, s))
301 return 0;
302
303 /* new key stored OK */
304
305 return s;
306 }
307
308 int
kex_ecdh(struct per_session_data__sshd * pss,uint8_t * reply,uint32_t * plen)309 kex_ecdh(struct per_session_data__sshd *pss, uint8_t *reply, uint32_t *plen)
310 {
311 uint8_t pri_key[64], temp[64], payload_sig[64 + 32], a, *lp, kbi[64];
312 struct lws_kex *kex = pss->kex;
313 struct lws_genhash_ctx ctx;
314 unsigned long long smlen;
315 uint8_t *p = reply + 5;
316 uint32_t be, kbi_len;
317 uint8_t servkey[256];
318 char keyt[33];
319 int r, c;
320
321 r = (int)get_gen_server_key_25519(pss, servkey, (int)sizeof(servkey));
322 if (!r) {
323 lwsl_err("%s: Failed to get or gen server key\n", __func__);
324
325 return 1;
326 }
327
328 r = ed25519_key_parse(servkey, r, keyt, sizeof(keyt),
329 pss->K_S /* public key */, pri_key);
330 if (r) {
331 lwsl_notice("%s: server key parse failed: %d\n", __func__, r);
332
333 return 1;
334 }
335 keyt[32] = '\0';
336
337 lwsl_info("Server key type: %s\n", keyt);
338
339 /*
340 * 1) Generate ephemeral key pair [ eph_pri_key | kex->Q_S ]
341 * 2) Compute shared secret.
342 * 3) Generate and sign exchange hash.
343 *
344 * 1) A 32 bytes private key should be generated for each new
345 * connection, using a secure PRNG. The following actions
346 * must be done on the private key:
347 *
348 * mysecret[0] &= 248;
349 * mysecret[31] &= 127;
350 * mysecret[31] |= 64;
351 */
352 lws_get_random(pss->vhd->context, kex->eph_pri_key, LWS_SIZE_EC25519);
353 kex->eph_pri_key[0] &= 248;
354 kex->eph_pri_key[31] &= 127;
355 kex->eph_pri_key[31] |= 64;
356
357 /*
358 * 2) The public key is calculated using the cryptographic scalar
359 * multiplication:
360 *
361 * const unsigned char privkey[32];
362 * unsigned char pubkey[32];
363 *
364 * crypto_scalarmult (pubkey, privkey, basepoint);
365 */
366 crypto_scalarmult_curve25519(kex->Q_S, kex->eph_pri_key, basepoint);
367
368 a = 0;
369 for (r = 0; r < (int)sizeof(kex->Q_S); r++)
370 a |= kex->Q_S[r];
371 if (!a) {
372 lwsl_notice("all zero pubkey\n");
373 return SSH_DISCONNECT_KEY_EXCHANGE_FAILED;
374 }
375
376 /*
377 * The shared secret, k, is defined in SSH specifications to be a big
378 * integer. This number is calculated using the following procedure:
379 *
380 * X is the 32 bytes point obtained by the scalar multiplication of
381 * the other side's public key and the local private key scalar.
382 */
383 crypto_scalarmult_curve25519(pss->K, kex->eph_pri_key, kex->Q_C);
384
385 /*
386 * The whole 32 bytes of the number X are then converted into a big
387 * integer k. This conversion follows the network byte order. This
388 * step differs from RFC5656.
389 */
390 kbi_len = lws_mpint_rfc4251(kbi, pss->K, LWS_SIZE_EC25519, 1);
391
392 /*
393 * The exchange hash H is computed as the hash of the concatenation of
394 * the following:
395 *
396 * string V_C, the client's identification string (CR and LF
397 * excluded)
398 * string V_S, the server's identification string (CR and LF
399 * excluded)
400 * string I_C, the payload of the client's SSH_MSG_KEXINIT
401 * string I_S, the payload of the server's SSH_MSG_KEXINIT
402 * string K_S, the host key
403 * mpint Q_C, exchange value sent by the client
404 * mpint Q_S, exchange value sent by the server
405 * mpint K, the shared secret
406 *
407 * However there are a lot of unwritten details in the hash
408 * definition...
409 */
410
411 if (lws_genhash_init(&ctx, LWS_GENHASH_TYPE_SHA256)) {
412 lwsl_notice("genhash init failed\n");
413 return 1;
414 }
415
416 if (_genhash_update_len(&ctx, pss->V_C, strlen(pss->V_C)))
417 goto hash_probs;
418 if (_genhash_update_len(&ctx, pss->vhd->ops->server_string, /* aka V_S */
419 strlen(pss->vhd->ops->server_string)))
420 goto hash_probs;
421 if (_genhash_update_len(&ctx, kex->I_C, kex->I_C_payload_len))
422 goto hash_probs;
423 if (_genhash_update_len(&ctx, kex->I_S, kex->I_S_payload_len))
424 goto hash_probs;
425 /*
426 * K_S (host public key)
427 *
428 * sum of name + key lengths and headers
429 * name length: name
430 * key length: key
431 * ---> */
432 lws_p32((uint8_t *)&be, 8 + (int)strlen(keyt) + LWS_SIZE_EC25519);
433 if (lws_genhash_update(&ctx, (void *)&be, 4))
434 goto hash_probs;
435
436 if (_genhash_update_len(&ctx, keyt, strlen(keyt)))
437 goto hash_probs;
438 if (_genhash_update_len(&ctx, pss->K_S, LWS_SIZE_EC25519))
439 goto hash_probs;
440 /* <---- */
441
442 if (_genhash_update_len(&ctx, kex->Q_C, LWS_SIZE_EC25519))
443 goto hash_probs;
444 if (_genhash_update_len(&ctx, kex->Q_S, LWS_SIZE_EC25519))
445 goto hash_probs;
446
447 if (lws_genhash_update(&ctx, kbi, kbi_len))
448 goto hash_probs;
449
450 if (lws_genhash_destroy(&ctx, temp))
451 goto hash_probs;
452
453 /*
454 * Sign the 32-byte SHA256 "exchange hash" in temp
455 * The signature is itself 64 bytes
456 */
457 smlen = LWS_SIZE_EC25519 + 64;
458 if (crypto_sign_ed25519(payload_sig, &smlen, temp, LWS_SIZE_EC25519,
459 pri_key))
460 return 1;
461
462 #if 0
463 l = LWS_SIZE_EC25519;
464 n = crypto_sign_ed25519_open(temp, &l, payload_sig, smlen, pss->K_S);
465
466 lwsl_notice("own sig sanity check says %d\n", n);
467 #endif
468
469 /* sig [64] and payload [32] concatenated in payload_sig
470 *
471 * The server then responds with the following
472 *
473 * uint32 packet length (exl self + mac)
474 * byte padding len
475 * byte SSH_MSG_KEX_ECDH_REPLY
476 * string server public host key and certificates (K_S)
477 * string Q_S (exchange value sent by the server)
478 * string signature of H
479 * padding
480 */
481 *p++ = SSH_MSG_KEX_ECDH_REPLY;
482
483 /* server public host key and certificates (K_S) */
484
485 lp = p;
486 p +=4;
487 lws_sized_blob(&p, keyt, (int)strlen(keyt));
488 lws_sized_blob(&p, pss->K_S, LWS_SIZE_EC25519);
489 lws_p32(lp, lws_ptr_diff(p, lp) - 4);
490
491 /* Q_S (exchange value sent by the server) */
492
493 lws_sized_blob(&p, kex->Q_S, LWS_SIZE_EC25519);
494
495 /* signature of H */
496
497 lp = p;
498 p +=4;
499 lws_sized_blob(&p, keyt, (int)strlen(keyt));
500 lws_sized_blob(&p, payload_sig, 64);
501 lws_p32(lp, lws_ptr_diff(p, lp) - 4);
502
503 /* end of message */
504
505 lws_pad_set_length(pss, reply, &p, &pss->active_keys_stc);
506 *plen = lws_ptr_diff(p, reply);
507
508 if (!pss->active_keys_stc.valid)
509 memcpy(pss->session_id, temp, LWS_SIZE_EC25519);
510
511 /* RFC4253 7.2:
512 *
513 * The key exchange produces two values: a shared secret K,
514 * and an exchange hash H. Encryption and authentication
515 * keys are derived from these. The exchange hash H from the
516 * first key exchange is additionally used as the session
517 * identifier, which is a unique identifier for this connection.
518 * It is used by authentication methods as a part of the data
519 * that is signed as a proof of possession of a private key.
520 * Once computed, the session identifier is not changed,
521 * even if keys are later re-exchanged.
522 *
523 * The hash alg used in the KEX must be used for key derivation.
524 *
525 * 1) Initial IV client to server:
526 *
527 * HASH(K || H || "A" || session_id)
528 *
529 * (Here K is encoded as mpint and "A" as byte and session_id
530 * as raw data. "A" means the single character A, ASCII 65).
531 *
532 *
533 */
534 for (c = 0; c < 3; c++) {
535 kex_ecdh_dv(kex->keys_next_cts.key[c], LWS_SIZE_CHACHA256_KEY,
536 kbi, kbi_len, temp, 'A' + (c * 2), pss->session_id);
537 kex_ecdh_dv(kex->keys_next_stc.key[c], LWS_SIZE_CHACHA256_KEY,
538 kbi, kbi_len, temp, 'B' + (c * 2), pss->session_id);
539 }
540
541 lws_explicit_bzero(temp, sizeof(temp));
542
543 return 0;
544
545 hash_probs:
546 lws_genhash_destroy(&ctx, NULL);
547
548 return 1;
549 }
550