xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh_api.c (revision 9469f4f13c84743995b7d51c506f9c9849ba30de)
1 /*	$NetBSD: ssh_api.c,v 1.18 2024/09/24 21:32:19 christos Exp $	*/
2 /* $OpenBSD: ssh_api.c,v 1.31 2024/09/09 02:39:57 djm Exp $ */
3 
4 /*
5  * Copyright (c) 2012 Markus Friedl.  All rights reserved.
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include "includes.h"
21 __RCSID("$NetBSD: ssh_api.c,v 1.18 2024/09/24 21:32:19 christos Exp $");
22 
23 #include <sys/types.h>
24 
25 #include <stdio.h>
26 #include <stdlib.h>
27 
28 #include "ssh_api.h"
29 #include "compat.h"
30 #include "log.h"
31 #include "authfile.h"
32 #include "sshkey.h"
33 #include "dh.h"
34 #include "misc.h"
35 #include "ssh2.h"
36 #include "version.h"
37 #include "myproposal.h"
38 #include "ssherr.h"
39 #include "sshbuf.h"
40 
41 #include <string.h>
42 
43 int	_ssh_exchange_banner(struct ssh *);
44 int	_ssh_send_banner(struct ssh *, struct sshbuf *);
45 int	_ssh_read_banner(struct ssh *, struct sshbuf *);
46 int	_ssh_order_hostkeyalgs(struct ssh *);
47 int	_ssh_verify_host_key(struct sshkey *, struct ssh *);
48 struct sshkey *_ssh_host_public_key(int, int, struct ssh *);
49 struct sshkey *_ssh_host_private_key(int, int, struct ssh *);
50 int	_ssh_host_key_sign(struct ssh *, struct sshkey *, struct sshkey *,
51     u_char **, size_t *, const u_char *, size_t, const char *);
52 
53 /*
54  * stubs for privsep calls in the server side implementation of kex.
55  */
56 int	mm_sshkey_sign(struct sshkey *, u_char **, u_int *,
57     const u_char *, u_int, const char *, const char *, const char *, u_int);
58 
59 #ifdef WITH_OPENSSL
60 DH	*mm_choose_dh(int, int, int);
61 #endif
62 
63 int
64 mm_sshkey_sign(struct sshkey *key, u_char **sigp, u_int *lenp,
65     const u_char *data, u_int datalen, const char *alg,
66     const char *sk_provider, const char *sk_pin, u_int compat)
67 {
68 	size_t slen = 0;
69 	int ret;
70 
71 	ret = sshkey_sign(key, sigp, &slen, data, datalen, alg,
72 	    sk_provider, sk_pin, compat);
73 	*lenp = slen;
74 	return ret;
75 }
76 
77 #ifdef WITH_OPENSSL
78 DH *
79 mm_choose_dh(int min, int nbits, int max)
80 {
81 	return choose_dh(min, nbits, max);
82 }
83 #endif
84 
85 /* API */
86 
87 int
88 ssh_init(struct ssh **sshp, int is_server, struct kex_params *kex_params)
89 {
90 	const char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
91 	char *populated[PROPOSAL_MAX];
92 	struct ssh *ssh;
93 	const char **proposal;
94 	static int called;
95 	int r;
96 
97 	if (!called) {
98 #ifdef WITH_OPENSSL
99 		OpenSSL_add_all_algorithms();
100 #endif
101 		called = 1;
102 	}
103 
104 	if ((ssh = ssh_packet_set_connection(NULL, -1, -1)) == NULL)
105 		return SSH_ERR_ALLOC_FAIL;
106 	if (is_server)
107 		ssh_packet_set_server(ssh);
108 
109 	/* Initialize key exchange */
110 	proposal = kex_params ? __UNCONST(kex_params->proposal) : myproposal;
111 	kex_proposal_populate_entries(ssh, populated,
112 	    proposal[PROPOSAL_KEX_ALGS],
113 	    proposal[PROPOSAL_ENC_ALGS_CTOS],
114 	    proposal[PROPOSAL_MAC_ALGS_CTOS],
115 	    proposal[PROPOSAL_COMP_ALGS_CTOS],
116 	    proposal[PROPOSAL_SERVER_HOST_KEY_ALGS]);
117 	r = kex_ready(ssh, populated);
118 	kex_proposal_free_entries(populated);
119 	if (r != 0) {
120 		ssh_free(ssh);
121 		return r;
122 	}
123 
124 	ssh->kex->server = is_server;
125 	if (is_server) {
126 #ifdef WITH_OPENSSL
127 		ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
128 		ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
129 		ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
130 		ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
131 		ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
132 		ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
133 		ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
134 		ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
135 #endif /* WITH_OPENSSL */
136 		ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_server;
137 		ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
138 		ssh->kex->kex[KEX_KEM_MLKEM768X25519_SHA256] = kex_gen_server;
139 		ssh->kex->load_host_public_key=&_ssh_host_public_key;
140 		ssh->kex->load_host_private_key=&_ssh_host_private_key;
141 		ssh->kex->sign=&_ssh_host_key_sign;
142 	} else {
143 #ifdef WITH_OPENSSL
144 		ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client;
145 		ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client;
146 		ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client;
147 		ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client;
148 		ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client;
149 		ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
150 		ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
151 		ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
152 #endif /* WITH_OPENSSL */
153 		ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
154 		ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client;
155 		ssh->kex->kex[KEX_KEM_MLKEM768X25519_SHA256] = kex_gen_client;
156 		ssh->kex->verify_host_key =&_ssh_verify_host_key;
157 	}
158 	*sshp = ssh;
159 	return 0;
160 }
161 
162 void
163 ssh_free(struct ssh *ssh)
164 {
165 	struct key_entry *k;
166 
167 	if (ssh == NULL)
168 		return;
169 
170 	/*
171 	 * we've only created the public keys variants in case we
172 	 * are a acting as a server.
173 	 */
174 	while ((k = TAILQ_FIRST(&ssh->public_keys)) != NULL) {
175 		TAILQ_REMOVE(&ssh->public_keys, k, next);
176 		if (ssh->kex && ssh->kex->server)
177 			sshkey_free(k->key);
178 		free(k);
179 	}
180 	while ((k = TAILQ_FIRST(&ssh->private_keys)) != NULL) {
181 		TAILQ_REMOVE(&ssh->private_keys, k, next);
182 		free(k);
183 	}
184 	ssh_packet_close(ssh);
185 	free(ssh);
186 }
187 
188 void
189 ssh_set_app_data(struct ssh *ssh, void *app_data)
190 {
191 	ssh->app_data = app_data;
192 }
193 
194 void *
195 ssh_get_app_data(struct ssh *ssh)
196 {
197 	return ssh->app_data;
198 }
199 
200 /* Returns < 0 on error, 0 otherwise */
201 int
202 ssh_add_hostkey(struct ssh *ssh, struct sshkey *key)
203 {
204 	struct sshkey *pubkey = NULL;
205 	struct key_entry *k = NULL, *k_prv = NULL;
206 	int r;
207 
208 	if (ssh->kex->server) {
209 		if ((r = sshkey_from_private(key, &pubkey)) != 0)
210 			return r;
211 		if ((k = malloc(sizeof(*k))) == NULL ||
212 		    (k_prv = malloc(sizeof(*k_prv))) == NULL) {
213 			free(k);
214 			sshkey_free(pubkey);
215 			return SSH_ERR_ALLOC_FAIL;
216 		}
217 		k_prv->key = key;
218 		TAILQ_INSERT_TAIL(&ssh->private_keys, k_prv, next);
219 
220 		/* add the public key, too */
221 		k->key = pubkey;
222 		TAILQ_INSERT_TAIL(&ssh->public_keys, k, next);
223 		r = 0;
224 	} else {
225 		if ((k = malloc(sizeof(*k))) == NULL)
226 			return SSH_ERR_ALLOC_FAIL;
227 		k->key = key;
228 		TAILQ_INSERT_TAIL(&ssh->public_keys, k, next);
229 		r = 0;
230 	}
231 
232 	return r;
233 }
234 
235 int
236 ssh_set_verify_host_key_callback(struct ssh *ssh,
237     int (*cb)(struct sshkey *, struct ssh *))
238 {
239 	if (cb == NULL || ssh->kex == NULL)
240 		return SSH_ERR_INVALID_ARGUMENT;
241 
242 	ssh->kex->verify_host_key = cb;
243 
244 	return 0;
245 }
246 
247 int
248 ssh_input_append(struct ssh *ssh, const u_char *data, size_t len)
249 {
250 	return sshbuf_put(ssh_packet_get_input(ssh), data, len);
251 }
252 
253 int
254 ssh_packet_next(struct ssh *ssh, u_char *typep)
255 {
256 	int r;
257 	u_int32_t seqnr;
258 	u_char type;
259 
260 	/*
261 	 * Try to read a packet. Return SSH_MSG_NONE if no packet or not
262 	 * enough data.
263 	 */
264 	*typep = SSH_MSG_NONE;
265 	if (sshbuf_len(ssh->kex->client_version) == 0 ||
266 	    sshbuf_len(ssh->kex->server_version) == 0)
267 		return _ssh_exchange_banner(ssh);
268 	/*
269 	 * If we enough data and a dispatch function then
270 	 * call the function and get the next packet.
271 	 * Otherwise return the packet type to the caller so it
272 	 * can decide how to go on.
273 	 *
274 	 * We will only call the dispatch function for:
275 	 *     20-29    Algorithm negotiation
276 	 *     30-49    Key exchange method specific (numbers can be reused for
277 	 *              different authentication methods)
278 	 */
279 	for (;;) {
280 		if ((r = ssh_packet_read_poll2(ssh, &type, &seqnr)) != 0)
281 			return r;
282 		if (type > 0 && type < DISPATCH_MAX &&
283 		    type >= SSH2_MSG_KEXINIT && type <= SSH2_MSG_TRANSPORT_MAX &&
284 		    ssh->dispatch[type] != NULL) {
285 			if ((r = (*ssh->dispatch[type])(type, seqnr, ssh)) != 0)
286 				return r;
287 		} else {
288 			*typep = type;
289 			return 0;
290 		}
291 	}
292 }
293 
294 const u_char *
295 ssh_packet_payload(struct ssh *ssh, size_t *lenp)
296 {
297 	return sshpkt_ptr(ssh, lenp);
298 }
299 
300 int
301 ssh_packet_put(struct ssh *ssh, int type, const u_char *data, size_t len)
302 {
303 	int r;
304 
305 	if ((r = sshpkt_start(ssh, type)) != 0 ||
306 	    (r = sshpkt_put(ssh, data, len)) != 0 ||
307 	    (r = sshpkt_send(ssh)) != 0)
308 		return r;
309 	return 0;
310 }
311 
312 const u_char *
313 ssh_output_ptr(struct ssh *ssh, size_t *len)
314 {
315 	struct sshbuf *output = ssh_packet_get_output(ssh);
316 
317 	*len = sshbuf_len(output);
318 	return sshbuf_ptr(output);
319 }
320 
321 int
322 ssh_output_consume(struct ssh *ssh, size_t len)
323 {
324 	return sshbuf_consume(ssh_packet_get_output(ssh), len);
325 }
326 
327 int
328 ssh_output_space(struct ssh *ssh, size_t len)
329 {
330 	return (0 == sshbuf_check_reserve(ssh_packet_get_output(ssh), len));
331 }
332 
333 int
334 ssh_input_space(struct ssh *ssh, size_t len)
335 {
336 	return (0 == sshbuf_check_reserve(ssh_packet_get_input(ssh), len));
337 }
338 
339 /* Read other side's version identification. */
340 int
341 _ssh_read_banner(struct ssh *ssh, struct sshbuf *banner)
342 {
343 	struct sshbuf *input = ssh_packet_get_input(ssh);
344 	const char *mismatch = "Protocol mismatch.\r\n";
345 	const u_char *s = sshbuf_ptr(input);
346 	u_char c;
347 	char *cp = NULL, *remote_version = NULL;
348 	int r = 0, remote_major, remote_minor, expect_nl;
349 	size_t n, j;
350 
351 	for (j = n = 0;;) {
352 		sshbuf_reset(banner);
353 		expect_nl = 0;
354 		for (;;) {
355 			if (j >= sshbuf_len(input))
356 				return 0; /* insufficient data in input buf */
357 			c = s[j++];
358 			if (c == '\r') {
359 				expect_nl = 1;
360 				continue;
361 			}
362 			if (c == '\n')
363 				break;
364 			if (expect_nl)
365 				goto bad;
366 			if ((r = sshbuf_put_u8(banner, c)) != 0)
367 				return r;
368 			if (sshbuf_len(banner) > SSH_MAX_BANNER_LEN)
369 				goto bad;
370 		}
371 		if (sshbuf_len(banner) >= 4 &&
372 		    memcmp(sshbuf_ptr(banner), "SSH-", 4) == 0)
373 			break;
374 		debug_f("%.*s", (int)sshbuf_len(banner),
375 		    sshbuf_ptr(banner));
376 		/* Accept lines before banner only on client */
377 		if (ssh->kex->server || ++n > SSH_MAX_PRE_BANNER_LINES) {
378   bad:
379 			if ((r = sshbuf_put(ssh_packet_get_output(ssh),
380 			    mismatch, strlen(mismatch))) != 0)
381 				return r;
382 			return SSH_ERR_NO_PROTOCOL_VERSION;
383 		}
384 	}
385 	if ((r = sshbuf_consume(input, j)) != 0)
386 		return r;
387 
388 	/* XXX remote version must be the same size as banner for sscanf */
389 	if ((cp = sshbuf_dup_string(banner)) == NULL ||
390 	    (remote_version = calloc(1, sshbuf_len(banner))) == NULL) {
391 		r = SSH_ERR_ALLOC_FAIL;
392 		goto out;
393 	}
394 
395 	/*
396 	 * Check that the versions match.  In future this might accept
397 	 * several versions and set appropriate flags to handle them.
398 	 */
399 	if (sscanf(cp, "SSH-%d.%d-%[^\n]\n",
400 	    &remote_major, &remote_minor, remote_version) != 3) {
401 		r = SSH_ERR_INVALID_FORMAT;
402 		goto out;
403 	}
404 	debug("Remote protocol version %d.%d, remote software version %.100s",
405 	    remote_major, remote_minor, remote_version);
406 
407 	compat_banner(ssh, remote_version);
408 	if  (remote_major == 1 && remote_minor == 99) {
409 		remote_major = 2;
410 		remote_minor = 0;
411 	}
412 	if (remote_major != 2)
413 		r = SSH_ERR_PROTOCOL_MISMATCH;
414 
415 	debug("Remote version string %.100s", cp);
416  out:
417 	free(cp);
418 	free(remote_version);
419 	return r;
420 }
421 
422 /* Send our own protocol version identification. */
423 int
424 _ssh_send_banner(struct ssh *ssh, struct sshbuf *banner)
425 {
426 	char *cp;
427 	int r;
428 
429 	if ((r = sshbuf_putf(banner, "SSH-2.0-%.100s\r\n", SSH_VERSION)) != 0)
430 		return r;
431 	if ((r = sshbuf_putb(ssh_packet_get_output(ssh), banner)) != 0)
432 		return r;
433 	/* Remove trailing \r\n */
434 	if ((r = sshbuf_consume_end(banner, 2)) != 0)
435 		return r;
436 	if ((cp = sshbuf_dup_string(banner)) == NULL)
437 		return SSH_ERR_ALLOC_FAIL;
438 	debug("Local version string %.100s", cp);
439 	free(cp);
440 	return 0;
441 }
442 
443 int
444 _ssh_exchange_banner(struct ssh *ssh)
445 {
446 	struct kex *kex = ssh->kex;
447 	int r;
448 
449 	/*
450 	 * if _ssh_read_banner() cannot parse a full version string
451 	 * it will return NULL and we end up calling it again.
452 	 */
453 
454 	r = 0;
455 	if (kex->server) {
456 		if (sshbuf_len(ssh->kex->server_version) == 0)
457 			r = _ssh_send_banner(ssh, ssh->kex->server_version);
458 		if (r == 0 &&
459 		    sshbuf_len(ssh->kex->server_version) != 0 &&
460 		    sshbuf_len(ssh->kex->client_version) == 0)
461 			r = _ssh_read_banner(ssh, ssh->kex->client_version);
462 	} else {
463 		if (sshbuf_len(ssh->kex->server_version) == 0)
464 			r = _ssh_read_banner(ssh, ssh->kex->server_version);
465 		if (r == 0 &&
466 		    sshbuf_len(ssh->kex->server_version) != 0 &&
467 		    sshbuf_len(ssh->kex->client_version) == 0)
468 			r = _ssh_send_banner(ssh, ssh->kex->client_version);
469 	}
470 	if (r != 0)
471 		return r;
472 	/* start initial kex as soon as we have exchanged the banners */
473 	if (sshbuf_len(ssh->kex->server_version) != 0 &&
474 	    sshbuf_len(ssh->kex->client_version) != 0) {
475 		if ((r = _ssh_order_hostkeyalgs(ssh)) != 0 ||
476 		    (r = kex_send_kexinit(ssh)) != 0)
477 			return r;
478 	}
479 	return 0;
480 }
481 
482 struct sshkey *
483 _ssh_host_public_key(int type, int nid, struct ssh *ssh)
484 {
485 	struct key_entry *k;
486 
487 	debug3_f("need %d", type);
488 	TAILQ_FOREACH(k, &ssh->public_keys, next) {
489 		debug3_f("check %s", sshkey_type(k->key));
490 		if (k->key->type == type &&
491 		    (type != KEY_ECDSA || k->key->ecdsa_nid == nid))
492 			return (k->key);
493 	}
494 	return (NULL);
495 }
496 
497 struct sshkey *
498 _ssh_host_private_key(int type, int nid, struct ssh *ssh)
499 {
500 	struct key_entry *k;
501 
502 	debug3_f("need %d", type);
503 	TAILQ_FOREACH(k, &ssh->private_keys, next) {
504 		debug3_f("check %s", sshkey_type(k->key));
505 		if (k->key->type == type &&
506 		    (type != KEY_ECDSA || k->key->ecdsa_nid == nid))
507 			return (k->key);
508 	}
509 	return (NULL);
510 }
511 
512 int
513 _ssh_verify_host_key(struct sshkey *hostkey, struct ssh *ssh)
514 {
515 	struct key_entry *k;
516 
517 	debug3_f("need %s", sshkey_type(hostkey));
518 	TAILQ_FOREACH(k, &ssh->public_keys, next) {
519 		debug3_f("check %s", sshkey_type(k->key));
520 		if (sshkey_equal_public(hostkey, k->key))
521 			return (0);	/* ok */
522 	}
523 	return (-1);	/* failed */
524 }
525 
526 /* offer hostkey algorithms in kexinit depending on registered keys */
527 int
528 _ssh_order_hostkeyalgs(struct ssh *ssh)
529 {
530 	struct key_entry *k;
531 	char *orig, *avail, *oavail = NULL, *alg, *replace = NULL;
532 	char **proposal;
533 	size_t maxlen;
534 	int ktype, r;
535 
536 	/* XXX we de-serialize ssh->kex->my, modify it, and change it */
537 	if ((r = kex_buf2prop(ssh->kex->my, NULL, &proposal)) != 0)
538 		return r;
539 	orig = proposal[PROPOSAL_SERVER_HOST_KEY_ALGS];
540 	if ((oavail = avail = strdup(orig)) == NULL) {
541 		r = SSH_ERR_ALLOC_FAIL;
542 		goto out;
543 	}
544 	maxlen = strlen(avail) + 1;
545 	if ((replace = calloc(1, maxlen)) == NULL) {
546 		r = SSH_ERR_ALLOC_FAIL;
547 		goto out;
548 	}
549 	*replace = '\0';
550 	while ((alg = strsep(&avail, ",")) && *alg != '\0') {
551 		if ((ktype = sshkey_type_from_name(alg)) == KEY_UNSPEC)
552 			continue;
553 		TAILQ_FOREACH(k, &ssh->public_keys, next) {
554 			if (k->key->type == ktype ||
555 			    (sshkey_is_cert(k->key) && k->key->type ==
556 			    sshkey_type_plain(ktype))) {
557 				if (*replace != '\0')
558 					strlcat(replace, ",", maxlen);
559 				strlcat(replace, alg, maxlen);
560 				break;
561 			}
562 		}
563 	}
564 	if (*replace != '\0') {
565 		debug2_f("orig/%d    %s", ssh->kex->server, orig);
566 		debug2_f("replace/%d %s", ssh->kex->server, replace);
567 		free(orig);
568 		proposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = replace;
569 		replace = NULL;	/* owned by proposal */
570 		r = kex_prop2buf(ssh->kex->my, proposal);
571 	}
572  out:
573 	free(oavail);
574 	free(replace);
575 	kex_prop_free(proposal);
576 	return r;
577 }
578 
579 int
580 _ssh_host_key_sign(struct ssh *ssh, struct sshkey *privkey,
581     struct sshkey *pubkey, u_char **signature, size_t *slen,
582     const u_char *data, size_t dlen, const char *alg)
583 {
584 	return sshkey_sign(privkey, signature, slen, data, dlen,
585 	    alg, NULL, NULL, ssh->compat);
586 }
587