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