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