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