kex.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578
  1. /* $OpenBSD: kex.c,v 1.159 2020/07/05 23:59:45 djm Exp $ */
  2. /*
  3. * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. *
  14. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  15. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  16. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  17. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  18. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  19. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  20. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  21. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  22. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  23. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. #include "includes.h"
  26. #include <sys/types.h>
  27. #include <errno.h>
  28. #include <signal.h>
  29. #include <stdarg.h>
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include <unistd.h>
  34. #ifdef HAVE_POLL_H
  35. #include <poll.h>
  36. #endif
  37. #ifdef WITH_OPENSSL
  38. #include <openssl/crypto.h>
  39. #include <openssl/dh.h>
  40. # ifdef HAVE_EVP_KDF_CTX_NEW_ID
  41. # include <openssl/kdf.h>
  42. # endif
  43. #endif
  44. #include "ssh.h"
  45. #include "ssh2.h"
  46. #include "atomicio.h"
  47. #include "version.h"
  48. #include "packet.h"
  49. #include "compat.h"
  50. #include "cipher.h"
  51. #include "sshkey.h"
  52. #include "kex.h"
  53. #include "log.h"
  54. #include "mac.h"
  55. #include "match.h"
  56. #include "misc.h"
  57. #include "dispatch.h"
  58. #include "monitor.h"
  59. #include "ssherr.h"
  60. #include "sshbuf.h"
  61. #include "canohost.h"
  62. #include "digest.h"
  63. #include "audit.h"
  64. /* prototype */
  65. static int kex_choose_conf(struct ssh *);
  66. static int kex_input_newkeys(int, u_int32_t, struct ssh *);
  67. static const char *proposal_names[PROPOSAL_MAX] = {
  68. "KEX algorithms",
  69. "host key algorithms",
  70. "ciphers ctos",
  71. "ciphers stoc",
  72. "MACs ctos",
  73. "MACs stoc",
  74. "compression ctos",
  75. "compression stoc",
  76. "languages ctos",
  77. "languages stoc",
  78. };
  79. struct kexalg {
  80. char *name;
  81. u_int type;
  82. int ec_nid;
  83. int hash_alg;
  84. };
  85. static const struct kexalg kexalgs[] = {
  86. #ifdef WITH_OPENSSL
  87. { KEX_DH1, KEX_DH_GRP1_SHA1, 0, SSH_DIGEST_SHA1 },
  88. { KEX_DH14_SHA1, KEX_DH_GRP14_SHA1, 0, SSH_DIGEST_SHA1 },
  89. { KEX_DH14_SHA256, KEX_DH_GRP14_SHA256, 0, SSH_DIGEST_SHA256 },
  90. { KEX_DH16_SHA512, KEX_DH_GRP16_SHA512, 0, SSH_DIGEST_SHA512 },
  91. { KEX_DH18_SHA512, KEX_DH_GRP18_SHA512, 0, SSH_DIGEST_SHA512 },
  92. { KEX_DHGEX_SHA1, KEX_DH_GEX_SHA1, 0, SSH_DIGEST_SHA1 },
  93. #ifdef HAVE_EVP_SHA256
  94. { KEX_DHGEX_SHA256, KEX_DH_GEX_SHA256, 0, SSH_DIGEST_SHA256 },
  95. #endif /* HAVE_EVP_SHA256 */
  96. #ifdef OPENSSL_HAS_ECC
  97. { KEX_ECDH_SHA2_NISTP256, KEX_ECDH_SHA2,
  98. NID_X9_62_prime256v1, SSH_DIGEST_SHA256 },
  99. { KEX_ECDH_SHA2_NISTP384, KEX_ECDH_SHA2, NID_secp384r1,
  100. SSH_DIGEST_SHA384 },
  101. # ifdef OPENSSL_HAS_NISTP521
  102. { KEX_ECDH_SHA2_NISTP521, KEX_ECDH_SHA2, NID_secp521r1,
  103. SSH_DIGEST_SHA512 },
  104. # endif /* OPENSSL_HAS_NISTP521 */
  105. #endif /* OPENSSL_HAS_ECC */
  106. #endif /* WITH_OPENSSL */
  107. #if defined(HAVE_EVP_SHA256) || !defined(WITH_OPENSSL)
  108. { KEX_CURVE25519_SHA256, KEX_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
  109. { KEX_CURVE25519_SHA256_OLD, KEX_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
  110. #ifdef USE_SNTRUP761X25519
  111. { KEX_SNTRUP761X25519_SHA512, KEX_KEM_SNTRUP761X25519_SHA512, 0,
  112. SSH_DIGEST_SHA512 },
  113. #endif
  114. #endif /* HAVE_EVP_SHA256 || !WITH_OPENSSL */
  115. { NULL, 0, -1, -1},
  116. };
  117. char *
  118. kex_alg_list(char sep)
  119. {
  120. char *ret = NULL, *tmp;
  121. size_t nlen, rlen = 0;
  122. const struct kexalg *k;
  123. for (k = kexalgs; k->name != NULL; k++) {
  124. if (ret != NULL)
  125. ret[rlen++] = sep;
  126. nlen = strlen(k->name);
  127. if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
  128. free(ret);
  129. return NULL;
  130. }
  131. ret = tmp;
  132. memcpy(ret + rlen, k->name, nlen + 1);
  133. rlen += nlen;
  134. }
  135. return ret;
  136. }
  137. static const struct kexalg *
  138. kex_alg_by_name(const char *name)
  139. {
  140. const struct kexalg *k;
  141. for (k = kexalgs; k->name != NULL; k++) {
  142. if (strcmp(k->name, name) == 0)
  143. return k;
  144. }
  145. return NULL;
  146. }
  147. /* Validate KEX method name list */
  148. int
  149. kex_names_valid(const char *names)
  150. {
  151. char *s, *cp, *p;
  152. if (names == NULL || strcmp(names, "") == 0)
  153. return 0;
  154. if ((s = cp = strdup(names)) == NULL)
  155. return 0;
  156. for ((p = strsep(&cp, ",")); p && *p != '\0';
  157. (p = strsep(&cp, ","))) {
  158. if (kex_alg_by_name(p) == NULL) {
  159. error("Unsupported KEX algorithm \"%.100s\"", p);
  160. free(s);
  161. return 0;
  162. }
  163. }
  164. debug3("kex names ok: [%s]", names);
  165. free(s);
  166. return 1;
  167. }
  168. /*
  169. * Concatenate algorithm names, avoiding duplicates in the process.
  170. * Caller must free returned string.
  171. */
  172. char *
  173. kex_names_cat(const char *a, const char *b)
  174. {
  175. char *ret = NULL, *tmp = NULL, *cp, *p, *m;
  176. size_t len;
  177. if (a == NULL || *a == '\0')
  178. return strdup(b);
  179. if (b == NULL || *b == '\0')
  180. return strdup(a);
  181. if (strlen(b) > 1024*1024)
  182. return NULL;
  183. len = strlen(a) + strlen(b) + 2;
  184. if ((tmp = cp = strdup(b)) == NULL ||
  185. (ret = calloc(1, len)) == NULL) {
  186. free(tmp);
  187. return NULL;
  188. }
  189. strlcpy(ret, a, len);
  190. for ((p = strsep(&cp, ",")); p && *p != '\0'; (p = strsep(&cp, ","))) {
  191. if ((m = match_list(ret, p, NULL)) != NULL) {
  192. free(m);
  193. continue; /* Algorithm already present */
  194. }
  195. if (strlcat(ret, ",", len) >= len ||
  196. strlcat(ret, p, len) >= len) {
  197. free(tmp);
  198. free(ret);
  199. return NULL; /* Shouldn't happen */
  200. }
  201. }
  202. free(tmp);
  203. return ret;
  204. }
  205. /*
  206. * Assemble a list of algorithms from a default list and a string from a
  207. * configuration file. The user-provided string may begin with '+' to
  208. * indicate that it should be appended to the default, '-' that the
  209. * specified names should be removed, or '^' that they should be placed
  210. * at the head.
  211. */
  212. int
  213. kex_assemble_names(char **listp, const char *def, const char *all)
  214. {
  215. char *cp, *tmp, *patterns;
  216. char *list = NULL, *ret = NULL, *matching = NULL, *opatterns = NULL;
  217. int r = SSH_ERR_INTERNAL_ERROR;
  218. if (listp == NULL || def == NULL || all == NULL)
  219. return SSH_ERR_INVALID_ARGUMENT;
  220. if (*listp == NULL || **listp == '\0') {
  221. if ((*listp = strdup(def)) == NULL)
  222. return SSH_ERR_ALLOC_FAIL;
  223. return 0;
  224. }
  225. list = *listp;
  226. *listp = NULL;
  227. if (*list == '+') {
  228. /* Append names to default list */
  229. if ((tmp = kex_names_cat(def, list + 1)) == NULL) {
  230. r = SSH_ERR_ALLOC_FAIL;
  231. goto fail;
  232. }
  233. free(list);
  234. list = tmp;
  235. } else if (*list == '-') {
  236. /* Remove names from default list */
  237. if ((*listp = match_filter_denylist(def, list + 1)) == NULL) {
  238. r = SSH_ERR_ALLOC_FAIL;
  239. goto fail;
  240. }
  241. free(list);
  242. /* filtering has already been done */
  243. return 0;
  244. } else if (*list == '^') {
  245. /* Place names at head of default list */
  246. if ((tmp = kex_names_cat(list + 1, def)) == NULL) {
  247. r = SSH_ERR_ALLOC_FAIL;
  248. goto fail;
  249. }
  250. free(list);
  251. list = tmp;
  252. } else {
  253. /* Explicit list, overrides default - just use "list" as is */
  254. }
  255. /*
  256. * The supplied names may be a pattern-list. For the -list case,
  257. * the patterns are applied above. For the +list and explicit list
  258. * cases we need to do it now.
  259. */
  260. ret = NULL;
  261. if ((patterns = opatterns = strdup(list)) == NULL) {
  262. r = SSH_ERR_ALLOC_FAIL;
  263. goto fail;
  264. }
  265. /* Apply positive (i.e. non-negated) patterns from the list */
  266. while ((cp = strsep(&patterns, ",")) != NULL) {
  267. if (*cp == '!') {
  268. /* negated matches are not supported here */
  269. r = SSH_ERR_INVALID_ARGUMENT;
  270. goto fail;
  271. }
  272. free(matching);
  273. if ((matching = match_filter_allowlist(all, cp)) == NULL) {
  274. r = SSH_ERR_ALLOC_FAIL;
  275. goto fail;
  276. }
  277. if ((tmp = kex_names_cat(ret, matching)) == NULL) {
  278. r = SSH_ERR_ALLOC_FAIL;
  279. goto fail;
  280. }
  281. free(ret);
  282. ret = tmp;
  283. }
  284. if (ret == NULL || *ret == '\0') {
  285. /* An empty name-list is an error */
  286. /* XXX better error code? */
  287. r = SSH_ERR_INVALID_ARGUMENT;
  288. goto fail;
  289. }
  290. /* success */
  291. *listp = ret;
  292. ret = NULL;
  293. r = 0;
  294. fail:
  295. free(matching);
  296. free(opatterns);
  297. free(list);
  298. free(ret);
  299. return r;
  300. }
  301. /* put algorithm proposal into buffer */
  302. int
  303. kex_prop2buf(struct sshbuf *b, char *proposal[PROPOSAL_MAX])
  304. {
  305. u_int i;
  306. int r;
  307. sshbuf_reset(b);
  308. /*
  309. * add a dummy cookie, the cookie will be overwritten by
  310. * kex_send_kexinit(), each time a kexinit is set
  311. */
  312. for (i = 0; i < KEX_COOKIE_LEN; i++) {
  313. if ((r = sshbuf_put_u8(b, 0)) != 0)
  314. return r;
  315. }
  316. for (i = 0; i < PROPOSAL_MAX; i++) {
  317. if ((r = sshbuf_put_cstring(b, proposal[i])) != 0)
  318. return r;
  319. }
  320. if ((r = sshbuf_put_u8(b, 0)) != 0 || /* first_kex_packet_follows */
  321. (r = sshbuf_put_u32(b, 0)) != 0) /* uint32 reserved */
  322. return r;
  323. return 0;
  324. }
  325. /* parse buffer and return algorithm proposal */
  326. int
  327. kex_buf2prop(struct sshbuf *raw, int *first_kex_follows, char ***propp)
  328. {
  329. struct sshbuf *b = NULL;
  330. u_char v;
  331. u_int i;
  332. char **proposal = NULL;
  333. int r;
  334. *propp = NULL;
  335. if ((proposal = calloc(PROPOSAL_MAX, sizeof(char *))) == NULL)
  336. return SSH_ERR_ALLOC_FAIL;
  337. if ((b = sshbuf_fromb(raw)) == NULL) {
  338. r = SSH_ERR_ALLOC_FAIL;
  339. goto out;
  340. }
  341. if ((r = sshbuf_consume(b, KEX_COOKIE_LEN)) != 0) { /* skip cookie */
  342. error("%s: consume cookie: %s", __func__, ssh_err(r));
  343. goto out;
  344. }
  345. /* extract kex init proposal strings */
  346. for (i = 0; i < PROPOSAL_MAX; i++) {
  347. if ((r = sshbuf_get_cstring(b, &(proposal[i]), NULL)) != 0) {
  348. error("%s: parse proposal %u: %s", __func__,
  349. i, ssh_err(r));
  350. goto out;
  351. }
  352. debug2("%s: %s", proposal_names[i], proposal[i]);
  353. }
  354. /* first kex follows / reserved */
  355. if ((r = sshbuf_get_u8(b, &v)) != 0 || /* first_kex_follows */
  356. (r = sshbuf_get_u32(b, &i)) != 0) { /* reserved */
  357. error("%s: parse: %s", __func__, ssh_err(r));
  358. goto out;
  359. }
  360. if (first_kex_follows != NULL)
  361. *first_kex_follows = v;
  362. debug2("first_kex_follows %d ", v);
  363. debug2("reserved %u ", i);
  364. r = 0;
  365. *propp = proposal;
  366. out:
  367. if (r != 0 && proposal != NULL)
  368. kex_prop_free(proposal);
  369. sshbuf_free(b);
  370. return r;
  371. }
  372. void
  373. kex_prop_free(char **proposal)
  374. {
  375. u_int i;
  376. if (proposal == NULL)
  377. return;
  378. for (i = 0; i < PROPOSAL_MAX; i++)
  379. free(proposal[i]);
  380. free(proposal);
  381. }
  382. /* ARGSUSED */
  383. int
  384. kex_protocol_error(int type, u_int32_t seq, struct ssh *ssh)
  385. {
  386. int r;
  387. error("kex protocol error: type %d seq %u", type, seq);
  388. if ((r = sshpkt_start(ssh, SSH2_MSG_UNIMPLEMENTED)) != 0 ||
  389. (r = sshpkt_put_u32(ssh, seq)) != 0 ||
  390. (r = sshpkt_send(ssh)) != 0)
  391. return r;
  392. return 0;
  393. }
  394. static void
  395. kex_reset_dispatch(struct ssh *ssh)
  396. {
  397. ssh_dispatch_range(ssh, SSH2_MSG_TRANSPORT_MIN,
  398. SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
  399. }
  400. static int
  401. kex_send_ext_info(struct ssh *ssh)
  402. {
  403. int r;
  404. char *algs;
  405. debug("Sending SSH2_MSG_EXT_INFO");
  406. if ((algs = sshkey_alg_list(0, 1, 1, ',')) == NULL)
  407. return SSH_ERR_ALLOC_FAIL;
  408. /* XXX filter algs list by allowed pubkey/hostbased types */
  409. if ((r = sshpkt_start(ssh, SSH2_MSG_EXT_INFO)) != 0 ||
  410. (r = sshpkt_put_u32(ssh, 1)) != 0 ||
  411. (r = sshpkt_put_cstring(ssh, "server-sig-algs")) != 0 ||
  412. (r = sshpkt_put_cstring(ssh, algs)) != 0 ||
  413. (r = sshpkt_send(ssh)) != 0) {
  414. error("%s: compose: %s", __func__, ssh_err(r));
  415. goto out;
  416. }
  417. /* success */
  418. r = 0;
  419. out:
  420. free(algs);
  421. return r;
  422. }
  423. int
  424. kex_send_newkeys(struct ssh *ssh)
  425. {
  426. int r;
  427. kex_reset_dispatch(ssh);
  428. if ((r = sshpkt_start(ssh, SSH2_MSG_NEWKEYS)) != 0 ||
  429. (r = sshpkt_send(ssh)) != 0)
  430. return r;
  431. debug("SSH2_MSG_NEWKEYS sent");
  432. ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_input_newkeys);
  433. if (ssh->kex->ext_info_c && (ssh->kex->flags & KEX_INITIAL) != 0)
  434. if ((r = kex_send_ext_info(ssh)) != 0)
  435. return r;
  436. debug("expecting SSH2_MSG_NEWKEYS");
  437. return 0;
  438. }
  439. int
  440. kex_input_ext_info(int type, u_int32_t seq, struct ssh *ssh)
  441. {
  442. struct kex *kex = ssh->kex;
  443. u_int32_t i, ninfo;
  444. char *name;
  445. u_char *val;
  446. size_t vlen;
  447. int r;
  448. debug("SSH2_MSG_EXT_INFO received");
  449. ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &kex_protocol_error);
  450. if ((r = sshpkt_get_u32(ssh, &ninfo)) != 0)
  451. return r;
  452. for (i = 0; i < ninfo; i++) {
  453. if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0)
  454. return r;
  455. if ((r = sshpkt_get_string(ssh, &val, &vlen)) != 0) {
  456. free(name);
  457. return r;
  458. }
  459. if (strcmp(name, "server-sig-algs") == 0) {
  460. /* Ensure no \0 lurking in value */
  461. if (memchr(val, '\0', vlen) != NULL) {
  462. error("%s: nul byte in %s", __func__, name);
  463. return SSH_ERR_INVALID_FORMAT;
  464. }
  465. debug("%s: %s=<%s>", __func__, name, val);
  466. kex->server_sig_algs = val;
  467. val = NULL;
  468. } else
  469. debug("%s: %s (unrecognised)", __func__, name);
  470. free(name);
  471. free(val);
  472. }
  473. return sshpkt_get_end(ssh);
  474. }
  475. static int
  476. kex_input_newkeys(int type, u_int32_t seq, struct ssh *ssh)
  477. {
  478. struct kex *kex = ssh->kex;
  479. int r;
  480. debug("SSH2_MSG_NEWKEYS received");
  481. ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error);
  482. ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
  483. if ((r = sshpkt_get_end(ssh)) != 0)
  484. return r;
  485. if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0)
  486. return r;
  487. kex->done = 1;
  488. kex->flags &= ~KEX_INITIAL;
  489. sshbuf_reset(kex->peer);
  490. /* sshbuf_reset(kex->my); */
  491. kex->flags &= ~KEX_INIT_SENT;
  492. free(kex->name);
  493. kex->name = NULL;
  494. return 0;
  495. }
  496. int
  497. kex_send_kexinit(struct ssh *ssh)
  498. {
  499. u_char *cookie;
  500. struct kex *kex = ssh->kex;
  501. int r;
  502. if (kex == NULL) {
  503. error("%s: no kex", __func__);
  504. return SSH_ERR_INTERNAL_ERROR;
  505. }
  506. if (kex->flags & KEX_INIT_SENT)
  507. return 0;
  508. kex->done = 0;
  509. /* generate a random cookie */
  510. if (sshbuf_len(kex->my) < KEX_COOKIE_LEN) {
  511. error("%s: bad kex length: %zu < %d", __func__,
  512. sshbuf_len(kex->my), KEX_COOKIE_LEN);
  513. return SSH_ERR_INVALID_FORMAT;
  514. }
  515. if ((cookie = sshbuf_mutable_ptr(kex->my)) == NULL) {
  516. error("%s: buffer error", __func__);
  517. return SSH_ERR_INTERNAL_ERROR;
  518. }
  519. arc4random_buf(cookie, KEX_COOKIE_LEN);
  520. if ((r = sshpkt_start(ssh, SSH2_MSG_KEXINIT)) != 0 ||
  521. (r = sshpkt_putb(ssh, kex->my)) != 0 ||
  522. (r = sshpkt_send(ssh)) != 0) {
  523. error("%s: compose reply: %s", __func__, ssh_err(r));
  524. return r;
  525. }
  526. debug("SSH2_MSG_KEXINIT sent");
  527. kex->flags |= KEX_INIT_SENT;
  528. return 0;
  529. }
  530. /* ARGSUSED */
  531. int
  532. kex_input_kexinit(int type, u_int32_t seq, struct ssh *ssh)
  533. {
  534. struct kex *kex = ssh->kex;
  535. const u_char *ptr;
  536. u_int i;
  537. size_t dlen;
  538. int r;
  539. debug("SSH2_MSG_KEXINIT received");
  540. if (kex == NULL) {
  541. error("%s: no kex", __func__);
  542. return SSH_ERR_INTERNAL_ERROR;
  543. }
  544. ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, NULL);
  545. ptr = sshpkt_ptr(ssh, &dlen);
  546. if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0)
  547. return r;
  548. /* discard packet */
  549. for (i = 0; i < KEX_COOKIE_LEN; i++) {
  550. if ((r = sshpkt_get_u8(ssh, NULL)) != 0) {
  551. error("%s: discard cookie: %s", __func__, ssh_err(r));
  552. return r;
  553. }
  554. }
  555. for (i = 0; i < PROPOSAL_MAX; i++) {
  556. if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
  557. error("%s: discard proposal: %s", __func__, ssh_err(r));
  558. return r;
  559. }
  560. }
  561. /*
  562. * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported
  563. * KEX method has the server move first, but a server might be using
  564. * a custom method or one that we otherwise don't support. We should
  565. * be prepared to remember first_kex_follows here so we can eat a
  566. * packet later.
  567. * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means
  568. * for cases where the server *doesn't* go first. I guess we should
  569. * ignore it when it is set for these cases, which is what we do now.
  570. */
  571. if ((r = sshpkt_get_u8(ssh, NULL)) != 0 || /* first_kex_follows */
  572. (r = sshpkt_get_u32(ssh, NULL)) != 0 || /* reserved */
  573. (r = sshpkt_get_end(ssh)) != 0)
  574. return r;
  575. if (!(kex->flags & KEX_INIT_SENT))
  576. if ((r = kex_send_kexinit(ssh)) != 0)
  577. return r;
  578. if ((r = kex_choose_conf(ssh)) != 0)
  579. return r;
  580. if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL)
  581. return (kex->kex[kex->kex_type])(ssh);
  582. error("%s: unknown kex type %u", __func__, kex->kex_type);
  583. return SSH_ERR_INTERNAL_ERROR;
  584. }
  585. struct kex *
  586. kex_new(void)
  587. {
  588. struct kex *kex;
  589. if ((kex = calloc(1, sizeof(*kex))) == NULL ||
  590. (kex->peer = sshbuf_new()) == NULL ||
  591. (kex->my = sshbuf_new()) == NULL ||
  592. (kex->client_version = sshbuf_new()) == NULL ||
  593. (kex->server_version = sshbuf_new()) == NULL ||
  594. (kex->session_id = sshbuf_new()) == NULL) {
  595. kex_free(kex);
  596. return NULL;
  597. }
  598. return kex;
  599. }
  600. void
  601. kex_free_newkeys(struct newkeys *newkeys)
  602. {
  603. if (newkeys == NULL)
  604. return;
  605. if (newkeys->enc.key) {
  606. explicit_bzero(newkeys->enc.key, newkeys->enc.key_len);
  607. free(newkeys->enc.key);
  608. newkeys->enc.key = NULL;
  609. }
  610. if (newkeys->enc.iv) {
  611. explicit_bzero(newkeys->enc.iv, newkeys->enc.iv_len);
  612. free(newkeys->enc.iv);
  613. newkeys->enc.iv = NULL;
  614. }
  615. free(newkeys->enc.name);
  616. explicit_bzero(&newkeys->enc, sizeof(newkeys->enc));
  617. free(newkeys->comp.name);
  618. explicit_bzero(&newkeys->comp, sizeof(newkeys->comp));
  619. mac_clear(&newkeys->mac);
  620. if (newkeys->mac.key) {
  621. explicit_bzero(newkeys->mac.key, newkeys->mac.key_len);
  622. free(newkeys->mac.key);
  623. newkeys->mac.key = NULL;
  624. }
  625. free(newkeys->mac.name);
  626. explicit_bzero(&newkeys->mac, sizeof(newkeys->mac));
  627. freezero(newkeys, sizeof(*newkeys));
  628. }
  629. void
  630. kex_free(struct kex *kex)
  631. {
  632. u_int mode;
  633. if (kex == NULL)
  634. return;
  635. #ifdef WITH_OPENSSL
  636. DH_free(kex->dh);
  637. #ifdef OPENSSL_HAS_ECC
  638. EC_KEY_free(kex->ec_client_key);
  639. #endif /* OPENSSL_HAS_ECC */
  640. #endif /* WITH_OPENSSL */
  641. for (mode = 0; mode < MODE_MAX; mode++) {
  642. kex_free_newkeys(kex->newkeys[mode]);
  643. kex->newkeys[mode] = NULL;
  644. }
  645. sshbuf_free(kex->peer);
  646. sshbuf_free(kex->my);
  647. sshbuf_free(kex->client_version);
  648. sshbuf_free(kex->server_version);
  649. sshbuf_free(kex->client_pub);
  650. sshbuf_free(kex->session_id);
  651. free(kex->failed_choice);
  652. free(kex->hostkey_alg);
  653. free(kex->name);
  654. free(kex);
  655. }
  656. int
  657. kex_ready(struct ssh *ssh, char *proposal[PROPOSAL_MAX])
  658. {
  659. int r;
  660. if ((r = kex_prop2buf(ssh->kex->my, proposal)) != 0)
  661. return r;
  662. ssh->kex->flags = KEX_INITIAL;
  663. kex_reset_dispatch(ssh);
  664. ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
  665. return 0;
  666. }
  667. int
  668. kex_setup(struct ssh *ssh, char *proposal[PROPOSAL_MAX])
  669. {
  670. int r;
  671. if ((r = kex_ready(ssh, proposal)) != 0)
  672. return r;
  673. if ((r = kex_send_kexinit(ssh)) != 0) { /* we start */
  674. kex_free(ssh->kex);
  675. ssh->kex = NULL;
  676. return r;
  677. }
  678. return 0;
  679. }
  680. /*
  681. * Request key re-exchange, returns 0 on success or a ssherr.h error
  682. * code otherwise. Must not be called if KEX is incomplete or in-progress.
  683. */
  684. int
  685. kex_start_rekex(struct ssh *ssh)
  686. {
  687. if (ssh->kex == NULL) {
  688. error("%s: no kex", __func__);
  689. return SSH_ERR_INTERNAL_ERROR;
  690. }
  691. if (ssh->kex->done == 0) {
  692. error("%s: requested twice", __func__);
  693. return SSH_ERR_INTERNAL_ERROR;
  694. }
  695. ssh->kex->done = 0;
  696. return kex_send_kexinit(ssh);
  697. }
  698. static int
  699. choose_enc(struct ssh *ssh, struct sshenc *enc, char *client, char *server)
  700. {
  701. char *name = match_list(client, server, NULL);
  702. if (name == NULL) {
  703. #ifdef SSH_AUDIT_EVENTS
  704. audit_unsupported(ssh, SSH_AUDIT_UNSUPPORTED_CIPHER);
  705. #endif
  706. return SSH_ERR_NO_CIPHER_ALG_MATCH;
  707. }
  708. if ((enc->cipher = cipher_by_name(name)) == NULL) {
  709. error("%s: unsupported cipher %s", __func__, name);
  710. free(name);
  711. return SSH_ERR_INTERNAL_ERROR;
  712. }
  713. enc->name = name;
  714. enc->enabled = 0;
  715. enc->iv = NULL;
  716. enc->iv_len = cipher_ivlen(enc->cipher);
  717. enc->key = NULL;
  718. enc->key_len = cipher_keylen(enc->cipher);
  719. enc->block_size = cipher_blocksize(enc->cipher);
  720. return 0;
  721. }
  722. static int
  723. choose_mac(struct ssh *ssh, struct sshmac *mac, char *client, char *server)
  724. {
  725. char *name = match_list(client, server, NULL);
  726. if (name == NULL) {
  727. #ifdef SSH_AUDIT_EVENTS
  728. audit_unsupported(ssh, SSH_AUDIT_UNSUPPORTED_MAC);
  729. #endif
  730. return SSH_ERR_NO_MAC_ALG_MATCH;
  731. }
  732. if (mac_setup(mac, name) < 0) {
  733. error("%s: unsupported MAC %s", __func__, name);
  734. free(name);
  735. return SSH_ERR_INTERNAL_ERROR;
  736. }
  737. mac->name = name;
  738. mac->key = NULL;
  739. mac->enabled = 0;
  740. return 0;
  741. }
  742. static int
  743. choose_comp(struct ssh *ssh, struct sshcomp *comp, char *client, char *server)
  744. {
  745. char *name = match_list(client, server, NULL);
  746. if (name == NULL) {
  747. #ifdef SSH_AUDIT_EVENTS
  748. audit_unsupported(ssh, SSH_AUDIT_UNSUPPORTED_COMPRESSION);
  749. #endif
  750. return SSH_ERR_NO_COMPRESS_ALG_MATCH;
  751. }
  752. #ifdef WITH_ZLIB
  753. if (strcmp(name, "zlib@openssh.com") == 0) {
  754. comp->type = COMP_DELAYED;
  755. } else if (strcmp(name, "zlib") == 0) {
  756. comp->type = COMP_ZLIB;
  757. } else
  758. #endif /* WITH_ZLIB */
  759. if (strcmp(name, "none") == 0) {
  760. comp->type = COMP_NONE;
  761. } else {
  762. error("%s: unsupported compression scheme %s", __func__, name);
  763. free(name);
  764. return SSH_ERR_INTERNAL_ERROR;
  765. }
  766. comp->name = name;
  767. return 0;
  768. }
  769. static int
  770. choose_kex(struct kex *k, char *client, char *server)
  771. {
  772. const struct kexalg *kexalg;
  773. k->name = match_list(client, server, NULL);
  774. debug("kex: algorithm: %s", k->name ? k->name : "(no match)");
  775. if (k->name == NULL)
  776. return SSH_ERR_NO_KEX_ALG_MATCH;
  777. if ((kexalg = kex_alg_by_name(k->name)) == NULL) {
  778. error("%s: unsupported KEX method %s", __func__, k->name);
  779. return SSH_ERR_INTERNAL_ERROR;
  780. }
  781. k->kex_type = kexalg->type;
  782. k->hash_alg = kexalg->hash_alg;
  783. k->ec_nid = kexalg->ec_nid;
  784. return 0;
  785. }
  786. static int
  787. choose_hostkeyalg(struct kex *k, char *client, char *server)
  788. {
  789. free(k->hostkey_alg);
  790. k->hostkey_alg = match_list(client, server, NULL);
  791. debug("kex: host key algorithm: %s",
  792. k->hostkey_alg ? k->hostkey_alg : "(no match)");
  793. if (k->hostkey_alg == NULL)
  794. return SSH_ERR_NO_HOSTKEY_ALG_MATCH;
  795. k->hostkey_type = sshkey_type_from_name(k->hostkey_alg);
  796. if (k->hostkey_type == KEY_UNSPEC) {
  797. error("%s: unsupported hostkey algorithm %s", __func__,
  798. k->hostkey_alg);
  799. return SSH_ERR_INTERNAL_ERROR;
  800. }
  801. k->hostkey_nid = sshkey_ecdsa_nid_from_name(k->hostkey_alg);
  802. return 0;
  803. }
  804. static int
  805. proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
  806. {
  807. static int check[] = {
  808. PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
  809. };
  810. int *idx;
  811. char *p;
  812. for (idx = &check[0]; *idx != -1; idx++) {
  813. if ((p = strchr(my[*idx], ',')) != NULL)
  814. *p = '\0';
  815. if ((p = strchr(peer[*idx], ',')) != NULL)
  816. *p = '\0';
  817. if (strcmp(my[*idx], peer[*idx]) != 0) {
  818. debug2("proposal mismatch: my %s peer %s",
  819. my[*idx], peer[*idx]);
  820. return (0);
  821. }
  822. }
  823. debug2("proposals match");
  824. return (1);
  825. }
  826. static int
  827. kex_choose_conf(struct ssh *ssh)
  828. {
  829. struct kex *kex = ssh->kex;
  830. struct newkeys *newkeys;
  831. char **my = NULL, **peer = NULL;
  832. char **cprop, **sprop;
  833. int nenc, nmac, ncomp;
  834. u_int mode, ctos, need, dh_need, authlen;
  835. int r, first_kex_follows;
  836. int auth_flag = 0;
  837. int log_flag = 0;
  838. auth_flag = packet_authentication_state(ssh);
  839. debug("AUTH STATE IS %d", auth_flag);
  840. debug2("local %s KEXINIT proposal", kex->server ? "server" : "client");
  841. if ((r = kex_buf2prop(kex->my, NULL, &my)) != 0)
  842. goto out;
  843. debug2("peer %s KEXINIT proposal", kex->server ? "client" : "server");
  844. if ((r = kex_buf2prop(kex->peer, &first_kex_follows, &peer)) != 0)
  845. goto out;
  846. if (kex->server) {
  847. cprop=peer;
  848. sprop=my;
  849. } else {
  850. cprop=my;
  851. sprop=peer;
  852. }
  853. /* Check whether client supports ext_info_c */
  854. if (kex->server && (kex->flags & KEX_INITIAL)) {
  855. char *ext;
  856. ext = match_list("ext-info-c", peer[PROPOSAL_KEX_ALGS], NULL);
  857. kex->ext_info_c = (ext != NULL);
  858. free(ext);
  859. }
  860. /* Algorithm Negotiation */
  861. if ((r = choose_kex(kex, cprop[PROPOSAL_KEX_ALGS],
  862. sprop[PROPOSAL_KEX_ALGS])) != 0) {
  863. kex->failed_choice = peer[PROPOSAL_KEX_ALGS];
  864. peer[PROPOSAL_KEX_ALGS] = NULL;
  865. goto out;
  866. }
  867. if ((r = choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
  868. sprop[PROPOSAL_SERVER_HOST_KEY_ALGS])) != 0) {
  869. kex->failed_choice = peer[PROPOSAL_SERVER_HOST_KEY_ALGS];
  870. peer[PROPOSAL_SERVER_HOST_KEY_ALGS] = NULL;
  871. goto out;
  872. }
  873. for (mode = 0; mode < MODE_MAX; mode++) {
  874. if ((newkeys = calloc(1, sizeof(*newkeys))) == NULL) {
  875. r = SSH_ERR_ALLOC_FAIL;
  876. goto out;
  877. }
  878. kex->newkeys[mode] = newkeys;
  879. ctos = (!kex->server && mode == MODE_OUT) ||
  880. (kex->server && mode == MODE_IN);
  881. nenc = ctos ? PROPOSAL_ENC_ALGS_CTOS : PROPOSAL_ENC_ALGS_STOC;
  882. nmac = ctos ? PROPOSAL_MAC_ALGS_CTOS : PROPOSAL_MAC_ALGS_STOC;
  883. ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
  884. if ((r = choose_enc(ssh, &newkeys->enc, cprop[nenc],
  885. sprop[nenc])) != 0) {
  886. kex->failed_choice = peer[nenc];
  887. peer[nenc] = NULL;
  888. goto out;
  889. }
  890. authlen = cipher_authlen(newkeys->enc.cipher);
  891. /* ignore mac for authenticated encryption */
  892. if (authlen == 0 &&
  893. (r = choose_mac(ssh, &newkeys->mac, cprop[nmac],
  894. sprop[nmac])) != 0) {
  895. kex->failed_choice = peer[nmac];
  896. peer[nmac] = NULL;
  897. goto out;
  898. }
  899. if ((r = choose_comp(ssh, &newkeys->comp, cprop[ncomp],
  900. sprop[ncomp])) != 0) {
  901. kex->failed_choice = peer[ncomp];
  902. peer[ncomp] = NULL;
  903. goto out;
  904. }
  905. debug("REQUESTED ENC.NAME is '%s'", newkeys->enc.name);
  906. debug("REQUESTED MAC.NAME is '%s'", newkeys->mac.name);
  907. if (strcmp(newkeys->enc.name, "none") == 0) {
  908. if (auth_flag == 1) {
  909. debug("None requested post authentication.");
  910. ssh->none = 1;
  911. }
  912. else
  913. fatal("Pre-authentication none cipher requests are not allowed.");
  914. if (newkeys->mac.name != NULL && strcmp(newkeys->mac.name, "none") == 0)
  915. debug("Requesting: NONEMAC. Authflag is %d", auth_flag);
  916. }
  917. debug("kex: %s cipher: %s MAC: %s compression: %s",
  918. ctos ? "client->server" : "server->client",
  919. newkeys->enc.name,
  920. authlen == 0 ? newkeys->mac.name : "<implicit>",
  921. newkeys->comp.name);
  922. /*
  923. * client starts with ctos = 0 && log flag = 0 and no log.
  924. * 2nd client pass ctos = 1 and flag = 1 so no log.
  925. * server starts with ctos = 1 && log_flag = 0 so log.
  926. * 2nd sever pass ctos = 1 && log flag = 1 so no log.
  927. * -cjr
  928. */
  929. if (ctos && !log_flag) {
  930. logit("SSH: Server;Ltype: Kex;Remote: %s-%d;Enc: %s;MAC: %s;Comp: %s",
  931. ssh_remote_ipaddr(ssh),
  932. ssh_remote_port(ssh),
  933. newkeys->enc.name,
  934. authlen == 0 ? newkeys->mac.name : "<implicit>",
  935. newkeys->comp.name);
  936. }
  937. log_flag = 1;
  938. }
  939. need = dh_need = 0;
  940. for (mode = 0; mode < MODE_MAX; mode++) {
  941. newkeys = kex->newkeys[mode];
  942. need = MAXIMUM(need, newkeys->enc.key_len);
  943. need = MAXIMUM(need, newkeys->enc.block_size);
  944. need = MAXIMUM(need, newkeys->enc.iv_len);
  945. need = MAXIMUM(need, newkeys->mac.key_len);
  946. dh_need = MAXIMUM(dh_need, cipher_seclen(newkeys->enc.cipher));
  947. dh_need = MAXIMUM(dh_need, newkeys->enc.block_size);
  948. dh_need = MAXIMUM(dh_need, newkeys->enc.iv_len);
  949. dh_need = MAXIMUM(dh_need, newkeys->mac.key_len);
  950. debug("kex: %s need=%d dh_need=%d", kex->name, need, dh_need);
  951. #ifdef SSH_AUDIT_EVENTS
  952. audit_kex(ssh, mode, newkeys->enc.name, newkeys->mac.name, newkeys->comp.name, kex->name);
  953. #endif
  954. }
  955. /* XXX need runden? */
  956. kex->we_need = need;
  957. kex->dh_need = dh_need;
  958. /* ignore the next message if the proposals do not match */
  959. if (first_kex_follows && !proposals_match(my, peer))
  960. ssh->dispatch_skip_packets = 1;
  961. r = 0;
  962. out:
  963. kex_prop_free(my);
  964. kex_prop_free(peer);
  965. return r;
  966. }
  967. #ifdef HAVE_EVP_KDF_CTX_NEW_ID
  968. static const EVP_MD *
  969. digest_to_md(int digest_type)
  970. {
  971. switch (digest_type) {
  972. case SSH_DIGEST_SHA1:
  973. return EVP_sha1();
  974. case SSH_DIGEST_SHA256:
  975. return EVP_sha256();
  976. case SSH_DIGEST_SHA384:
  977. return EVP_sha384();
  978. case SSH_DIGEST_SHA512:
  979. return EVP_sha512();
  980. }
  981. return NULL;
  982. }
  983. static int
  984. derive_key(struct ssh *ssh, int id, u_int need, u_char *hash, u_int hashlen,
  985. const struct sshbuf *shared_secret, u_char **keyp)
  986. {
  987. struct kex *kex = ssh->kex;
  988. EVP_KDF_CTX *ctx = NULL;
  989. u_char *key = NULL;
  990. int r, key_len, actualsize;
  991. if ((key_len = ssh_digest_bytes(kex->hash_alg)) == 0)
  992. return SSH_ERR_INVALID_ARGUMENT;
  993. key_len = ROUNDUP(need, key_len);
  994. if ((key = calloc(1, key_len)) == NULL) {
  995. r = SSH_ERR_ALLOC_FAIL;
  996. goto out;
  997. }
  998. ctx = EVP_KDF_CTX_new_id(EVP_KDF_SSHKDF);
  999. if (!ctx) {
  1000. r = SSH_ERR_LIBCRYPTO_ERROR;
  1001. debug("ERROR: ctx=EVP_KDF_CTX_new_id(EVP_KDF_SSHKDF); !ctx=true;");
  1002. goto out;
  1003. }
  1004. r = EVP_KDF_ctrl(ctx, EVP_KDF_CTRL_SET_MD, digest_to_md(kex->hash_alg));
  1005. if (r != 1) {
  1006. r = SSH_ERR_LIBCRYPTO_ERROR;
  1007. debug("EVP_KDF_ctrl(ctx, EVP_KDF_CTRL_SET_MD, digest_to_md(kex->hash_alg)) != 1");
  1008. goto out;
  1009. }
  1010. r = EVP_KDF_ctrl(ctx, EVP_KDF_CTRL_SET_KEY,
  1011. sshbuf_ptr(shared_secret), sshbuf_len(shared_secret));
  1012. if (r != 1) {
  1013. debug("EVP_KDF_ctrl(ctx, EVP_KDF_CTRL_SET_KEY, sshbuf_ptr(shared_secret), sshbuf_len(shared_secret)) != 1");
  1014. r = SSH_ERR_LIBCRYPTO_ERROR;
  1015. goto out;
  1016. }
  1017. r = EVP_KDF_ctrl(ctx, EVP_KDF_CTRL_SET_SSHKDF_XCGHASH, hash, hashlen);
  1018. if (r != 1) {
  1019. r = SSH_ERR_LIBCRYPTO_ERROR;
  1020. debug("EVP_KDF_ctrl(ctx, EVP_KDF_CTRL_SET_SSHKDF_XCGHASH, hash, hashlen) != 1");
  1021. goto out;
  1022. }
  1023. r = EVP_KDF_ctrl(ctx, EVP_KDF_CTRL_SET_SSHKDF_TYPE, id);
  1024. if (r != 1) {
  1025. r = SSH_ERR_LIBCRYPTO_ERROR;
  1026. debug("EVP_KDF_ctrl(ctx, EVP_KDF_CTRL_SET_SSHKDF_TYPE, id) != 1");
  1027. goto out;
  1028. }
  1029. r = EVP_KDF_ctrl(ctx, EVP_KDF_CTRL_SET_SSHKDF_SESSION_ID,
  1030. kex->session_id);
  1031. if (r != 1) {
  1032. r = SSH_ERR_LIBCRYPTO_ERROR;
  1033. debug("EVP_KDF_ctrl(ctx, EVP_KDF_CTRL_SET_SSHKDF_SESSION_ID, kex->session_id) != 1");
  1034. goto out;
  1035. }
  1036. r = EVP_KDF_derive(ctx, key, key_len);
  1037. if (r != 1) {
  1038. debug("EVP_KDF_derive(ctx, key, key_len) != 1");
  1039. actualsize=EVP_KDF_size(ctx);
  1040. //fprintf(stderr, "\ndebug: r=%d, key_len=%d, actualsize=%d, key=%X\n\n", r, key_len, actualsize, &key);
  1041. r = SSH_ERR_LIBCRYPTO_ERROR;
  1042. goto out;
  1043. }
  1044. #ifdef DEBUG_KEX
  1045. fprintf(stderr, "key '%c'== ", id);
  1046. dump_digest("key", key, key_len);
  1047. #endif
  1048. *keyp = key;
  1049. key = NULL;
  1050. r = 0;
  1051. out:
  1052. free (key);
  1053. EVP_KDF_CTX_free(ctx);
  1054. if (r < 0) {
  1055. return r;
  1056. }
  1057. return 0;
  1058. }
  1059. #else
  1060. static int
  1061. derive_key(struct ssh *ssh, int id, u_int need, u_char *hash, u_int hashlen,
  1062. const struct sshbuf *shared_secret, u_char **keyp)
  1063. {
  1064. struct kex *kex = ssh->kex;
  1065. struct ssh_digest_ctx *hashctx = NULL;
  1066. char c = id;
  1067. u_int have;
  1068. size_t mdsz;
  1069. u_char *digest;
  1070. int r;
  1071. if ((mdsz = ssh_digest_bytes(kex->hash_alg)) == 0)
  1072. return SSH_ERR_INVALID_ARGUMENT;
  1073. if ((digest = calloc(1, ROUNDUP(need, mdsz))) == NULL) {
  1074. r = SSH_ERR_ALLOC_FAIL;
  1075. goto out;
  1076. }
  1077. /* K1 = HASH(K || H || "A" || session_id) */
  1078. if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
  1079. ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
  1080. ssh_digest_update(hashctx, hash, hashlen) != 0 ||
  1081. ssh_digest_update(hashctx, &c, 1) != 0 ||
  1082. ssh_digest_update_buffer(hashctx, kex->session_id) != 0 ||
  1083. ssh_digest_final(hashctx, digest, mdsz) != 0) {
  1084. r = SSH_ERR_LIBCRYPTO_ERROR;
  1085. error("%s: KEX hash failed", __func__);
  1086. goto out;
  1087. }
  1088. ssh_digest_free(hashctx);
  1089. hashctx = NULL;
  1090. /*
  1091. * expand key:
  1092. * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
  1093. * Key = K1 || K2 || ... || Kn
  1094. */
  1095. for (have = mdsz; need > have; have += mdsz) {
  1096. if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
  1097. ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
  1098. ssh_digest_update(hashctx, hash, hashlen) != 0 ||
  1099. ssh_digest_update(hashctx, digest, have) != 0 ||
  1100. ssh_digest_final(hashctx, digest + have, mdsz) != 0) {
  1101. error("%s: KDF failed", __func__);
  1102. r = SSH_ERR_LIBCRYPTO_ERROR;
  1103. goto out;
  1104. }
  1105. ssh_digest_free(hashctx);
  1106. hashctx = NULL;
  1107. }
  1108. #ifdef DEBUG_KEX
  1109. fprintf(stderr, "key '%c'== ", c);
  1110. dump_digest("key", digest, need);
  1111. #endif
  1112. *keyp = digest;
  1113. digest = NULL;
  1114. r = 0;
  1115. out:
  1116. free(digest);
  1117. ssh_digest_free(hashctx);
  1118. return r;
  1119. }
  1120. #endif /* HAVE_OPENSSL_EVP_KDF_CTX_NEW_ID */
  1121. #define NKEYS 6
  1122. int
  1123. kex_derive_keys(struct ssh *ssh, u_char *hash, u_int hashlen,
  1124. const struct sshbuf *shared_secret)
  1125. {
  1126. struct kex *kex = ssh->kex;
  1127. u_char *keys[NKEYS];
  1128. u_int i, j, mode, ctos;
  1129. int r;
  1130. /* save initial hash as session id */
  1131. if ((kex->flags & KEX_INITIAL) != 0) {
  1132. if (sshbuf_len(kex->session_id) != 0) {
  1133. error("already have session ID at kex");
  1134. return SSH_ERR_INTERNAL_ERROR;
  1135. }
  1136. if ((r = sshbuf_put(kex->session_id, hash, hashlen)) != 0)
  1137. return r;
  1138. } else if (sshbuf_len(kex->session_id) == 0) {
  1139. error("no session ID in rekex");
  1140. return SSH_ERR_INTERNAL_ERROR;
  1141. }
  1142. for (i = 0; i < NKEYS; i++) {
  1143. if ((r = derive_key(ssh, 'A'+i, kex->we_need, hash, hashlen,
  1144. shared_secret, &keys[i])) != 0) {
  1145. for (j = 0; j < i; j++)
  1146. free(keys[j]);
  1147. return r;
  1148. }
  1149. }
  1150. for (mode = 0; mode < MODE_MAX; mode++) {
  1151. ctos = (!kex->server && mode == MODE_OUT) ||
  1152. (kex->server && mode == MODE_IN);
  1153. kex->newkeys[mode]->enc.iv = keys[ctos ? 0 : 1];
  1154. kex->newkeys[mode]->enc.key = keys[ctos ? 2 : 3];
  1155. kex->newkeys[mode]->mac.key = keys[ctos ? 4 : 5];
  1156. }
  1157. return 0;
  1158. }
  1159. int
  1160. kex_load_hostkey(struct ssh *ssh, struct sshkey **prvp, struct sshkey **pubp)
  1161. {
  1162. struct kex *kex = ssh->kex;
  1163. *pubp = NULL;
  1164. *prvp = NULL;
  1165. if (kex->load_host_public_key == NULL ||
  1166. kex->load_host_private_key == NULL) {
  1167. error("%s: missing hostkey loader", __func__);
  1168. return SSH_ERR_INVALID_ARGUMENT;
  1169. }
  1170. *pubp = kex->load_host_public_key(kex->hostkey_type,
  1171. kex->hostkey_nid, ssh);
  1172. *prvp = kex->load_host_private_key(kex->hostkey_type,
  1173. kex->hostkey_nid, ssh);
  1174. if (*pubp == NULL)
  1175. return SSH_ERR_NO_HOSTKEY_LOADED;
  1176. return 0;
  1177. }
  1178. int
  1179. kex_verify_host_key(struct ssh *ssh, struct sshkey *server_host_key)
  1180. {
  1181. struct kex *kex = ssh->kex;
  1182. if (kex->verify_host_key == NULL) {
  1183. error("%s: missing hostkey verifier", __func__);
  1184. return SSH_ERR_INVALID_ARGUMENT;
  1185. }
  1186. if (server_host_key->type != kex->hostkey_type ||
  1187. (kex->hostkey_type == KEY_ECDSA &&
  1188. server_host_key->ecdsa_nid != kex->hostkey_nid))
  1189. return SSH_ERR_KEY_TYPE_MISMATCH;
  1190. if (kex->verify_host_key(server_host_key, ssh) == -1)
  1191. return SSH_ERR_SIGNATURE_INVALID;
  1192. return 0;
  1193. }
  1194. #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) || defined(DEBUG_KEXECDH)
  1195. void
  1196. dump_digest(const char *msg, const u_char *digest, int len)
  1197. {
  1198. fprintf(stderr, "%s\n", msg);
  1199. sshbuf_dump_data(digest, len, stderr);
  1200. }
  1201. #endif
  1202. static void
  1203. enc_destroy(struct sshenc *enc)
  1204. {
  1205. if (enc == NULL)
  1206. return;
  1207. if (enc->key) {
  1208. memset(enc->key, 0, enc->key_len);
  1209. free(enc->key);
  1210. }
  1211. if (enc->iv) {
  1212. memset(enc->iv, 0, enc->iv_len);
  1213. free(enc->iv);
  1214. }
  1215. memset(enc, 0, sizeof(*enc));
  1216. }
  1217. void
  1218. newkeys_destroy(struct newkeys *newkeys)
  1219. {
  1220. if (newkeys == NULL)
  1221. return;
  1222. enc_destroy(&newkeys->enc);
  1223. mac_destroy(&newkeys->mac);
  1224. memset(&newkeys->comp, 0, sizeof(newkeys->comp));
  1225. }
  1226. /*
  1227. * Send a plaintext error message to the peer, suffixed by \r\n.
  1228. * Only used during banner exchange, and there only for the server.
  1229. */
  1230. static void
  1231. send_error(struct ssh *ssh, char *msg)
  1232. {
  1233. char *crnl = "\r\n";
  1234. if (!ssh->kex->server)
  1235. return;
  1236. if (atomicio(vwrite, ssh_packet_get_connection_out(ssh),
  1237. msg, strlen(msg)) != strlen(msg) ||
  1238. atomicio(vwrite, ssh_packet_get_connection_out(ssh),
  1239. crnl, strlen(crnl)) != strlen(crnl))
  1240. error("%s: write: %.100s", __func__, strerror(errno));
  1241. }
  1242. /*
  1243. * Sends our identification string and waits for the peer's. Will block for
  1244. * up to timeout_ms (or indefinitely if timeout_ms <= 0).
  1245. * Returns on 0 success or a ssherr.h code on failure.
  1246. */
  1247. int
  1248. kex_exchange_identification(struct ssh *ssh, int timeout_ms,
  1249. const char *version_addendum)
  1250. {
  1251. int remote_major, remote_minor, mismatch, oerrno = 0;
  1252. size_t len, i, n;
  1253. int r, expect_nl;
  1254. u_char c;
  1255. struct sshbuf *our_version = ssh->kex->server ?
  1256. ssh->kex->server_version : ssh->kex->client_version;
  1257. struct sshbuf *peer_version = ssh->kex->server ?
  1258. ssh->kex->client_version : ssh->kex->server_version;
  1259. char *our_version_string = NULL, *peer_version_string = NULL;
  1260. char *cp, *remote_version = NULL;
  1261. /* Prepare and send our banner */
  1262. sshbuf_reset(our_version);
  1263. if (version_addendum != NULL && *version_addendum == '\0')
  1264. version_addendum = NULL;
  1265. if ((r = sshbuf_putf(our_version, "SSH-%d.%d-%.100s%s%s\r\n",
  1266. PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_RELEASE,
  1267. version_addendum == NULL ? "" : " ",
  1268. version_addendum == NULL ? "" : version_addendum)) != 0) {
  1269. oerrno = errno;
  1270. error("%s: sshbuf_putf: %s", __func__, ssh_err(r));
  1271. goto out;
  1272. }
  1273. if (atomicio(vwrite, ssh_packet_get_connection_out(ssh),
  1274. sshbuf_mutable_ptr(our_version),
  1275. sshbuf_len(our_version)) != sshbuf_len(our_version)) {
  1276. oerrno = errno;
  1277. debug("%s: write: %.100s", __func__, strerror(errno));
  1278. r = SSH_ERR_SYSTEM_ERROR;
  1279. goto out;
  1280. }
  1281. if ((r = sshbuf_consume_end(our_version, 2)) != 0) { /* trim \r\n */
  1282. oerrno = errno;
  1283. error("%s: sshbuf_consume_end: %s", __func__, ssh_err(r));
  1284. goto out;
  1285. }
  1286. our_version_string = sshbuf_dup_string(our_version);
  1287. if (our_version_string == NULL) {
  1288. error("%s: sshbuf_dup_string failed", __func__);
  1289. r = SSH_ERR_ALLOC_FAIL;
  1290. goto out;
  1291. }
  1292. debug("Local version string %.100s", our_version_string);
  1293. /* Read other side's version identification. */
  1294. for (n = 0; ; n++) {
  1295. if (n >= SSH_MAX_PRE_BANNER_LINES) {
  1296. send_error(ssh, "No SSH identification string "
  1297. "received.");
  1298. error("%s: No SSH version received in first %u lines "
  1299. "from server", __func__, SSH_MAX_PRE_BANNER_LINES);
  1300. r = SSH_ERR_INVALID_FORMAT;
  1301. goto out;
  1302. }
  1303. sshbuf_reset(peer_version);
  1304. expect_nl = 0;
  1305. for (i = 0; ; i++) {
  1306. if (timeout_ms > 0) {
  1307. r = waitrfd(ssh_packet_get_connection_in(ssh),
  1308. &timeout_ms);
  1309. if (r == -1 && errno == ETIMEDOUT) {
  1310. send_error(ssh, "Timed out waiting "
  1311. "for SSH identification string.");
  1312. error("Connection timed out during "
  1313. "banner exchange");
  1314. r = SSH_ERR_CONN_TIMEOUT;
  1315. goto out;
  1316. } else if (r == -1) {
  1317. oerrno = errno;
  1318. error("%s: %s",
  1319. __func__, strerror(errno));
  1320. r = SSH_ERR_SYSTEM_ERROR;
  1321. goto out;
  1322. }
  1323. }
  1324. len = atomicio(read, ssh_packet_get_connection_in(ssh),
  1325. &c, 1);
  1326. if (len != 1 && errno == EPIPE) {
  1327. error("%s: Connection closed by remote host",
  1328. __func__);
  1329. r = SSH_ERR_CONN_CLOSED;
  1330. goto out;
  1331. } else if (len != 1) {
  1332. oerrno = errno;
  1333. error("%s: read: %.100s",
  1334. __func__, strerror(errno));
  1335. r = SSH_ERR_SYSTEM_ERROR;
  1336. goto out;
  1337. }
  1338. if (c == '\r') {
  1339. expect_nl = 1;
  1340. continue;
  1341. }
  1342. if (c == '\n')
  1343. break;
  1344. if (c == '\0' || expect_nl) {
  1345. error("%s: banner line contains invalid "
  1346. "characters", __func__);
  1347. goto invalid;
  1348. }
  1349. if ((r = sshbuf_put_u8(peer_version, c)) != 0) {
  1350. oerrno = errno;
  1351. error("%s: sshbuf_put: %s",
  1352. __func__, ssh_err(r));
  1353. goto out;
  1354. }
  1355. if (sshbuf_len(peer_version) > SSH_MAX_BANNER_LEN) {
  1356. error("%s: banner line too long", __func__);
  1357. goto invalid;
  1358. }
  1359. }
  1360. /* Is this an actual protocol banner? */
  1361. if (sshbuf_len(peer_version) > 4 &&
  1362. memcmp(sshbuf_ptr(peer_version), "SSH-", 4) == 0)
  1363. break;
  1364. /* If not, then just log the line and continue */
  1365. if ((cp = sshbuf_dup_string(peer_version)) == NULL) {
  1366. error("%s: sshbuf_dup_string failed", __func__);
  1367. r = SSH_ERR_ALLOC_FAIL;
  1368. goto out;
  1369. }
  1370. /* Do not accept lines before the SSH ident from a client */
  1371. if (ssh->kex->server) {
  1372. error("%s: client sent invalid protocol identifier "
  1373. "\"%.256s\"", __func__, cp);
  1374. free(cp);
  1375. goto invalid;
  1376. }
  1377. debug("%s: banner line %zu: %s", __func__, n, cp);
  1378. free(cp);
  1379. }
  1380. peer_version_string = sshbuf_dup_string(peer_version);
  1381. if (peer_version_string == NULL)
  1382. error("%s: sshbuf_dup_string failed", __func__);
  1383. /* XXX must be same size for sscanf */
  1384. if ((remote_version = calloc(1, sshbuf_len(peer_version))) == NULL) {
  1385. error("%s: calloc failed", __func__);
  1386. r = SSH_ERR_ALLOC_FAIL;
  1387. goto out;
  1388. }
  1389. /*
  1390. * Check that the versions match. In future this might accept
  1391. * several versions and set appropriate flags to handle them.
  1392. */
  1393. if (sscanf(peer_version_string, "SSH-%d.%d-%[^\n]\n",
  1394. &remote_major, &remote_minor, remote_version) != 3) {
  1395. error("Bad remote protocol version identification: '%.100s'",
  1396. peer_version_string);
  1397. invalid:
  1398. send_error(ssh, "Invalid SSH identification string.");
  1399. r = SSH_ERR_INVALID_FORMAT;
  1400. goto out;
  1401. }
  1402. /* report the version information to syslog if this is the server */
  1403. if (timeout_ms == -1) { /* only the server uses this value */
  1404. logit("SSH: Server;Ltype: Version;Remote: %s-%d;Protocol: %d.%d;Client: %.100s",
  1405. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
  1406. remote_major, remote_minor, remote_version);
  1407. }
  1408. debug("Remote protocol version %d.%d, remote software version %.100s",
  1409. remote_major, remote_minor, remote_version);
  1410. compat_banner(ssh, remote_version);
  1411. mismatch = 0;
  1412. switch (remote_major) {
  1413. case 2:
  1414. break;
  1415. case 1:
  1416. if (remote_minor != 99)
  1417. mismatch = 1;
  1418. break;
  1419. default:
  1420. mismatch = 1;
  1421. break;
  1422. }
  1423. if (mismatch) {
  1424. error("Protocol major versions differ: %d vs. %d",
  1425. PROTOCOL_MAJOR_2, remote_major);
  1426. send_error(ssh, "Protocol major versions differ.");
  1427. r = SSH_ERR_NO_PROTOCOL_VERSION;
  1428. goto out;
  1429. }
  1430. if (ssh->kex->server && (ssh->compat & SSH_BUG_PROBE) != 0) {
  1431. logit("probed from %s port %d with %s. Don't panic.",
  1432. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
  1433. peer_version_string);
  1434. r = SSH_ERR_CONN_CLOSED; /* XXX */
  1435. goto out;
  1436. }
  1437. if (ssh->kex->server && (ssh->compat & SSH_BUG_SCANNER) != 0) {
  1438. logit("scanned from %s port %d with %s. Don't panic.",
  1439. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
  1440. peer_version_string);
  1441. r = SSH_ERR_CONN_CLOSED; /* XXX */
  1442. goto out;
  1443. }
  1444. if ((ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
  1445. logit("Remote version \"%.100s\" uses unsafe RSA signature "
  1446. "scheme; disabling use of RSA keys", remote_version);
  1447. }
  1448. /* success */
  1449. r = 0;
  1450. out:
  1451. free(our_version_string);
  1452. free(peer_version_string);
  1453. free(remote_version);
  1454. if (r == SSH_ERR_SYSTEM_ERROR)
  1455. errno = oerrno;
  1456. return r;
  1457. }