122514Sdarrenr/* $OpenBSD: ssh_api.c,v 1.28 2024/01/09 21:39:14 djm Exp $ */
2255332Scy/*
322514Sdarrenr * Copyright (c) 2012 Markus Friedl.  All rights reserved.
4145510Sdarrenr *
522514Sdarrenr * Permission to use, copy, modify, and distribute this software for any
631183Speter * purpose with or without fee is hereby granted, provided that the above
731183Speter * copyright notice and this permission notice appear in all copies.
831183Speter *
922514Sdarrenr * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
1022514Sdarrenr * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
1122514Sdarrenr * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
1231183Speter * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
1322514Sdarrenr * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
1422514Sdarrenr * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
1522514Sdarrenr * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1622514Sdarrenr */
1731183Speter
1831183Speter#include "includes.h"
1931183Speter
2022514Sdarrenr#include <sys/types.h>
2131183Speter
2231183Speter#include <stdio.h>
2331183Speter#include <stdlib.h>
2431183Speter
2531183Speter#include "ssh_api.h"
2631183Speter#include "compat.h"
2731183Speter#include "log.h"
2831183Speter#include "authfile.h"
2931183Speter#include "sshkey.h"
3031183Speter#include "misc.h"
3122514Sdarrenr#include "ssh2.h"
3222514Sdarrenr#include "version.h"
3322514Sdarrenr#include "myproposal.h"
3422514Sdarrenr#include "ssherr.h"
3522514Sdarrenr#include "sshbuf.h"
3622514Sdarrenr
3731183Speter#include "openbsd-compat/openssl-compat.h"
3822514Sdarrenr
3922514Sdarrenr#include <string.h>
4022514Sdarrenr
4131183Speterint	_ssh_exchange_banner(struct ssh *);
4231183Speterint	_ssh_send_banner(struct ssh *, struct sshbuf *);
4331183Speterint	_ssh_read_banner(struct ssh *, struct sshbuf *);
4431183Speterint	_ssh_order_hostkeyalgs(struct ssh *);
4531183Speterint	_ssh_verify_host_key(struct sshkey *, struct ssh *);
4631183Speterstruct sshkey *_ssh_host_public_key(int, int, struct ssh *);
4731183Speterstruct sshkey *_ssh_host_private_key(int, int, struct ssh *);
4831183Speterint	_ssh_host_key_sign(struct ssh *, struct sshkey *, struct sshkey *,
4931183Speter    u_char **, size_t *, const u_char *, size_t, const char *);
5031183Speter
5131183Speter/*
5231183Speter * stubs for the server side implementation of kex.
5331183Speter * disable privsep so our stubs will never be called.
5431183Speter */
5531183Speterint	use_privsep = 0;
5631183Speterint	mm_sshkey_sign(struct sshkey *, u_char **, u_int *,
5731183Speter    const u_char *, u_int, const char *, const char *, const char *, u_int);
5831183Speter
5931183Speter#ifdef WITH_OPENSSL
6022514SdarrenrDH	*mm_choose_dh(int, int, int);
6122514Sdarrenr#endif
6222514Sdarrenr
6326119Sdarrenrint
6426119Sdarrenrmm_sshkey_sign(struct sshkey *key, u_char **sigp, u_int *lenp,
6526119Sdarrenr    const u_char *data, u_int datalen, const char *alg,
6622514Sdarrenr    const char *sk_provider, const char *sk_pin, u_int compat)
6722514Sdarrenr{
6853024Sguido	return (-1);
6922514Sdarrenr}
7022514Sdarrenr
7122514Sdarrenr#ifdef WITH_OPENSSL
7222514SdarrenrDH *
7322514Sdarrenrmm_choose_dh(int min, int nbits, int max)
7422514Sdarrenr{
7522514Sdarrenr	return (NULL);
7653024Sguido}
7722514Sdarrenr#endif
7822514Sdarrenr
7922514Sdarrenr/* API */
8022514Sdarrenr
8122514Sdarrenrint
8222514Sdarrenrssh_init(struct ssh **sshp, int is_server, struct kex_params *kex_params)
8322514Sdarrenr{
8453024Sguido	char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
8553024Sguido	char *populated[PROPOSAL_MAX];
8622514Sdarrenr	struct ssh *ssh;
8722514Sdarrenr	char **proposal;
8822514Sdarrenr	static int called;
8922514Sdarrenr	int r;
9022514Sdarrenr
9122514Sdarrenr	if (!called) {
9222514Sdarrenr		seed_rng();
9353024Sguido		called = 1;
9422514Sdarrenr	}
9522514Sdarrenr
9622514Sdarrenr	if ((ssh = ssh_packet_set_connection(NULL, -1, -1)) == NULL)
9722514Sdarrenr		return SSH_ERR_ALLOC_FAIL;
9822514Sdarrenr	if (is_server)
9922514Sdarrenr		ssh_packet_set_server(ssh);
10022514Sdarrenr
10153024Sguido	/* Initialize key exchange */
10222514Sdarrenr	proposal = kex_params ? kex_params->proposal : myproposal;
10331183Speter	kex_proposal_populate_entries(ssh, populated,
10422514Sdarrenr	    proposal[PROPOSAL_KEX_ALGS],
10531183Speter	    proposal[PROPOSAL_ENC_ALGS_CTOS],
10622514Sdarrenr	    proposal[PROPOSAL_MAC_ALGS_CTOS],
10722514Sdarrenr	    proposal[PROPOSAL_COMP_ALGS_CTOS],
10831183Speter	    proposal[PROPOSAL_SERVER_HOST_KEY_ALGS]);
10931183Speter	r = kex_ready(ssh, populated);
11022514Sdarrenr	kex_proposal_free_entries(populated);
11131183Speter	if (r != 0) {
11231183Speter		ssh_free(ssh);
11331183Speter		return r;
11431183Speter	}
11522514Sdarrenr
11631183Speter	ssh->kex->server = is_server;
11731183Speter	if (is_server) {
11822514Sdarrenr#ifdef WITH_OPENSSL
11931183Speter		ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
12031183Speter		ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
12153024Sguido		ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
12231183Speter		ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
12331183Speter		ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
12431183Speter		ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
12531183Speter		ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
12622514Sdarrenr# ifdef OPENSSL_HAS_ECC
12731183Speter		ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
12831183Speter# endif
12953024Sguido#endif /* WITH_OPENSSL */
13031183Speter		ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_server;
13131183Speter		ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
13231183Speter		ssh->kex->load_host_public_key=&_ssh_host_public_key;
13331183Speter		ssh->kex->load_host_private_key=&_ssh_host_private_key;
13431183Speter		ssh->kex->sign=&_ssh_host_key_sign;
135145510Sdarrenr	} else {
136145510Sdarrenr#ifdef WITH_OPENSSL
137145510Sdarrenr		ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client;
138145510Sdarrenr		ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client;
139145510Sdarrenr		ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client;
140145510Sdarrenr		ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client;
141145510Sdarrenr		ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client;
142145510Sdarrenr		ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
14331183Speter		ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
14431183Speter# ifdef OPENSSL_HAS_ECC
14531183Speter		ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
14622514Sdarrenr# endif
14731183Speter#endif /* WITH_OPENSSL */
14822514Sdarrenr		ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
14922514Sdarrenr		ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client;
15031183Speter		ssh->kex->verify_host_key =&_ssh_verify_host_key;
15122514Sdarrenr	}
15231183Speter	*sshp = ssh;
15331183Speter	return 0;
15431183Speter}
15531183Speter
15631183Spetervoid
15731183Speterssh_free(struct ssh *ssh)
15831183Speter{
15931183Speter	struct key_entry *k;
16031183Speter
16131183Speter	if (ssh == NULL)
16231183Speter		return;
16331183Speter
16431183Speter	/*
16531183Speter	 * we've only created the public keys variants in case we
16631183Speter	 * are a acting as a server.
16731183Speter	 */
16831183Speter	while ((k = TAILQ_FIRST(&ssh->public_keys)) != NULL) {
16931183Speter		TAILQ_REMOVE(&ssh->public_keys, k, next);
17031183Speter		if (ssh->kex && ssh->kex->server)
17131183Speter			sshkey_free(k->key);
17231183Speter		free(k);
17331183Speter	}
17431183Speter	while ((k = TAILQ_FIRST(&ssh->private_keys)) != NULL) {
17531183Speter		TAILQ_REMOVE(&ssh->private_keys, k, next);
17622514Sdarrenr		free(k);
17722514Sdarrenr	}
17831183Speter	ssh_packet_close(ssh);
17931183Speter	free(ssh);
18031183Speter}
18131183Speter
18231183Spetervoid
18331183Speterssh_set_app_data(struct ssh *ssh, void *app_data)
184{
185	ssh->app_data = app_data;
186}
187
188void *
189ssh_get_app_data(struct ssh *ssh)
190{
191	return ssh->app_data;
192}
193
194/* Returns < 0 on error, 0 otherwise */
195int
196ssh_add_hostkey(struct ssh *ssh, struct sshkey *key)
197{
198	struct sshkey *pubkey = NULL;
199	struct key_entry *k = NULL, *k_prv = NULL;
200	int r;
201
202	if (ssh->kex->server) {
203		if ((r = sshkey_from_private(key, &pubkey)) != 0)
204			return r;
205		if ((k = malloc(sizeof(*k))) == NULL ||
206		    (k_prv = malloc(sizeof(*k_prv))) == NULL) {
207			free(k);
208			sshkey_free(pubkey);
209			return SSH_ERR_ALLOC_FAIL;
210		}
211		k_prv->key = key;
212		TAILQ_INSERT_TAIL(&ssh->private_keys, k_prv, next);
213
214		/* add the public key, too */
215		k->key = pubkey;
216		TAILQ_INSERT_TAIL(&ssh->public_keys, k, next);
217		r = 0;
218	} else {
219		if ((k = malloc(sizeof(*k))) == NULL)
220			return SSH_ERR_ALLOC_FAIL;
221		k->key = key;
222		TAILQ_INSERT_TAIL(&ssh->public_keys, k, next);
223		r = 0;
224	}
225
226	return r;
227}
228
229int
230ssh_set_verify_host_key_callback(struct ssh *ssh,
231    int (*cb)(struct sshkey *, struct ssh *))
232{
233	if (cb == NULL || ssh->kex == NULL)
234		return SSH_ERR_INVALID_ARGUMENT;
235
236	ssh->kex->verify_host_key = cb;
237
238	return 0;
239}
240
241int
242ssh_input_append(struct ssh *ssh, const u_char *data, size_t len)
243{
244	return sshbuf_put(ssh_packet_get_input(ssh), data, len);
245}
246
247int
248ssh_packet_next(struct ssh *ssh, u_char *typep)
249{
250	int r;
251	u_int32_t seqnr;
252	u_char type;
253
254	/*
255	 * Try to read a packet. Return SSH_MSG_NONE if no packet or not
256	 * enough data.
257	 */
258	*typep = SSH_MSG_NONE;
259	if (sshbuf_len(ssh->kex->client_version) == 0 ||
260	    sshbuf_len(ssh->kex->server_version) == 0)
261		return _ssh_exchange_banner(ssh);
262	/*
263	 * If we enough data and a dispatch function then
264	 * call the function and get the next packet.
265	 * Otherwise return the packet type to the caller so it
266	 * can decide how to go on.
267	 *
268	 * We will only call the dispatch function for:
269	 *     20-29    Algorithm negotiation
270	 *     30-49    Key exchange method specific (numbers can be reused for
271	 *              different authentication methods)
272	 */
273	for (;;) {
274		if ((r = ssh_packet_read_poll2(ssh, &type, &seqnr)) != 0)
275			return r;
276		if (type > 0 && type < DISPATCH_MAX &&
277		    type >= SSH2_MSG_KEXINIT && type <= SSH2_MSG_TRANSPORT_MAX &&
278		    ssh->dispatch[type] != NULL) {
279			if ((r = (*ssh->dispatch[type])(type, seqnr, ssh)) != 0)
280				return r;
281		} else {
282			*typep = type;
283			return 0;
284		}
285	}
286}
287
288const u_char *
289ssh_packet_payload(struct ssh *ssh, size_t *lenp)
290{
291	return sshpkt_ptr(ssh, lenp);
292}
293
294int
295ssh_packet_put(struct ssh *ssh, int type, const u_char *data, size_t len)
296{
297	int r;
298
299	if ((r = sshpkt_start(ssh, type)) != 0 ||
300	    (r = sshpkt_put(ssh, data, len)) != 0 ||
301	    (r = sshpkt_send(ssh)) != 0)
302		return r;
303	return 0;
304}
305
306const u_char *
307ssh_output_ptr(struct ssh *ssh, size_t *len)
308{
309	struct sshbuf *output = ssh_packet_get_output(ssh);
310
311	*len = sshbuf_len(output);
312	return sshbuf_ptr(output);
313}
314
315int
316ssh_output_consume(struct ssh *ssh, size_t len)
317{
318	return sshbuf_consume(ssh_packet_get_output(ssh), len);
319}
320
321int
322ssh_output_space(struct ssh *ssh, size_t len)
323{
324	return (0 == sshbuf_check_reserve(ssh_packet_get_output(ssh), len));
325}
326
327int
328ssh_input_space(struct ssh *ssh, size_t len)
329{
330	return (0 == sshbuf_check_reserve(ssh_packet_get_input(ssh), len));
331}
332
333/* Read other side's version identification. */
334int
335_ssh_read_banner(struct ssh *ssh, struct sshbuf *banner)
336{
337	struct sshbuf *input = ssh_packet_get_input(ssh);
338	const char *mismatch = "Protocol mismatch.\r\n";
339	const u_char *s = sshbuf_ptr(input);
340	u_char c;
341	char *cp = NULL, *remote_version = NULL;
342	int r = 0, remote_major, remote_minor, expect_nl;
343	size_t n, j;
344
345	for (j = n = 0;;) {
346		sshbuf_reset(banner);
347		expect_nl = 0;
348		for (;;) {
349			if (j >= sshbuf_len(input))
350				return 0; /* insufficient data in input buf */
351			c = s[j++];
352			if (c == '\r') {
353				expect_nl = 1;
354				continue;
355			}
356			if (c == '\n')
357				break;
358			if (expect_nl)
359				goto bad;
360			if ((r = sshbuf_put_u8(banner, c)) != 0)
361				return r;
362			if (sshbuf_len(banner) > SSH_MAX_BANNER_LEN)
363				goto bad;
364		}
365		if (sshbuf_len(banner) >= 4 &&
366		    memcmp(sshbuf_ptr(banner), "SSH-", 4) == 0)
367			break;
368		debug_f("%.*s", (int)sshbuf_len(banner),
369		    sshbuf_ptr(banner));
370		/* Accept lines before banner only on client */
371		if (ssh->kex->server || ++n > SSH_MAX_PRE_BANNER_LINES) {
372  bad:
373			if ((r = sshbuf_put(ssh_packet_get_output(ssh),
374			    mismatch, strlen(mismatch))) != 0)
375				return r;
376			return SSH_ERR_NO_PROTOCOL_VERSION;
377		}
378	}
379	if ((r = sshbuf_consume(input, j)) != 0)
380		return r;
381
382	/* XXX remote version must be the same size as banner for sscanf */
383	if ((cp = sshbuf_dup_string(banner)) == NULL ||
384	    (remote_version = calloc(1, sshbuf_len(banner))) == NULL) {
385		r = SSH_ERR_ALLOC_FAIL;
386		goto out;
387	}
388
389	/*
390	 * Check that the versions match.  In future this might accept
391	 * several versions and set appropriate flags to handle them.
392	 */
393	if (sscanf(cp, "SSH-%d.%d-%[^\n]\n",
394	    &remote_major, &remote_minor, remote_version) != 3) {
395		r = SSH_ERR_INVALID_FORMAT;
396		goto out;
397	}
398	debug("Remote protocol version %d.%d, remote software version %.100s",
399	    remote_major, remote_minor, remote_version);
400
401	compat_banner(ssh, remote_version);
402	if  (remote_major == 1 && remote_minor == 99) {
403		remote_major = 2;
404		remote_minor = 0;
405	}
406	if (remote_major != 2)
407		r = SSH_ERR_PROTOCOL_MISMATCH;
408
409	debug("Remote version string %.100s", cp);
410 out:
411	free(cp);
412	free(remote_version);
413	return r;
414}
415
416/* Send our own protocol version identification. */
417int
418_ssh_send_banner(struct ssh *ssh, struct sshbuf *banner)
419{
420	char *cp;
421	int r;
422
423	if ((r = sshbuf_putf(banner, "SSH-2.0-%.100s\r\n", SSH_VERSION)) != 0)
424		return r;
425	if ((r = sshbuf_putb(ssh_packet_get_output(ssh), banner)) != 0)
426		return r;
427	/* Remove trailing \r\n */
428	if ((r = sshbuf_consume_end(banner, 2)) != 0)
429		return r;
430	if ((cp = sshbuf_dup_string(banner)) == NULL)
431		return SSH_ERR_ALLOC_FAIL;
432	debug("Local version string %.100s", cp);
433	free(cp);
434	return 0;
435}
436
437int
438_ssh_exchange_banner(struct ssh *ssh)
439{
440	struct kex *kex = ssh->kex;
441	int r;
442
443	/*
444	 * if _ssh_read_banner() cannot parse a full version string
445	 * it will return NULL and we end up calling it again.
446	 */
447
448	r = 0;
449	if (kex->server) {
450		if (sshbuf_len(ssh->kex->server_version) == 0)
451			r = _ssh_send_banner(ssh, ssh->kex->server_version);
452		if (r == 0 &&
453		    sshbuf_len(ssh->kex->server_version) != 0 &&
454		    sshbuf_len(ssh->kex->client_version) == 0)
455			r = _ssh_read_banner(ssh, ssh->kex->client_version);
456	} else {
457		if (sshbuf_len(ssh->kex->server_version) == 0)
458			r = _ssh_read_banner(ssh, ssh->kex->server_version);
459		if (r == 0 &&
460		    sshbuf_len(ssh->kex->server_version) != 0 &&
461		    sshbuf_len(ssh->kex->client_version) == 0)
462			r = _ssh_send_banner(ssh, ssh->kex->client_version);
463	}
464	if (r != 0)
465		return r;
466	/* start initial kex as soon as we have exchanged the banners */
467	if (sshbuf_len(ssh->kex->server_version) != 0 &&
468	    sshbuf_len(ssh->kex->client_version) != 0) {
469		if ((r = _ssh_order_hostkeyalgs(ssh)) != 0 ||
470		    (r = kex_send_kexinit(ssh)) != 0)
471			return r;
472	}
473	return 0;
474}
475
476struct sshkey *
477_ssh_host_public_key(int type, int nid, struct ssh *ssh)
478{
479	struct key_entry *k;
480
481	debug3_f("need %d", type);
482	TAILQ_FOREACH(k, &ssh->public_keys, next) {
483		debug3_f("check %s", sshkey_type(k->key));
484		if (k->key->type == type &&
485		    (type != KEY_ECDSA || k->key->ecdsa_nid == nid))
486			return (k->key);
487	}
488	return (NULL);
489}
490
491struct sshkey *
492_ssh_host_private_key(int type, int nid, struct ssh *ssh)
493{
494	struct key_entry *k;
495
496	debug3_f("need %d", type);
497	TAILQ_FOREACH(k, &ssh->private_keys, next) {
498		debug3_f("check %s", sshkey_type(k->key));
499		if (k->key->type == type &&
500		    (type != KEY_ECDSA || k->key->ecdsa_nid == nid))
501			return (k->key);
502	}
503	return (NULL);
504}
505
506int
507_ssh_verify_host_key(struct sshkey *hostkey, struct ssh *ssh)
508{
509	struct key_entry *k;
510
511	debug3_f("need %s", sshkey_type(hostkey));
512	TAILQ_FOREACH(k, &ssh->public_keys, next) {
513		debug3_f("check %s", sshkey_type(k->key));
514		if (sshkey_equal_public(hostkey, k->key))
515			return (0);	/* ok */
516	}
517	return (-1);	/* failed */
518}
519
520/* offer hostkey algorithms in kexinit depending on registered keys */
521int
522_ssh_order_hostkeyalgs(struct ssh *ssh)
523{
524	struct key_entry *k;
525	char *orig, *avail, *oavail = NULL, *alg, *replace = NULL;
526	char **proposal;
527	size_t maxlen;
528	int ktype, r;
529
530	/* XXX we de-serialize ssh->kex->my, modify it, and change it */
531	if ((r = kex_buf2prop(ssh->kex->my, NULL, &proposal)) != 0)
532		return r;
533	orig = proposal[PROPOSAL_SERVER_HOST_KEY_ALGS];
534	if ((oavail = avail = strdup(orig)) == NULL) {
535		r = SSH_ERR_ALLOC_FAIL;
536		goto out;
537	}
538	maxlen = strlen(avail) + 1;
539	if ((replace = calloc(1, maxlen)) == NULL) {
540		r = SSH_ERR_ALLOC_FAIL;
541		goto out;
542	}
543	*replace = '\0';
544	while ((alg = strsep(&avail, ",")) && *alg != '\0') {
545		if ((ktype = sshkey_type_from_name(alg)) == KEY_UNSPEC)
546			continue;
547		TAILQ_FOREACH(k, &ssh->public_keys, next) {
548			if (k->key->type == ktype ||
549			    (sshkey_is_cert(k->key) && k->key->type ==
550			    sshkey_type_plain(ktype))) {
551				if (*replace != '\0')
552					strlcat(replace, ",", maxlen);
553				strlcat(replace, alg, maxlen);
554				break;
555			}
556		}
557	}
558	if (*replace != '\0') {
559		debug2_f("orig/%d    %s", ssh->kex->server, orig);
560		debug2_f("replace/%d %s", ssh->kex->server, replace);
561		free(orig);
562		proposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = replace;
563		replace = NULL;	/* owned by proposal */
564		r = kex_prop2buf(ssh->kex->my, proposal);
565	}
566 out:
567	free(oavail);
568	free(replace);
569	kex_prop_free(proposal);
570	return r;
571}
572
573int
574_ssh_host_key_sign(struct ssh *ssh, struct sshkey *privkey,
575    struct sshkey *pubkey, u_char **signature, size_t *slen,
576    const u_char *data, size_t dlen, const char *alg)
577{
578	return sshkey_sign(privkey, signature, slen, data, dlen,
579	    alg, NULL, NULL, ssh->compat);
580}
581