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