blob: e244c3b834a853828c370330bea8a30ddadb2071 [file] [log] [blame]
Michal Vasko086311b2016-01-08 09:53:11 +01001/**
Michal Vasko95ea9ff2021-11-09 12:29:14 +01002 * @file session_server_ssh.c
3 * @author Michal Vasko <mvasko@cesnet.cz>
4 * @brief libnetconf2 SSH server session manipulation functions
Michal Vasko086311b2016-01-08 09:53:11 +01005 *
Michal Vasko95ea9ff2021-11-09 12:29:14 +01006 * @copyright
7 * Copyright (c) 2017 - 2021 CESNET, z.s.p.o.
Michal Vasko086311b2016-01-08 09:53:11 +01008 *
Radek Krejci9b81f5b2016-02-24 13:14:49 +01009 * This source code is licensed under BSD 3-Clause License (the "License").
10 * You may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
Michal Vaskoafd416b2016-02-25 14:51:46 +010012 *
Radek Krejci9b81f5b2016-02-24 13:14:49 +010013 * https://opensource.org/licenses/BSD-3-Clause
Michal Vasko086311b2016-01-08 09:53:11 +010014 */
15
16#define _GNU_SOURCE
17
romanc6518422023-11-30 16:39:00 +010018#include "config.h" /* Expose HAVE_LIBPAM and HAVE_SHADOW */
apropp-molex4e903c32020-04-20 03:06:58 -040019
Michal Vasko0d81c572022-09-26 10:39:31 +020020#ifdef HAVE_LIBPAM
roman068eb402023-11-02 15:27:04 +010021# include <security/pam_appl.h>
Michal Vasko0d81c572022-09-26 10:39:31 +020022#endif
romanc6518422023-11-30 16:39:00 +010023#ifdef HAVE_SHADOW
24# include <shadow.h>
25#endif
apropp-molex4e903c32020-04-20 03:06:58 -040026
romanf578cd52023-10-19 09:47:40 +020027#include <arpa/inet.h>
28#include <assert.h>
romana9ec3362023-12-21 10:59:57 +010029#include <ctype.h>
Michal Vaskob83a3fa2021-05-26 09:53:42 +020030#include <errno.h>
romanf578cd52023-10-19 09:47:40 +020031#include <libssh/libssh.h>
32#include <libssh/server.h>
33#include <libyang/libyang.h>
Michal Vaskob83a3fa2021-05-26 09:53:42 +020034#include <pwd.h>
romanf578cd52023-10-19 09:47:40 +020035#include <stdint.h>
Michal Vasko086311b2016-01-08 09:53:11 +010036#include <stdlib.h>
37#include <string.h>
Michal Vasko27252692017-03-21 15:34:13 +010038#include <sys/stat.h>
Michal Vaskob83a3fa2021-05-26 09:53:42 +020039#include <sys/types.h>
Michal Vasko9f6275e2017-10-05 13:50:05 +020040#include <time.h>
Claus Klein22091912020-01-20 13:45:47 +010041#include <unistd.h>
Michal Vasko086311b2016-01-08 09:53:11 +010042
Michal Vasko7a20d2e2021-05-19 16:40:23 +020043#include "compat.h"
romanf578cd52023-10-19 09:47:40 +020044#include "log_p.h"
45#include "session.h"
46#include "session_p.h"
roman83289292024-04-05 12:33:24 +020047#include "session_wrapper.h"
Michal Vasko086311b2016-01-08 09:53:11 +010048
49extern struct nc_server_opts server_opts;
Michal Vaskob05053d2016-01-22 16:12:06 +010050
roman1ea193e2024-05-22 14:16:41 +020051/**
52 * @brief Stores the private key data as a temporary file.
53 *
54 * @param[in] in Private key data.
55 * @param[in] privkey_format String representation of the private key format.
56 * @return Path to the created temporary file or NULL on fail.
57 */
Michal Vasko4c1fb492017-01-30 14:31:07 +010058static char *
roman1ea193e2024-05-22 14:16:41 +020059nc_server_ssh_privkey_data_to_tmp_file(const char *in, const char *privkey_format)
Michal Vasko086311b2016-01-08 09:53:11 +010060{
Michal Vasko4c1fb492017-01-30 14:31:07 +010061 char path[12] = "/tmp/XXXXXX";
62 int fd, written;
romanf578cd52023-10-19 09:47:40 +020063 unsigned len;
Michal Vasko27252692017-03-21 15:34:13 +010064 mode_t umode;
Michal Vasko4c1fb492017-01-30 14:31:07 +010065 FILE *file;
66
romanf578cd52023-10-19 09:47:40 +020067 NC_CHECK_ARG_RET(NULL, in, NULL);
Michal Vasko086311b2016-01-08 09:53:11 +010068
mekleob31878b2019-09-09 14:10:47 +020069 umode = umask(0177);
Michal Vasko4c1fb492017-01-30 14:31:07 +010070 fd = mkstemp(path);
Michal Vasko27252692017-03-21 15:34:13 +010071 umask(umode);
Michal Vasko4c1fb492017-01-30 14:31:07 +010072 if (fd == -1) {
73 return NULL;
74 }
75
Michal Vasko3964a832018-09-18 14:37:39 +020076 file = fdopen(fd, "w");
Michal Vasko4c1fb492017-01-30 14:31:07 +010077 if (!file) {
78 close(fd);
79 return NULL;
80 }
81
romanf578cd52023-10-19 09:47:40 +020082 /* write header */
romand0fe5952024-03-21 15:59:33 +010083 written = fwrite("-----BEGIN", 1, 10, file);
romanf578cd52023-10-19 09:47:40 +020084 if (privkey_format) {
85 written += fwrite(privkey_format, 1, strlen(privkey_format), file);
romanf578cd52023-10-19 09:47:40 +020086 written += fwrite("PRIVATE KEY-----\n", 1, 17, file);
romand0fe5952024-03-21 15:59:33 +010087 } else {
88 written += fwrite(" PRIVATE KEY-----\n", 1, 18, file);
romanf578cd52023-10-19 09:47:40 +020089 }
Michal Vasko68177b72020-04-27 15:46:53 +020090
romanf578cd52023-10-19 09:47:40 +020091 /* write data */
92 written += fwrite(in, 1, strlen(in), file);
93
94 /* write footer */
romand0fe5952024-03-21 15:59:33 +010095 written += fwrite("\n-----END", 1, 9, file);
romanf578cd52023-10-19 09:47:40 +020096 if (privkey_format) {
97 written += fwrite(privkey_format, 1, strlen(privkey_format), file);
romanf578cd52023-10-19 09:47:40 +020098 written += fwrite("PRIVATE KEY-----", 1, 16, file);
romand0fe5952024-03-21 15:59:33 +010099 } else {
100 written += fwrite(" PRIVATE KEY-----", 1, 17, file);
romanf578cd52023-10-19 09:47:40 +0200101 }
102
103 fclose(file);
104
105 /* checksum */
106 if (privkey_format) {
romand0fe5952024-03-21 15:59:33 +0100107 len = 10 + strlen(privkey_format) + 17 + strlen(in) + 9 + strlen(privkey_format) + 16;
romanf578cd52023-10-19 09:47:40 +0200108 } else {
romand0fe5952024-03-21 15:59:33 +0100109 len = 10 + 18 + strlen(in) + 9 + 17;
romanf578cd52023-10-19 09:47:40 +0200110 }
111
112 if ((unsigned)written != len) {
113 unlink(path);
114 return NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +0100115 }
116
117 return strdup(path);
118}
119
roman1ea193e2024-05-22 14:16:41 +0200120/**
121 * @brief Get asymmetric key from the keystore.
122 *
123 * @param[in] referenced_name Name of the asymmetric key in the keystore.
124 * @param[out] askey Referenced asymmetric key.
125 * @return 0 on success, 1 on error.
126 */
Michal Vasko4c1fb492017-01-30 14:31:07 +0100127static int
romanf578cd52023-10-19 09:47:40 +0200128nc_server_ssh_ks_ref_get_key(const char *referenced_name, struct nc_asymmetric_key **askey)
Michal Vasko4c1fb492017-01-30 14:31:07 +0100129{
romanf578cd52023-10-19 09:47:40 +0200130 uint16_t i;
131 struct nc_keystore *ks = &server_opts.keystore;
Michal Vaskofbfe8b62017-02-14 10:22:30 +0100132
romanf578cd52023-10-19 09:47:40 +0200133 *askey = NULL;
Michal Vaskod45e25a2016-01-08 15:48:44 +0100134
romanf578cd52023-10-19 09:47:40 +0200135 /* lookup name */
136 for (i = 0; i < ks->asym_key_count; i++) {
137 if (!strcmp(referenced_name, ks->asym_keys[i].name)) {
138 break;
Michal Vaskofbfe8b62017-02-14 10:22:30 +0100139 }
140 }
141
romanf578cd52023-10-19 09:47:40 +0200142 if (i == ks->asym_key_count) {
143 ERR(NULL, "Keystore entry \"%s\" not found.", referenced_name);
144 return 1;
Michal Vaskoe2713da2016-08-22 16:06:40 +0200145 }
Michal Vasko7d255882017-02-09 13:35:08 +0100146
romanf578cd52023-10-19 09:47:40 +0200147 *askey = &ks->asym_keys[i];
148
149 /* check if the referenced public key is SubjectPublicKeyInfo */
150 if ((*askey)->pubkey_data && nc_is_pk_subject_public_key_info((*askey)->pubkey_data)) {
151 ERR(NULL, "The public key of the referenced hostkey \"%s\" is in the SubjectPublicKeyInfo format, "
152 "which is not allowed in the SSH!", referenced_name);
153 return 1;
Michal Vasko7d255882017-02-09 13:35:08 +0100154 }
Michal Vaskoe2713da2016-08-22 16:06:40 +0200155
Michal Vasko5fcc7142016-02-02 12:21:10 +0100156 return 0;
Michal Vaskob05053d2016-01-22 16:12:06 +0100157}
158
roman1ea193e2024-05-22 14:16:41 +0200159/**
160 * @brief Get public keys from the truststore.
161 *
162 * @param[in] referenced_name Name of the public key bag in the truststore.
163 * @param[out] pubkeys Referenced public keys.
164 * @param[out] pubkey_count Referenced public key count.
165 * @return 0 on success, 1 on error.
166 */
romanf578cd52023-10-19 09:47:40 +0200167static int
168nc_server_ssh_ts_ref_get_keys(const char *referenced_name, struct nc_public_key **pubkeys, uint16_t *pubkey_count)
Michal Vaskob05053d2016-01-22 16:12:06 +0100169{
romanf578cd52023-10-19 09:47:40 +0200170 uint16_t i, j;
171 struct nc_truststore *ts = &server_opts.truststore;
Michal Vasko3031aae2016-01-27 16:07:18 +0100172
romanf578cd52023-10-19 09:47:40 +0200173 *pubkeys = NULL;
174 *pubkey_count = 0;
175
176 /* lookup name */
177 for (i = 0; i < ts->pub_bag_count; i++) {
178 if (!strcmp(referenced_name, ts->pub_bags[i].name)) {
179 break;
180 }
Michal Vasko3031aae2016-01-27 16:07:18 +0100181 }
Michal Vaskoc46b3df2021-07-26 09:30:05 +0200182
romanf578cd52023-10-19 09:47:40 +0200183 if (i == ts->pub_bag_count) {
184 ERR(NULL, "Truststore entry \"%s\" not found.", referenced_name);
185 return 1;
186 }
Michal Vaskoc46b3df2021-07-26 09:30:05 +0200187
romanf578cd52023-10-19 09:47:40 +0200188 /* check if any of the referenced public keys is SubjectPublicKeyInfo */
189 for (j = 0; j < ts->pub_bags[i].pubkey_count; j++) {
190 if (nc_is_pk_subject_public_key_info(ts->pub_bags[i].pubkeys[j].data)) {
191 ERR(NULL, "A public key of the referenced public key bag \"%s\" is in the SubjectPublicKeyInfo format, "
192 "which is not allowed in the SSH!", referenced_name);
193 return 1;
194 }
195 }
Michal Vasko3031aae2016-01-27 16:07:18 +0100196
romanf578cd52023-10-19 09:47:40 +0200197 *pubkeys = ts->pub_bags[i].pubkeys;
198 *pubkey_count = ts->pub_bags[i].pubkey_count;
199 return 0;
Michal Vaskob05053d2016-01-22 16:12:06 +0100200}
201
roman1ea193e2024-05-22 14:16:41 +0200202/**
203 * @brief Convert UID to string.
204 *
205 * @param[in] uid UID to convert.
206 * @return UID converted to string or NULL on fail.
207 */
romana9ec3362023-12-21 10:59:57 +0100208static char *
209nc_server_ssh_uid_to_str(uid_t uid)
210{
211 int buf_len;
212 char *uid_str;
213
214 /* get the number of digits and alloc */
215 buf_len = snprintf(NULL, 0, "%u", uid);
216 uid_str = malloc(buf_len + 1);
217 NC_CHECK_ERRMEM_RET(!uid_str, NULL);
218
219 /* convert to string */
220 sprintf(uid_str, "%u", uid);
221 uid_str[buf_len] = '\0';
222 return uid_str;
223}
224
roman1ea193e2024-05-22 14:16:41 +0200225/**
226 * @brief Append a character or a string to a string.
227 *
228 * @param[in] src_c Source character.
229 * @param[in] src_str Source string.
230 * @param[in,out] size Size of the destination string.
231 * @param[out] idx Index of the next character to write.
232 * @param[out] dst Destination string.
233 * @return 0 on success, 1 on error.
234 */
romana9ec3362023-12-21 10:59:57 +0100235static int
236nc_server_ssh_str_append(const char src_c, const char *src_str, int *size, int *idx, char **dst)
237{
238 int src_size, allocate = 0, ret;
239
240 /* get size of char/string we want to append */
241 if (src_str) {
242 src_size = strlen(src_str);
243 } else {
244 src_size = 1;
245 }
246
247 /* check if we have enough space, if not realloc */
248 while ((src_size + *idx) >= *size) {
249 (*size) += 16;
250 allocate = 1;
251 }
252 if (allocate) {
253 *dst = nc_realloc(*dst, *size);
254 NC_CHECK_ERRMEM_RET(!*dst, 1);
255 }
256
257 /* append the char/string */
258 if (src_str) {
259 ret = sprintf(*dst + *idx, "%s", src_str);
260 } else {
261 ret = sprintf(*dst + *idx, "%c", src_c);
262 }
263 if (ret < 0) {
264 return 1;
265 }
266
267 *idx += ret;
268 return 0;
269}
270
roman1ea193e2024-05-22 14:16:41 +0200271/**
272 * @brief Get the path to the system public keys from format set by an API.
273 *
274 * @param[in] username Username.
275 * @param[out] out_path Path to the system public keys.
276 * @return 0 on success, 1 on error.
277 */
romana9ec3362023-12-21 10:59:57 +0100278static int
279nc_server_ssh_get_system_keys_path(const char *username, char **out_path)
280{
281 int ret = 0, i, have_percent = 0, size = 0, idx = 0;
282 const char *path_fmt = server_opts.authkey_path_fmt;
283 char *path = NULL, *buf = NULL, *uid = NULL;
284 struct passwd *pw, pw_buf;
285 size_t buf_len = 0;
286
roman19207722024-05-22 14:18:20 +0200287 if (!path_fmt) {
288 ERR(NULL, "System public keys path format not set.");
289 return 1;
290 }
291
romana9ec3362023-12-21 10:59:57 +0100292 /* check if the path format contains any tokens */
293 if (strstr(path_fmt, "%h") || strstr(path_fmt, "%U") || strstr(path_fmt, "%u") || strstr(path_fmt, "%%")) {
294 /* get pw */
295 pw = nc_getpw(0, username, &pw_buf, &buf, &buf_len);
296 if (!pw) {
297 ERR(NULL, "Unable to get passwd entry for user \"%s\".", username);
298 ret = 1;
299 goto cleanup;
300 }
301
302 /* convert UID to a string */
303 uid = nc_server_ssh_uid_to_str(pw->pw_uid);
304 if (!uid) {
305 ret = 1;
306 goto cleanup;
307 }
308 } else {
309 /* no tokens, just copy the path and return */
310 *out_path = strdup(path_fmt);
311 NC_CHECK_ERRMEM_RET(!*out_path, 1);
312 goto cleanup;
313 }
314
315 /* go over characters from format, copy them to path and interpret tokens correctly */
316 for (i = 0; path_fmt[i]; i++) {
317 if (have_percent) {
318 /* special token, need to convert it */
319 if (path_fmt[i] == '%') {
320 ret = nc_server_ssh_str_append('%', NULL, &size, &idx, &path);
321 } else if (path_fmt[i] == 'h') {
322 /* user home */
323 ret = nc_server_ssh_str_append(0, pw->pw_dir, &size, &idx, &path);
324 } else if (path_fmt[i] == 'u') {
325 /* username */
326 ret = nc_server_ssh_str_append(0, username, &size, &idx, &path);
327 } else if (path_fmt[i] == 'U') {
328 /* UID */
329 ret = nc_server_ssh_str_append(0, uid, &size, &idx, &path);
330 } else {
331 ERR(NULL, "Failed to parse system public keys path format \"%s\".", server_opts.authkey_path_fmt);
332 ret = 1;
333 }
334
335 have_percent = 0;
336 } else {
337 if (path_fmt[i] == '%') {
338 have_percent = 1;
339 } else {
340 /* ordinary character with no meaning */
341 ret = nc_server_ssh_str_append(path_fmt[i], NULL, &size, &idx, &path);
342 }
343 }
344
345 if (ret) {
346 free(path);
347 goto cleanup;
348 }
349 }
350
351 *out_path = path;
352cleanup:
353 free(uid);
354 free(buf);
355 return ret;
356}
357
roman1ea193e2024-05-22 14:16:41 +0200358/**
359 * @brief Read public keys from the authorized keys file.
360 *
361 * @param[in] path Path to the authorized keys file.
362 * @param[out] pubkeys Public keys.
363 * @param[out] pubkey_count Public key count.
364 * @return 0 on success, 1 on error.
365 */
romana9ec3362023-12-21 10:59:57 +0100366static int
367nc_server_ssh_read_authorized_keys_file(const char *path, struct nc_public_key **pubkeys, uint16_t *pubkey_count)
368{
roman1ea193e2024-05-22 14:16:41 +0200369 int ret = 0, rc, line_num = 0;
romana9ec3362023-12-21 10:59:57 +0100370 FILE *f = NULL;
371 char *line = NULL, *ptr, *ptr2;
372 size_t n;
373 enum ssh_keytypes_e ktype;
374
375 NC_CHECK_ARG_RET(NULL, path, pubkeys, 1);
376
377 *pubkeys = NULL;
378 *pubkey_count = 0;
379
380 f = fopen(path, "r");
381 if (!f) {
382 ERR(NULL, "Unable to open \"%s\" (%s).", path, strerror(errno));
383 ret = 1;
384 goto cleanup;
385 }
386
387 while (getline(&line, &n, f) > -1) {
388 ++line_num;
389 if ((line[0] == '#') || (line[0] == '\n')) {
390 /* comment or empty line */
391 continue;
392 }
393
394 /* separate key type */
395 ptr = line;
396 for (ptr2 = ptr; ptr2[0] && !isspace(ptr2[0]); ptr2++) {}
397 if (!ptr2[0]) {
398 ERR(NULL, "Invalid format of authorized keys file \"%s\" on line %d.", path, line_num);
399 ret = 1;
400 goto cleanup;
401 }
402 ptr2[0] = '\0';
403
404 /* detect key type */
405 ktype = ssh_key_type_from_name(ptr);
406 if ((ktype != SSH_KEYTYPE_RSA) && (ktype != SSH_KEYTYPE_ECDSA_P256) && (ktype != SSH_KEYTYPE_ECDSA_P384) &&
407 (ktype != SSH_KEYTYPE_ECDSA_P521) && (ktype != SSH_KEYTYPE_ED25519)) {
408 WRN(NULL, "Unsupported key type \"%s\" in authorized keys file \"%s\" on line %d.", ptr, path, line_num);
409 continue;
410 }
411
412 /* get key data */
413 ptr = ptr2 + 1;
414 for (ptr2 = ptr; ptr2[0] && !isspace(ptr2[0]); ptr2++) {}
415 ptr2[0] = '\0';
416
417 /* add the key */
418 *pubkeys = nc_realloc(*pubkeys, (*pubkey_count + 1) * sizeof **pubkeys);
419 NC_CHECK_ERRMEM_GOTO(!(*pubkeys), ret = 1, cleanup);
roman1ea193e2024-05-22 14:16:41 +0200420 rc = asprintf(&(*pubkeys)[*pubkey_count].name, "authorized_key_%" PRIu16, *pubkey_count);
421 NC_CHECK_ERRMEM_GOTO(rc == -1, (*pubkeys)[*pubkey_count].name = NULL; ret = 1, cleanup);
romana9ec3362023-12-21 10:59:57 +0100422 (*pubkeys)[*pubkey_count].type = NC_PUBKEY_FORMAT_SSH;
423 (*pubkeys)[*pubkey_count].data = strdup(ptr);
424 NC_CHECK_ERRMEM_GOTO(!(*pubkeys)[*pubkey_count].data, ret = 1, cleanup);
425 (*pubkey_count)++;
426 }
427
428 /* ok */
429 ret = 0;
430cleanup:
431 if (f) {
432 fclose(f);
433 }
434 free(line);
435 return ret;
436}
437
roman1ea193e2024-05-22 14:16:41 +0200438/**
439 * @brief Get user's public keys from the system.
440 *
441 * @param[in] username Username.
442 * @param[out] pubkeys User's public keys.
443 * @param[out] pubkey_count Public key count.
444 * @return 0 on success, non-zero on error.
445 */
romana9ec3362023-12-21 10:59:57 +0100446static int
447nc_server_ssh_get_system_keys(const char *username, struct nc_public_key **pubkeys, uint16_t *pubkey_count)
448{
449 int ret = 0;
450 char *path = NULL;
451
452 /* convert the path format to get the actual path */
453 ret = nc_server_ssh_get_system_keys_path(username, &path);
454 if (ret) {
455 ERR(NULL, "Getting system keys path failed.");
456 goto cleanup;
457 }
458
459 /* get the keys */
460 ret = nc_server_ssh_read_authorized_keys_file(path, pubkeys, pubkey_count);
461 if (ret) {
462 ERR(NULL, "Reading system keys failed.");
463 goto cleanup;
464 }
465
466cleanup:
467 free(path);
468 return ret;
469}
470
romanbe162202024-05-22 14:19:23 +0200471#ifdef HAVE_SHADOW
472
Michal Vaskof3c41e32022-09-09 11:22:21 +0200473/**
romanbe162202024-05-22 14:19:23 +0200474 * @brief Get the user's /etc/passwd entry.
Michal Vaskof3c41e32022-09-09 11:22:21 +0200475 *
romanbe162202024-05-22 14:19:23 +0200476 * @param[in] username Username.
477 * @param[out] pwd_buf Buffer for the passwd structure.
478 * @param[out] buf Buffer for the pwd's strings.
479 * @param[out] buf_size Size of the buffer.
480 * @return User's passwd entry or NULL on error.
481 */
482static struct passwd *
483nc_server_ssh_getpwnam(const char *username, struct passwd *pwd_buf, char **buf, size_t *buf_size)
484{
485 struct passwd *pwd = NULL;
486 char *mem;
487 int r = 0;
488
489 do {
490 r = getpwnam_r(username, pwd_buf, *buf, *buf_size, &pwd);
491 if (pwd) {
492 /* entry found */
493 break;
494 }
495
496 if (r == ERANGE) {
497 /* small buffer, enlarge */
498 *buf_size <<= 2;
499 mem = realloc(*buf, *buf_size);
500 if (!mem) {
501 ERRMEM;
502 return NULL;
503 }
504 *buf = mem;
505 }
506 } while (r == ERANGE);
507
508 return pwd;
509}
510
511/**
512 * @brief Get the user's /etc/shadow entry.
513 *
514 * @param[in] username Username.
515 * @param[out] spwd_buf Buffer for the spwd structure.
516 * @param[out] buf Buffer for the spwd's strings.
517 * @param[out] buf_size Size of the buffer.
518 * @return User's shadow entry or NULL on error.
519 */
520static struct spwd *
521nc_server_ssh_getspnam(const char *username, struct spwd *spwd_buf, char **buf, size_t *buf_size)
522{
523 struct spwd *spwd = NULL;
524 char *mem;
525 int r = 0;
526
527 do {
528# ifndef __QNXNTO__
529 r = getspnam_r(username, spwd_buf, *buf, *buf_size, &spwd);
530# else
531 spwd = getspnam_r(username, spwd_buf, *buf, *buf_size);
roman90420232024-05-23 14:45:02 +0200532 r = errno;
romanbe162202024-05-22 14:19:23 +0200533# endif
534 if (spwd) {
535 /* entry found */
536 break;
537 }
538
539 if (r == ERANGE) {
540 /* small buffer, enlarge */
541 *buf_size <<= 2;
542 mem = realloc(*buf, *buf_size);
543 if (!mem) {
544 ERRMEM;
545 return NULL;
546 }
547 *buf = mem;
548 }
549 } while (r == ERANGE);
550
551 return spwd;
552}
553
554/**
555 * @brief Get the user's hashed password from the system.
556 *
557 * @param[in] username Username.
558 * @return User's hashed password or NULL on error.
559 */
560static char *
561nc_server_ssh_get_pwd_hash(const char *username)
562{
563 struct passwd *pwd, pwd_buf;
564 struct spwd *spwd, spwd_buf;
565 char *pass_hash = NULL, *buf = NULL;
566 size_t buf_size = 256;
567
568 buf = malloc(buf_size);
569 NC_CHECK_ERRMEM_GOTO(!buf, , error);
570
571 pwd = nc_server_ssh_getpwnam(username, &pwd_buf, &buf, &buf_size);
572 if (!pwd) {
roman5858e6d2024-05-23 09:18:22 +0200573 VRB(NULL, "User \"%s\" not found in the system.", username);
romanbe162202024-05-22 14:19:23 +0200574 goto error;
575 }
576
577 if (!strcmp(pwd->pw_passwd, "x")) {
578 spwd = nc_server_ssh_getspnam(username, &spwd_buf, &buf, &buf_size);
579 if (!spwd) {
580 VRB(NULL, "Failed to retrieve the shadow entry for \"%s\".", username);
581 goto error;
582 } else if ((spwd->sp_expire > -1) && (spwd->sp_expire <= (time(NULL) / (60 * 60 * 24)))) {
583 WRN(NULL, "User \"%s\" account has expired.", username);
584 goto error;
585 }
586
587 pass_hash = spwd->sp_pwdp;
588 } else {
589 pass_hash = pwd->pw_passwd;
590 }
591
592 if (!pass_hash) {
593 ERR(NULL, "No password could be retrieved for \"%s\".", username);
594 goto error;
595 }
596
597 /* check the hash structure for special meaning */
598 if (!strcmp(pass_hash, "*") || !strcmp(pass_hash, "!")) {
599 VRB(NULL, "User \"%s\" is not allowed to authenticate using a password.", username);
600 goto error;
601 }
602 if (!strcmp(pass_hash, "*NP*")) {
603 VRB(NULL, "Retrieving password for \"%s\" from a NIS+ server not supported.", username);
604 goto error;
605 }
606
607 pass_hash = strdup(pass_hash);
608 free(buf);
609 return pass_hash;
610
611error:
612 free(buf);
613 return NULL;
614}
615
616#endif
617
618/**
619 * @brief Compare stored hashed password with a cleartext received password.
620 *
621 * @param[in] stored_pw Hashed stored password.
622 * @param[in] received_pw Cleartext received password.
623 * @return 0 on match, non-zero otherwise.
Michal Vaskof3c41e32022-09-09 11:22:21 +0200624 */
Michal Vasko086311b2016-01-08 09:53:11 +0100625static int
romanbe162202024-05-22 14:19:23 +0200626nc_server_ssh_compare_password(const char *stored_pw, const char *received_pw)
Michal Vasko086311b2016-01-08 09:53:11 +0100627{
roman814f5112023-10-19 15:51:16 +0200628 char *received_pw_hash = NULL;
roman8b1a6c32023-10-26 13:35:22 +0200629 struct crypt_data cdata = {0};
Michal Vasko086311b2016-01-08 09:53:11 +0100630
romanbe162202024-05-22 14:19:23 +0200631 NC_CHECK_ARG_RET(NULL, stored_pw, received_pw, 1);
632
roman814f5112023-10-19 15:51:16 +0200633 if (!stored_pw[0]) {
634 if (!received_pw[0]) {
Michal Vasko05532772021-06-03 12:12:38 +0200635 WRN(NULL, "User authentication successful with an empty password!");
Michal Vasko086311b2016-01-08 09:53:11 +0100636 return 0;
637 } else {
638 /* the user did now know he does not need any password,
639 * (which should not be used) so deny authentication */
640 return 1;
641 }
642 }
643
roman814f5112023-10-19 15:51:16 +0200644 if (!strncmp(stored_pw, "$0$", 3)) {
645 /* cleartext password, simply compare the values */
646 return strcmp(stored_pw + 3, received_pw);
647 }
648
roman814f5112023-10-19 15:51:16 +0200649 received_pw_hash = crypt_r(received_pw, stored_pw, &cdata);
roman814f5112023-10-19 15:51:16 +0200650 if (!received_pw_hash) {
roman8b1a6c32023-10-26 13:35:22 +0200651 ERR(NULL, "Hashing the password failed (%s).", strerror(errno));
Andrew Langefeld158d6fd2018-06-11 18:51:44 -0500652 return 1;
653 }
654
roman814f5112023-10-19 15:51:16 +0200655 return strcmp(received_pw_hash, stored_pw);
Michal Vasko086311b2016-01-08 09:53:11 +0100656}
657
romane5675b12024-03-05 14:26:23 +0100658API int
659nc_server_ssh_kbdint_get_nanswers(const struct nc_session *session, ssh_session libssh_session)
romanc6518422023-11-30 16:39:00 +0100660{
661 int ret = 0;
662 struct timespec ts_timeout = {0};
roman56c85c02023-12-07 13:09:28 +0100663 ssh_message reply = NULL;
romane5675b12024-03-05 14:26:23 +0100664 uint16_t auth_timeout = *((uint16_t *)session->data);
665
666 NC_CHECK_ARG_RET(NULL, session, libssh_session, -1);
romanc6518422023-11-30 16:39:00 +0100667
668 if (auth_timeout) {
669 nc_timeouttime_get(&ts_timeout, auth_timeout * 1000);
670 }
671
672 /* wait for answers from the client */
673 do {
674 if (!nc_session_is_connected(session)) {
675 ERR(NULL, "SSH communication socket unexpectedly closed.");
676 ret = -1;
677 goto cleanup;
678 }
679
680 reply = ssh_message_get(libssh_session);
681 if (reply) {
682 break;
683 }
684
685 usleep(NC_TIMEOUT_STEP);
686 } while (auth_timeout && (nc_timeouttime_cur_diff(&ts_timeout) >= 1));
687 if (!reply) {
688 ERR(NULL, "Authentication timeout.");
689 ret = -1;
690 goto cleanup;
691 }
692
693 ret = ssh_userauth_kbdint_getnanswers(libssh_session);
694
695cleanup:
696 ssh_message_free(reply);
697 return ret;
698}
699
Michal Vasko0d81c572022-09-26 10:39:31 +0200700#ifdef HAVE_LIBPAM
701
roman41a11e42022-06-22 09:27:08 +0200702/**
703 * @brief PAM conversation function, which serves as a callback for exchanging messages between the client and a PAM module.
704 *
705 * @param[in] n_messages Number of messages.
706 * @param[in] msg PAM module's messages.
707 * @param[out] resp User responses.
708 * @param[in] appdata_ptr Callback's data.
roman808f3f62023-11-23 16:01:04 +0100709 * @return PAM_SUCCESS on success, PAM_BUF_ERR on memory allocation error, PAM_CONV_ERR otherwise.
roman41a11e42022-06-22 09:27:08 +0200710 */
711static int
712nc_pam_conv_clb(int n_messages, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr)
713{
714 int i, j, t, r = PAM_SUCCESS, n_answers, n_requests = n_messages;
715 const char **prompts = NULL;
716 char *echo = NULL;
717 const char *name = "Keyboard-Interactive Authentication";
718 const char *instruction = "Please enter your authentication token";
719 ssh_message reply = NULL;
720 struct nc_pam_thread_arg *clb_data = appdata_ptr;
721 ssh_session libssh_session;
roman41a11e42022-06-22 09:27:08 +0200722
723 libssh_session = clb_data->session->ti.libssh.session;
roman41a11e42022-06-22 09:27:08 +0200724
725 /* PAM_MAX_NUM_MSG == 32 by default */
726 if ((n_messages <= 0) || (n_messages >= PAM_MAX_NUM_MSG)) {
romanc6518422023-11-30 16:39:00 +0100727 ERR(clb_data->session, "Bad number of PAM messages (#%d).", n_messages);
roman41a11e42022-06-22 09:27:08 +0200728 r = PAM_CONV_ERR;
729 goto cleanup;
730 }
731
732 /* only accepting these 4 types of messages */
733 for (i = 0; i < n_messages; i++) {
734 t = msg[i]->msg_style;
735 if ((t != PAM_PROMPT_ECHO_OFF) && (t != PAM_PROMPT_ECHO_ON) && (t != PAM_TEXT_INFO) && (t != PAM_ERROR_MSG)) {
romanc6518422023-11-30 16:39:00 +0100736 ERR(clb_data->session, "PAM conversation callback received an unexpected type of message.");
roman41a11e42022-06-22 09:27:08 +0200737 r = PAM_CONV_ERR;
738 goto cleanup;
739 }
740 }
741
742 /* display messages with errors and/or some information and count the amount of actual authentication challenges */
743 for (i = 0; i < n_messages; i++) {
744 if (msg[i]->msg_style == PAM_TEXT_INFO) {
romanc6518422023-11-30 16:39:00 +0100745 VRB(clb_data->session, "PAM conversation callback received a message with some information for the client (%s).", msg[i]->msg);
roman41a11e42022-06-22 09:27:08 +0200746 n_requests--;
747 }
748 if (msg[i]->msg_style == PAM_ERROR_MSG) {
romanc6518422023-11-30 16:39:00 +0100749 ERR(clb_data->session, "PAM conversation callback received an error message (%s).", msg[i]->msg);
roman41a11e42022-06-22 09:27:08 +0200750 r = PAM_CONV_ERR;
751 goto cleanup;
752 }
753 }
754
755 /* there are no requests left for the user, only messages with some information for the client were sent */
756 if (n_requests <= 0) {
757 r = PAM_SUCCESS;
758 goto cleanup;
759 }
760
761 /* it is the PAM module's responsibility to release both, this array and the responses themselves */
762 *resp = calloc(n_requests, sizeof **resp);
763 prompts = calloc(n_requests, sizeof *prompts);
764 echo = calloc(n_requests, sizeof *echo);
roman3a95bb22023-10-26 11:07:17 +0200765 NC_CHECK_ERRMEM_GOTO(!(*resp) || !prompts || !echo, r = PAM_BUF_ERR, cleanup);
roman41a11e42022-06-22 09:27:08 +0200766
767 /* set the prompts for the user */
768 j = 0;
769 for (i = 0; i < n_messages; i++) {
770 if ((msg[i]->msg_style == PAM_PROMPT_ECHO_ON) || (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF)) {
771 prompts[j++] = msg[i]->msg;
772 }
773 }
774
775 /* iterate over all the messages and adjust the echo array accordingly */
776 j = 0;
777 for (i = 0; i < n_messages; i++) {
778 if (msg[i]->msg_style == PAM_PROMPT_ECHO_ON) {
779 echo[j++] = 1;
780 }
781 if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF) {
782 /* no need to set to 0 because of calloc */
783 j++;
784 }
785 }
786
787 /* print all the keyboard-interactive challenges to the user */
788 r = ssh_message_auth_interactive_request(clb_data->msg, name, instruction, n_requests, prompts, echo);
789 if (r != SSH_OK) {
romanc6518422023-11-30 16:39:00 +0100790 ERR(clb_data->session, "Failed to send an authentication request.");
roman41a11e42022-06-22 09:27:08 +0200791 r = PAM_CONV_ERR;
792 goto cleanup;
793 }
794
romane5675b12024-03-05 14:26:23 +0100795 n_answers = nc_server_ssh_kbdint_get_nanswers(clb_data->session, libssh_session);
romanc6518422023-11-30 16:39:00 +0100796 if (n_answers < 0) {
797 /* timeout or dc */
roman41a11e42022-06-22 09:27:08 +0200798 r = PAM_CONV_ERR;
799 goto cleanup;
romanc6518422023-11-30 16:39:00 +0100800 } else if (n_answers != n_requests) {
801 /* check if the number of answers and requests matches */
802 ERR(clb_data->session, "Expected %d response(s), got %d.", n_requests, n_answers);
roman41a11e42022-06-22 09:27:08 +0200803 r = PAM_CONV_ERR;
804 goto cleanup;
805 }
806
807 /* give the replies to a PAM module */
808 for (i = 0; i < n_answers; i++) {
809 (*resp)[i].resp = strdup(ssh_userauth_kbdint_getanswer(libssh_session, i));
810 /* it should be the caller's responsibility to free this, however if mem alloc fails,
811 * it is safer to free the responses here and set them to NULL */
812 if ((*resp)[i].resp == NULL) {
813 for (j = 0; j < i; j++) {
814 free((*resp)[j].resp);
815 (*resp)[j].resp = NULL;
816 }
817 ERRMEM;
818 r = PAM_BUF_ERR;
819 goto cleanup;
820 }
821 }
822
823cleanup:
824 ssh_message_free(reply);
825 free(prompts);
826 free(echo);
827 return r;
828}
829
830/**
831 * @brief Handles authentication via Linux PAM.
832 *
833 * @param[in] session NETCONF session.
romanbe162202024-05-22 14:19:23 +0200834 * @param[in] username Username of the client to auhtenticate.
roman41a11e42022-06-22 09:27:08 +0200835 * @param[in] ssh_msg SSH message with a keyboard-interactive authentication request.
836 * @return PAM_SUCCESS on success;
837 * @return PAM error otherwise.
838 */
839static int
romanbe162202024-05-22 14:19:23 +0200840nc_server_ssh_auth_kbdint_pam(struct nc_session *session, const char *username, ssh_message ssh_msg)
roman41a11e42022-06-22 09:27:08 +0200841{
842 pam_handle_t *pam_h = NULL;
843 int ret;
844 struct nc_pam_thread_arg clb_data;
845 struct pam_conv conv;
846
847 /* structure holding callback's data */
848 clb_data.msg = ssh_msg;
849 clb_data.session = session;
850
851 /* PAM conversation structure holding the callback and it's data */
852 conv.conv = nc_pam_conv_clb;
853 conv.appdata_ptr = &clb_data;
854
roman808f3f62023-11-23 16:01:04 +0100855 if (!server_opts.pam_config_name) {
romanc6518422023-11-30 16:39:00 +0100856 ERR(session, "PAM configuration filename not set.");
romanf578cd52023-10-19 09:47:40 +0200857 ret = 1;
858 goto cleanup;
859 }
860
roman41a11e42022-06-22 09:27:08 +0200861 /* initialize PAM and see if the given configuration file exists */
romanbe162202024-05-22 14:19:23 +0200862 ret = pam_start(server_opts.pam_config_name, username, &conv, &pam_h);
roman41a11e42022-06-22 09:27:08 +0200863 if (ret != PAM_SUCCESS) {
romanc6518422023-11-30 16:39:00 +0100864 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200865 goto cleanup;
866 }
867
868 /* authentication based on the modules listed in the configuration file */
869 ret = pam_authenticate(pam_h, 0);
870 if (ret != PAM_SUCCESS) {
871 if (ret == PAM_ABORT) {
romanc6518422023-11-30 16:39:00 +0100872 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200873 goto cleanup;
874 } else {
romanc6518422023-11-30 16:39:00 +0100875 VRB(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200876 goto cleanup;
877 }
878 }
879
880 /* correct token entered, check other requirements(the time of the day, expired token, ...) */
881 ret = pam_acct_mgmt(pam_h, 0);
882 if ((ret != PAM_SUCCESS) && (ret != PAM_NEW_AUTHTOK_REQD)) {
romanc6518422023-11-30 16:39:00 +0100883 VRB(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200884 goto cleanup;
885 }
886
887 /* if a token has expired a new one will be generated */
888 if (ret == PAM_NEW_AUTHTOK_REQD) {
romanc6518422023-11-30 16:39:00 +0100889 VRB(session, "PAM warning occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200890 ret = pam_chauthtok(pam_h, PAM_CHANGE_EXPIRED_AUTHTOK);
891 if (ret == PAM_SUCCESS) {
romanbe162202024-05-22 14:19:23 +0200892 VRB(session, "The authentication token of user \"%s\" updated successfully.", username);
roman41a11e42022-06-22 09:27:08 +0200893 } else {
romanc6518422023-11-30 16:39:00 +0100894 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200895 goto cleanup;
896 }
897 }
898
899cleanup:
900 /* destroy the PAM context */
roman6dfdc0d2023-11-09 13:25:27 +0100901 if (pam_h && (pam_end(pam_h, ret) != PAM_SUCCESS)) {
romancab602e2023-11-24 11:30:32 +0100902 ERR(NULL, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200903 }
904 return ret;
905}
906
romanc6518422023-11-30 16:39:00 +0100907#elif defined (HAVE_SHADOW)
908
romanc6518422023-11-30 16:39:00 +0100909/**
roman5858e6d2024-05-23 09:18:22 +0200910 * @brief Authenticate using credentials stored in the system.
romanc6518422023-11-30 16:39:00 +0100911 *
912 * @param[in] session Session to authenticate on.
romanbe162202024-05-22 14:19:23 +0200913 * @param[in] username Username of the client to authenticate.
romanc6518422023-11-30 16:39:00 +0100914 * @param[in] msg SSH message that originally requested kbdint authentication.
915 *
916 * @return 0 on success, non-zero otherwise.
917 */
918static int
romanbe162202024-05-22 14:19:23 +0200919nc_server_ssh_auth_kbdint_system(struct nc_session *session, const char *username, ssh_message msg)
romanc6518422023-11-30 16:39:00 +0100920{
921 int ret = 0, n_answers;
922 const char *name = "Keyboard-Interactive Authentication";
923 const char *instruction = "Please enter your authentication token";
roman5858e6d2024-05-23 09:18:22 +0200924 char *prompt = NULL, *pw = NULL, *received_pw = NULL;
romanc6518422023-11-30 16:39:00 +0100925 char echo[] = {0};
926
roman5858e6d2024-05-23 09:18:22 +0200927 /* try to get the client's pw hash from the system */
928 pw = nc_server_ssh_get_pwd_hash(username);
929 if (!pw) {
romanc6518422023-11-30 16:39:00 +0100930 ret = 1;
931 goto cleanup;
932 }
933
romanbe162202024-05-22 14:19:23 +0200934 ret = asprintf(&prompt, "%s's password:", username);
romanc6518422023-11-30 16:39:00 +0100935 NC_CHECK_ERRMEM_GOTO(ret == -1, prompt = NULL; ret = 1, cleanup);
936
937 /* send the password prompt to the client */
938 ret = ssh_message_auth_interactive_request(msg, name, instruction, 1, (const char **) &prompt, echo);
939 if (ret) {
romanbe162202024-05-22 14:19:23 +0200940 ERR(session, "Failed to send an authentication request to client \"%s\".", username);
romanc6518422023-11-30 16:39:00 +0100941 goto cleanup;
942 }
943
944 /* get the reply */
romane5675b12024-03-05 14:26:23 +0100945 n_answers = nc_server_ssh_kbdint_get_nanswers(session, session->ti.libssh.session);
romanc6518422023-11-30 16:39:00 +0100946 if (n_answers < 0) {
947 /* timeout or dc */
948 ret = 1;
949 goto cleanup;
950 } else if (n_answers != 1) {
951 /* only expecting a single answer */
952 ERR(session, "Unexpected amount of answers in system auth. Expected 1, got \"%d\".", n_answers);
953 ret = 1;
954 goto cleanup;
955 }
956 received_pw = strdup(ssh_userauth_kbdint_getanswer(session->ti.libssh.session, 0));
957 NC_CHECK_ERRMEM_GOTO(!received_pw, ret = 1, cleanup);
958
romanbe162202024-05-22 14:19:23 +0200959 /* cmp the passwords */
roman5858e6d2024-05-23 09:18:22 +0200960 ret = nc_server_ssh_compare_password(pw, received_pw);
romanc6518422023-11-30 16:39:00 +0100961
962cleanup:
roman5858e6d2024-05-23 09:18:22 +0200963 free(pw);
romanc6518422023-11-30 16:39:00 +0100964 free(received_pw);
965 free(prompt);
966 return ret;
967}
968
969#endif
Michal Vasko0d81c572022-09-26 10:39:31 +0200970
roman808f3f62023-11-23 16:01:04 +0100971API void
972nc_server_ssh_set_interactive_auth_clb(int (*interactive_auth_clb)(const struct nc_session *session, ssh_session ssh_sess, ssh_message msg, void *user_data),
973 void *user_data, void (*free_user_data)(void *user_data))
974{
romanc6518422023-11-30 16:39:00 +0100975 /* CONFIG LOCK */
976 pthread_rwlock_wrlock(&server_opts.config_lock);
977
roman808f3f62023-11-23 16:01:04 +0100978 server_opts.interactive_auth_clb = interactive_auth_clb;
979 server_opts.interactive_auth_data = user_data;
980 server_opts.interactive_auth_data_free = free_user_data;
romanc6518422023-11-30 16:39:00 +0100981
982 /* CONFIG UNLOCK */
983 pthread_rwlock_unlock(&server_opts.config_lock);
roman808f3f62023-11-23 16:01:04 +0100984}
985
986#ifdef HAVE_LIBPAM
987
988API int
989nc_server_ssh_set_pam_conf_filename(const char *filename)
990{
romanc6518422023-11-30 16:39:00 +0100991 int ret = 0;
992
roman808f3f62023-11-23 16:01:04 +0100993 NC_CHECK_ARG_RET(NULL, filename, 1);
994
romanc6518422023-11-30 16:39:00 +0100995 /* CONFIG LOCK */
996 pthread_rwlock_wrlock(&server_opts.config_lock);
997
roman808f3f62023-11-23 16:01:04 +0100998 free(server_opts.pam_config_name);
999 server_opts.pam_config_name = strdup(filename);
romanc6518422023-11-30 16:39:00 +01001000 if (!server_opts.pam_config_name) {
1001 ERRMEM;
1002 ret = 1;
1003 }
1004
1005 /* CONFIG UNLOCK */
1006 pthread_rwlock_unlock(&server_opts.config_lock);
1007 return ret;
roman808f3f62023-11-23 16:01:04 +01001008}
1009
1010#else
1011
1012API int
1013nc_server_ssh_set_pam_conf_filename(const char *filename)
1014{
romanf69fbcf2023-12-14 09:24:34 +01001015 /* LibPAM not supported */
roman808f3f62023-11-23 16:01:04 +01001016 (void) filename;
roman808f3f62023-11-23 16:01:04 +01001017 return 1;
1018}
1019
1020#endif /* HAVE_LIBPAM */
1021
romana9ec3362023-12-21 10:59:57 +01001022API int
1023nc_server_ssh_set_authkey_path_format(const char *path)
1024{
1025 int ret = 0;
1026
1027 NC_CHECK_ARG_RET(NULL, path, 1);
1028
1029 /* CONFIG LOCK */
1030 pthread_rwlock_wrlock(&server_opts.config_lock);
1031
1032 free(server_opts.authkey_path_fmt);
1033 server_opts.authkey_path_fmt = strdup(path);
1034 if (!server_opts.authkey_path_fmt) {
1035 ERRMEM;
1036 ret = 1;
1037 }
1038
1039 /* CONFIG UNLOCK */
1040 pthread_rwlock_unlock(&server_opts.config_lock);
1041 return ret;
1042}
1043
roman1ea193e2024-05-22 14:16:41 +02001044/**
1045 * @brief Get the public key type from binary data.
romanbe162202024-05-22 14:19:23 +02001046 *
roman1ea193e2024-05-22 14:16:41 +02001047 * @param[in] buffer Binary key data, which is in the form of: 4 bytes = data length, then data of data length.
1048 * Data is in network byte order. The key has to be in the SSH2 format.
1049 * @param[out] len Length of the key type.
1050 * @return Pointer to where the key type starts in the buffer and is of the length @p len .
romanf578cd52023-10-19 09:47:40 +02001051 */
1052static const char *
romance435112024-04-23 15:12:09 +02001053nc_server_ssh_get_pubkey_type(const unsigned char *buffer, uint32_t *len)
romanf578cd52023-10-19 09:47:40 +02001054{
1055 uint32_t type_len;
1056
1057 /* copy the 4 bytes */
1058 memcpy(&type_len, buffer, sizeof type_len);
1059 /* type_len now stores the length of the key type */
1060 type_len = ntohl(type_len);
1061 *len = type_len;
1062
1063 /* move 4 bytes in the buffer, this is where the type should be */
1064 buffer += sizeof type_len;
romance435112024-04-23 15:12:09 +02001065 return (const char *)buffer;
romanf578cd52023-10-19 09:47:40 +02001066}
1067
1068/**
1069 * @brief Create ssh key from base64 pubkey data.
1070 *
1071 * @param[in] base64 base64 encoded public key.
1072 * @param[out] key created ssh key.
1073 * @return 0 on success, 1 otherwise.
1074 */
1075static int
1076nc_server_ssh_create_ssh_pubkey(const char *base64, ssh_key *key)
1077{
1078 int ret = 0;
romance435112024-04-23 15:12:09 +02001079 unsigned char *bin = NULL;
romanf578cd52023-10-19 09:47:40 +02001080 const char *pub_type = NULL;
1081 uint32_t pub_type_len = 0;
1082
roman6dfdc0d2023-11-09 13:25:27 +01001083 NC_CHECK_ARG_RET(NULL, base64, key, 1);
romanf578cd52023-10-19 09:47:40 +02001084
1085 *key = NULL;
1086
1087 /* convert base64 to binary */
roman83289292024-04-05 12:33:24 +02001088 if (nc_base64_decode_wrap(base64, &bin) == -1) {
romanf578cd52023-10-19 09:47:40 +02001089 ret = 1;
1090 goto cleanup;
1091 }
1092
1093 /* get the key type and try to import it if possible */
1094 pub_type = nc_server_ssh_get_pubkey_type(bin, &pub_type_len);
1095 if (!pub_type) {
1096 ret = 1;
1097 goto cleanup;
1098 } else if (!strncmp(pub_type, "ssh-dss", pub_type_len)) {
1099 ERR(NULL, "DSA keys are not supported.");
1100 ret = 1;
1101 goto cleanup;
1102 } else if (!strncmp(pub_type, "ssh-rsa", pub_type_len)) {
1103 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_RSA, key);
1104 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp256", pub_type_len)) {
1105 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P256, key);
1106 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp384", pub_type_len)) {
1107 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P384, key);
1108 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp521", pub_type_len)) {
1109 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P521, key);
1110 } else if (!strncmp(pub_type, "ssh-ed25519", pub_type_len)) {
1111 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ED25519, key);
1112 } else {
1113 ERR(NULL, "Public key type not recognised.");
1114 ret = 1;
1115 goto cleanup;
1116 }
1117
1118cleanup:
1119 if (ret != SSH_OK) {
1120 ERR(NULL, "Error importing public key.");
1121 }
1122 free(bin);
1123 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +01001124}
1125
Michal Vaskof3c41e32022-09-09 11:22:21 +02001126/**
1127 * @brief Compare SSH key with configured authorized keys and return the username of the matching one, if any.
1128 *
1129 * @param[in] key Presented SSH key to compare.
1130 * @return Authorized key username, NULL if no match was found.
1131 */
romanf578cd52023-10-19 09:47:40 +02001132static int
romanbe162202024-05-22 14:19:23 +02001133nc_server_ssh_auth_pubkey_compare_key(ssh_key key, struct nc_public_key *pubkeys, uint16_t pubkey_count)
Michal Vasko086311b2016-01-08 09:53:11 +01001134{
romanbe162202024-05-22 14:19:23 +02001135 uint16_t i;
Michal Vasko3e9d1682017-02-24 09:50:15 +01001136 int ret = 0;
romanf578cd52023-10-19 09:47:40 +02001137 ssh_key new_key = NULL;
Michal Vasko086311b2016-01-08 09:53:11 +01001138
romanbe162202024-05-22 14:19:23 +02001139 /* try to compare all of the client's keys with the key received in the SSH message */
1140 for (i = 0; i < pubkey_count; i++) {
1141 /* create the SSH key from the data */
1142 if (nc_server_ssh_create_ssh_pubkey(pubkeys[i].data, &new_key)) {
1143 /* skip */
1144 ssh_key_free(new_key);
1145 continue;
1146 }
1147
1148 /* compare the keys */
1149 ret = ssh_key_cmp(key, new_key, SSH_KEY_CMP_PUBLIC);
1150 ssh_key_free(new_key);
1151 if (!ret) {
1152 /* found a match */
1153 break;
1154 }
1155 }
1156 if (i == pubkey_count) {
1157 ret = 1;
1158 }
1159
1160 return ret;
1161}
1162
1163/**
1164 * @brief Handle authentication request for the None method.
1165 *
1166 * @param[in] local_users_supported Whether the server supports local users.
1167 * @param[in] auth_client Configured client's authentication data.
1168 * @param[in] msg libssh message.
1169 * @return 0 if the authentication was successful, -1 if not (@p msg already replied to).
1170 */
1171static int
1172nc_server_ssh_auth_none(int local_users_supported, struct nc_auth_client *auth_client, ssh_message msg)
1173{
1174 assert(!local_users_supported || auth_client);
1175
1176 if (local_users_supported && auth_client->none_enabled) {
1177 /* success */
1178 return 0;
1179 }
1180
roman5858e6d2024-05-23 09:18:22 +02001181 /* reply and return -1 so that this does not get counted as an unsuccessful authentication attempt */
romanbe162202024-05-22 14:19:23 +02001182 ssh_message_reply_default(msg);
1183 return -1;
1184}
1185
1186/**
1187 * @brief Handle authentication request for the Password method.
1188 *
1189 * @param[in] session NETCONF session.
1190 * @param[in] local_users_supported Whether the server supports local users.
1191 * @param[in] auth_client Configured client's authentication data.
1192 * @param[in] msg libssh message.
1193 * @return 0 if the authentication was successful, 1 if not (@p msg not yet replied to).
1194 */
1195static int
1196nc_server_ssh_auth_password(struct nc_session *session, int local_users_supported,
1197 struct nc_auth_client *auth_client, ssh_message msg)
1198{
1199 int rc;
1200 char *password = NULL;
1201
1202 assert(!local_users_supported || auth_client);
1203
1204 if (local_users_supported) {
1205 /* obtain pw from config */
1206 password = auth_client->password;
1207 if (!password) {
1208 VRB(session, "User \"%s\" does not have password method configured, but a request was received.", session->username);
1209 return 1;
1210 }
1211 } else {
1212#ifdef HAVE_SHADOW
1213 /* obtain pw from system, this one needs to be free'd */
1214 password = nc_server_ssh_get_pwd_hash(session->username);
1215 if (!password) {
1216 return 1;
1217 }
1218#else
1219 ERR(session, "Obtaining password from system not supported.");
1220 return 1;
1221#endif
1222 }
1223
1224 /* compare the passwords */
1225 rc = nc_server_ssh_compare_password(password, ssh_message_auth_password(msg));
1226
1227 if (!local_users_supported) {
1228 free(password);
1229 }
1230
1231 return rc ? 1 : 0;
1232}
1233
1234/**
1235 * @brief Handle authentication request for the Publickey method.
1236 *
1237 * @param[in] session NETCONF session.
1238 * @param[in] local_users_supported Whether the server supports local users.
1239 * @param[in] auth_client Configured client's authentication data.
1240 * @param[in] msg libssh message.
1241 * @return 0 if the authentication was successful, 1 if not and the @p msg not yet replied to, -1 if not and @p msg was replied to.
1242 */
1243static int
1244nc_server_ssh_auth_pubkey(struct nc_session *session, int local_users_supported,
1245 struct nc_auth_client *auth_client, ssh_message msg)
1246{
1247 int signature_state, ret = 0;
1248 struct nc_public_key *pubkeys = NULL;
1249 uint16_t pubkey_count = 0, i;
1250
1251 assert(!local_users_supported || auth_client);
1252
1253 /* get the public keys */
1254 if (!local_users_supported || (auth_client->store == NC_STORE_SYSTEM)) {
1255 /* system user or the user has 'use system keys' configured, these need to be free'd */
1256 ret = nc_server_ssh_get_system_keys(session->username, &pubkeys, &pubkey_count);
1257 if (ret) {
1258 goto cleanup;
1259 }
1260 } else if (auth_client->store == NC_STORE_LOCAL) {
romanf578cd52023-10-19 09:47:40 +02001261 pubkeys = auth_client->pubkeys;
1262 pubkey_count = auth_client->pubkey_count;
romana9ec3362023-12-21 10:59:57 +01001263 } else if (auth_client->store == NC_STORE_TRUSTSTORE) {
romanf578cd52023-10-19 09:47:40 +02001264 ret = nc_server_ssh_ts_ref_get_keys(auth_client->ts_ref, &pubkeys, &pubkey_count);
1265 if (ret) {
romana9ec3362023-12-21 10:59:57 +01001266 goto cleanup;
1267 }
1268 } else {
1269 ERRINT;
1270 return 1;
romanf578cd52023-10-19 09:47:40 +02001271 }
Michal Vasko17dfda92016-12-01 14:06:16 +01001272
romanbe162202024-05-22 14:19:23 +02001273 /* compare the received pubkey with the authorized ones */
1274 if (nc_server_ssh_auth_pubkey_compare_key(ssh_message_auth_pubkey(msg), pubkeys, pubkey_count)) {
roman9130fc12023-11-03 13:56:23 +01001275 VRB(session, "User \"%s\" tried to use an unknown (unauthorized) public key.", session->username);
1276 ret = 1;
romanbe162202024-05-22 14:19:23 +02001277 goto cleanup;
Michal Vaskobd13a932016-09-14 09:00:35 +02001278 }
Michal Vaskobd13a932016-09-14 09:00:35 +02001279
Michal Vasko086311b2016-01-08 09:53:11 +01001280 signature_state = ssh_message_auth_publickey_state(msg);
romanf578cd52023-10-19 09:47:40 +02001281 if (signature_state == SSH_PUBLICKEY_STATE_NONE) {
Michal Vaskobd13a932016-09-14 09:00:35 +02001282 /* accepting only the use of a public key */
1283 ssh_message_auth_reply_pk_ok_simple(msg);
romanbe162202024-05-22 14:19:23 +02001284 ret = -1;
Michal Vasko086311b2016-01-08 09:53:11 +01001285 }
1286
romanbe162202024-05-22 14:19:23 +02001287cleanup:
1288 if (!local_users_supported || (auth_client->store == NC_STORE_SYSTEM)) {
1289 for (i = 0; i < pubkey_count; i++) {
1290 free(pubkeys[i].name);
1291 free(pubkeys[i].data);
1292 }
1293 free(pubkeys);
1294 }
romanf578cd52023-10-19 09:47:40 +02001295
1296 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +01001297}
1298
roman70639ca2024-05-23 15:27:52 +02001299/**
1300 * @brief Handle authentication request for the Keyboard-interactive method.
1301 *
1302 * @param[in] session NETCONF session.
1303 * @param[in] local_users_supported Whether the server supports local users.
1304 * @param[in] auth_client Configured client's authentication data.
1305 * @param[in] msg libssh message.
1306 * @return 0 if the authentication was successful, 1 if not.
1307 */
Michal Vasko086311b2016-01-08 09:53:11 +01001308static int
romanbe162202024-05-22 14:19:23 +02001309nc_server_ssh_auth_kbdint(struct nc_session *session, int local_users_supported, struct nc_auth_client *auth_client, ssh_message msg)
1310{
roman70639ca2024-05-23 15:27:52 +02001311 int rc = 0;
romanbe162202024-05-22 14:19:23 +02001312
1313 assert(!local_users_supported || auth_client);
1314
1315 if (local_users_supported && !auth_client->kb_int_enabled) {
1316 VRB(session, "User \"%s\" does not have Keyboard-interactive method configured, but a request was received.", session->username);
roman70639ca2024-05-23 15:27:52 +02001317 return 1;
romanbe162202024-05-22 14:19:23 +02001318 } else if (server_opts.interactive_auth_clb) {
1319 rc = server_opts.interactive_auth_clb(session, session->ti.libssh.session, msg, server_opts.interactive_auth_data);
1320 } else {
1321#ifdef HAVE_LIBPAM
1322 /* authenticate using PAM */
1323 rc = nc_server_ssh_auth_kbdint_pam(session, session->username, msg);
1324#elif defined (HAVE_SHADOW)
roman5858e6d2024-05-23 09:18:22 +02001325 /* authenticate using the system */
romanbe162202024-05-22 14:19:23 +02001326 rc = nc_server_ssh_auth_kbdint_system(session, session->username, msg);
1327#else
1328 ERR(NULL, "Keyboard-interactive method not supported.");
roman70639ca2024-05-23 15:27:52 +02001329 return 1;
romanbe162202024-05-22 14:19:23 +02001330#endif
1331 }
1332
1333 return rc ? 1 : 0;
1334}
1335
1336/**
1337 * @brief Handle SSH channel open request.
1338 *
1339 * @param[in] session NETCONF session.
1340 * @param[in] msg libssh message.
1341 * @return 0 on success, -1 on failure.
1342 */
1343static int
1344nc_server_ssh_channel_open(struct nc_session *session, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +01001345{
Michal Vasko96164bf2016-01-21 15:41:58 +01001346 ssh_channel chan;
1347
1348 /* first channel request */
1349 if (!session->ti.libssh.channel) {
1350 if (session->status != NC_STATUS_STARTING) {
Michal Vasko9e036d52016-01-08 10:49:26 +01001351 ERRINT;
Michal Vasko086311b2016-01-08 09:53:11 +01001352 return -1;
1353 }
Michal Vasko96164bf2016-01-21 15:41:58 +01001354 chan = ssh_message_channel_request_open_reply_accept(msg);
1355 if (!chan) {
Michal Vasko05532772021-06-03 12:12:38 +02001356 ERR(session, "Failed to create a new SSH channel.");
Michal Vasko96164bf2016-01-21 15:41:58 +01001357 return -1;
1358 }
1359 session->ti.libssh.channel = chan;
Michal Vasko086311b2016-01-08 09:53:11 +01001360
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001361 /* additional channel request */
Michal Vasko96164bf2016-01-21 15:41:58 +01001362 } else {
1363 chan = ssh_message_channel_request_open_reply_accept(msg);
1364 if (!chan) {
Michal Vasko05532772021-06-03 12:12:38 +02001365 ERR(session, "Session %u: failed to create a new SSH channel.", session->id);
Michal Vasko96164bf2016-01-21 15:41:58 +01001366 return -1;
1367 }
1368 /* channel was created and libssh stored it internally in the ssh_session structure, good enough */
Michal Vasko086311b2016-01-08 09:53:11 +01001369 }
1370
Michal Vasko086311b2016-01-08 09:53:11 +01001371 return 0;
1372}
1373
romanbe162202024-05-22 14:19:23 +02001374/**
1375 * @brief Handle SSH channel request subsystem request.
1376 *
1377 * @param[in] session NETCONF session.
1378 * @param[in] channel Requested SSH channel.
1379 * @param[in] subsystem Name of the requested subsystem.
1380 * @return 0 on success, -1 on failure.
1381 */
Michal Vasko086311b2016-01-08 09:53:11 +01001382static int
romanbe162202024-05-22 14:19:23 +02001383nc_server_ssh_channel_subsystem(struct nc_session *session, ssh_channel channel, const char *subsystem)
Michal Vasko086311b2016-01-08 09:53:11 +01001384{
Michal Vasko96164bf2016-01-21 15:41:58 +01001385 struct nc_session *new_session;
Michal Vasko086311b2016-01-08 09:53:11 +01001386
Michal Vasko96164bf2016-01-21 15:41:58 +01001387 if (strcmp(subsystem, "netconf")) {
Michal Vasko05532772021-06-03 12:12:38 +02001388 WRN(session, "Received an unknown subsystem \"%s\" request.", subsystem);
Michal Vasko086311b2016-01-08 09:53:11 +01001389 return -1;
1390 }
1391
Michal Vasko96164bf2016-01-21 15:41:58 +01001392 if (session->ti.libssh.channel == channel) {
1393 /* first channel requested */
1394 if (session->ti.libssh.next || (session->status != NC_STATUS_STARTING)) {
1395 ERRINT;
1396 return -1;
Michal Vasko086311b2016-01-08 09:53:11 +01001397 }
Michal Vasko96164bf2016-01-21 15:41:58 +01001398 if (session->flags & NC_SESSION_SSH_SUBSYS_NETCONF) {
Michal Vasko05532772021-06-03 12:12:38 +02001399 ERR(session, "Subsystem \"netconf\" requested for the second time.");
Michal Vasko96164bf2016-01-21 15:41:58 +01001400 return -1;
1401 }
1402
1403 session->flags |= NC_SESSION_SSH_SUBSYS_NETCONF;
Michal Vasko086311b2016-01-08 09:53:11 +01001404 } else {
Michal Vasko96164bf2016-01-21 15:41:58 +01001405 /* additional channel subsystem request, new session is ready as far as SSH is concerned */
Michal Vasko131120a2018-05-29 15:44:02 +02001406 new_session = nc_new_session(NC_SERVER, 1);
roman3a95bb22023-10-26 11:07:17 +02001407 NC_CHECK_ERRMEM_RET(!new_session, -1);
Michal Vasko96164bf2016-01-21 15:41:58 +01001408
1409 /* insert the new session */
1410 if (!session->ti.libssh.next) {
1411 new_session->ti.libssh.next = session;
1412 } else {
1413 new_session->ti.libssh.next = session->ti.libssh.next;
1414 }
1415 session->ti.libssh.next = new_session;
1416
1417 new_session->status = NC_STATUS_STARTING;
roman506354a2024-04-11 09:37:22 +02001418 new_session->ti_type = NC_TI_SSH;
Michal Vasko131120a2018-05-29 15:44:02 +02001419 new_session->io_lock = session->io_lock;
Michal Vasko96164bf2016-01-21 15:41:58 +01001420 new_session->ti.libssh.channel = channel;
1421 new_session->ti.libssh.session = session->ti.libssh.session;
Michal Vasko93224072021-11-09 12:14:28 +01001422 new_session->username = strdup(session->username);
1423 new_session->host = strdup(session->host);
Michal Vasko96164bf2016-01-21 15:41:58 +01001424 new_session->port = session->port;
Michal Vasko93224072021-11-09 12:14:28 +01001425 new_session->ctx = (struct ly_ctx *)session->ctx;
Michal Vasko83d15322018-09-27 09:44:02 +02001426 new_session->flags = NC_SESSION_SSH_AUTHENTICATED | NC_SESSION_SSH_SUBSYS_NETCONF | NC_SESSION_SHAREDCTX;
Michal Vasko086311b2016-01-08 09:53:11 +01001427 }
1428
1429 return 0;
1430}
1431
romanbe162202024-05-22 14:19:23 +02001432/**
1433 * @brief Handle NETCONF SSH authentication.
1434 *
1435 * @param[in] session NETCONF session.
1436 * @param[in] opts SSH server options.
1437 * @param[in] msg libssh message.
1438 * @param[in] method Type of the authentication method.
1439 * @param[in] str_method String representation of the authentication method.
1440 * @param[in] local_users_supported Whether the server supports local users.
1441 * @param[in,out] state Authentication state.
1442 * @return 1 in case of a fatal error, 0 otherwise.
1443 */
1444static int
1445nc_server_ssh_auth(struct nc_session *session, struct nc_server_ssh_opts *opts, ssh_message msg,
1446 int method, const char *str_method, int local_users_supported, struct nc_auth_state *state)
Michal Vasko086311b2016-01-08 09:53:11 +01001447{
romanbe162202024-05-22 14:19:23 +02001448 const char *username;
1449 int libssh_auth_methods = 0, ret = 0;
romanf578cd52023-10-19 09:47:40 +02001450 uint16_t i;
1451 struct nc_auth_client *auth_client = NULL;
roman78df0fa2023-11-02 10:33:57 +01001452 struct nc_endpt *referenced_endpt;
Michal Vasko086311b2016-01-08 09:53:11 +01001453
romanbe162202024-05-22 14:19:23 +02001454 /* save the username, do not let the client change it */
1455 username = ssh_message_auth_user(msg);
1456 assert(username);
1457
1458 if (local_users_supported) {
1459 /* get the locally configured user */
1460 for (i = 0; i < opts->client_count; i++) {
1461 if (!strcmp(opts->auth_clients[i].username, username)) {
1462 auth_client = &opts->auth_clients[i];
1463 break;
1464 }
1465 }
1466
1467 if (!auth_client) {
1468 if (opts->referenced_endpt_name) {
1469 /* client not known by the endpt, but it references another one so try it */
1470 if (nc_server_get_referenced_endpt(opts->referenced_endpt_name, &referenced_endpt)) {
1471 ERRINT;
1472 return 1;
1473 }
1474
1475 return nc_server_ssh_auth(session, referenced_endpt->opts.ssh, msg, method,
1476 str_method, local_users_supported, state);
1477 }
1478
1479 /* user not known, set his authentication methods to public key only so that
1480 * there is no interaction and it will simply be denied */
1481 ERR(NULL, "User \"%s\" not known by the server.", username);
1482 ssh_set_auth_methods(session->ti.libssh.session, SSH_AUTH_METHOD_PUBLICKEY);
1483 ssh_message_reply_default(msg);
1484 return 0;
1485 }
1486 }
1487
1488 if (!session->username) {
1489 session->username = strdup(username);
1490 NC_CHECK_ERRMEM_RET(!session->username, 1);
1491
1492 /* configure and count accepted auth methods */
1493 if (local_users_supported) {
1494 if (((auth_client->store == NC_STORE_LOCAL) && (auth_client->pubkey_count)) ||
1495 (auth_client->store == NC_STORE_TRUSTSTORE) || (auth_client->store == NC_STORE_SYSTEM)) {
1496 /* either locally configured pubkeys, or truststore or system (need to check for
1497 * pubkey count, because NC_STORE_LOCAL is the default enum value) */
1498 state->auth_method_count++;
1499 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1500 }
1501 if (auth_client->password) {
1502 state->auth_method_count++;
1503 libssh_auth_methods |= SSH_AUTH_METHOD_PASSWORD;
1504 }
1505 if (auth_client->kb_int_enabled) {
1506 state->auth_method_count++;
1507 libssh_auth_methods |= SSH_AUTH_METHOD_INTERACTIVE;
1508 }
1509 if (auth_client->none_enabled) {
1510 state->auth_method_count++;
1511 libssh_auth_methods |= SSH_AUTH_METHOD_NONE;
1512 }
1513 } else {
1514 /* no local users meaning pw, pubkey and kbdint methods are supported, method count is set to 1,
1515 * because only one method is needed for successul auth */
1516 state->auth_method_count = 1;
1517 libssh_auth_methods = SSH_AUTH_METHOD_PUBLICKEY | SSH_AUTH_METHOD_PASSWORD | SSH_AUTH_METHOD_INTERACTIVE;
1518 }
1519
1520 ssh_set_auth_methods(session->ti.libssh.session, libssh_auth_methods);
1521 } else {
1522 if (strcmp(username, session->username)) {
1523 /* changing username not allowed */
1524 ERR(session, "User \"%s\" changed its username to \"%s\".", session->username, username);
1525 session->status = NC_STATUS_INVALID;
1526 session->term_reason = NC_SESSION_TERM_OTHER;
1527 return 1;
1528 }
1529 }
1530
1531 /* try authenticating, if local users are supported, then the configured user must authenticate via all of his
1532 * configured auth methods, otherwise for system users just one is needed,
1533 * 0 return indicates success, 1 fail (msg not yet replied to), -1 fail (msg was replied to) */
1534 if (method == SSH_AUTH_METHOD_NONE) {
1535 ret = nc_server_ssh_auth_none(local_users_supported, auth_client, msg);
1536 } else if (method == SSH_AUTH_METHOD_PASSWORD) {
1537 ret = nc_server_ssh_auth_password(session, local_users_supported, auth_client, msg);
1538 } else if (method == SSH_AUTH_METHOD_PUBLICKEY) {
1539 ret = nc_server_ssh_auth_pubkey(session, local_users_supported, auth_client, msg);
1540 } else if (method == SSH_AUTH_METHOD_INTERACTIVE) {
1541 ret = nc_server_ssh_auth_kbdint(session, local_users_supported, auth_client, msg);
1542 } else {
1543 ++session->opts.server.ssh_auth_attempts;
1544 VRB(session, "Authentication method \"%s\" not supported.", str_method);
1545 ssh_message_reply_default(msg);
1546 return 0;
1547 }
1548
1549 if (!ret) {
1550 state->auth_success_count++;
1551
1552 if (state->auth_success_count < state->auth_method_count) {
1553 /* success, but he needs to do another method */
1554 VRB(session, "User \"%s\" partially authenticated, but still needs to authenticate via the rest of his configured methods.", username);
1555 ssh_message_auth_reply_success(msg, 1);
1556 } else {
1557 /* authenticated */
1558 ssh_message_auth_reply_success(msg, 0);
1559 session->flags |= NC_SESSION_SSH_AUTHENTICATED;
1560 VRB(session, "User \"%s\" authenticated.", username);
1561 }
1562 } else if (ret == 1) {
1563 /* failed attempt, msg wasnt yet replied to */
1564 ++session->opts.server.ssh_auth_attempts;
1565 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", session->username,
1566 session->opts.server.ssh_auth_attempts);
1567 ssh_message_reply_default(msg);
1568 }
1569
1570 return 0;
1571}
1572
1573int
1574nc_session_ssh_msg(struct nc_session *session, struct nc_server_ssh_opts *opts, ssh_message msg, struct nc_auth_state *state)
1575{
1576 const char *str_type, *str_subtype = NULL;
1577 int subtype, type, rc, local_users_supported;
1578 const struct ly_ctx *ctx;
1579 struct lys_module *mod;
1580
Michal Vasko086311b2016-01-08 09:53:11 +01001581 type = ssh_message_type(msg);
1582 subtype = ssh_message_subtype(msg);
1583
1584 switch (type) {
1585 case SSH_REQUEST_AUTH:
1586 str_type = "request-auth";
1587 switch (subtype) {
1588 case SSH_AUTH_METHOD_NONE:
1589 str_subtype = "none";
1590 break;
1591 case SSH_AUTH_METHOD_PASSWORD:
1592 str_subtype = "password";
1593 break;
1594 case SSH_AUTH_METHOD_PUBLICKEY:
1595 str_subtype = "publickey";
1596 break;
1597 case SSH_AUTH_METHOD_HOSTBASED:
1598 str_subtype = "hostbased";
1599 break;
1600 case SSH_AUTH_METHOD_INTERACTIVE:
1601 str_subtype = "interactive";
1602 break;
1603 case SSH_AUTH_METHOD_GSSAPI_MIC:
1604 str_subtype = "gssapi-mic";
1605 break;
1606 }
1607 break;
1608
1609 case SSH_REQUEST_CHANNEL_OPEN:
1610 str_type = "request-channel-open";
1611 switch (subtype) {
1612 case SSH_CHANNEL_SESSION:
1613 str_subtype = "session";
1614 break;
1615 case SSH_CHANNEL_DIRECT_TCPIP:
1616 str_subtype = "direct-tcpip";
1617 break;
1618 case SSH_CHANNEL_FORWARDED_TCPIP:
1619 str_subtype = "forwarded-tcpip";
1620 break;
1621 case (int)SSH_CHANNEL_X11:
1622 str_subtype = "channel-x11";
1623 break;
1624 case SSH_CHANNEL_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001625 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001626 default:
1627 str_subtype = "unknown";
1628 break;
1629 }
1630 break;
1631
1632 case SSH_REQUEST_CHANNEL:
1633 str_type = "request-channel";
1634 switch (subtype) {
1635 case SSH_CHANNEL_REQUEST_PTY:
1636 str_subtype = "pty";
1637 break;
1638 case SSH_CHANNEL_REQUEST_EXEC:
1639 str_subtype = "exec";
1640 break;
1641 case SSH_CHANNEL_REQUEST_SHELL:
1642 str_subtype = "shell";
1643 break;
1644 case SSH_CHANNEL_REQUEST_ENV:
1645 str_subtype = "env";
1646 break;
1647 case SSH_CHANNEL_REQUEST_SUBSYSTEM:
1648 str_subtype = "subsystem";
1649 break;
1650 case SSH_CHANNEL_REQUEST_WINDOW_CHANGE:
1651 str_subtype = "window-change";
1652 break;
1653 case SSH_CHANNEL_REQUEST_X11:
1654 str_subtype = "x11";
1655 break;
1656 case SSH_CHANNEL_REQUEST_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001657 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001658 default:
1659 str_subtype = "unknown";
1660 break;
1661 }
1662 break;
1663
1664 case SSH_REQUEST_SERVICE:
1665 str_type = "request-service";
1666 str_subtype = ssh_message_service_service(msg);
1667 break;
1668
1669 case SSH_REQUEST_GLOBAL:
1670 str_type = "request-global";
1671 switch (subtype) {
1672 case SSH_GLOBAL_REQUEST_TCPIP_FORWARD:
1673 str_subtype = "tcpip-forward";
1674 break;
1675 case SSH_GLOBAL_REQUEST_CANCEL_TCPIP_FORWARD:
1676 str_subtype = "cancel-tcpip-forward";
1677 break;
1678 case SSH_GLOBAL_REQUEST_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001679 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001680 default:
1681 str_subtype = "unknown";
1682 break;
1683 }
1684 break;
1685
1686 default:
1687 str_type = "unknown";
1688 str_subtype = "unknown";
1689 break;
1690 }
1691
Michal Vasko05532772021-06-03 12:12:38 +02001692 VRB(session, "Received an SSH message \"%s\" of subtype \"%s\".", str_type, str_subtype);
Michal Vasko5e0edd82020-07-29 15:26:13 +02001693 if (!session || (session->status == NC_STATUS_CLOSING) || (session->status == NC_STATUS_INVALID)) {
Michal Vaskoce319162016-02-03 15:33:08 +01001694 /* "valid" situation if, for example, receiving some auth or channel request timeouted,
1695 * but we got it now, during session free */
Michal Vasko05532772021-06-03 12:12:38 +02001696 VRB(session, "SSH message arrived on a %s session, the request will be denied.",
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001697 (session && session->status == NC_STATUS_CLOSING ? "closing" : "invalid"));
Michal Vaskoce319162016-02-03 15:33:08 +01001698 ssh_message_reply_default(msg);
1699 return 0;
1700 }
Michal Vasko086311b2016-01-08 09:53:11 +01001701
1702 /*
1703 * process known messages
1704 */
1705 if (type == SSH_REQUEST_AUTH) {
1706 if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
Michal Vasko05532772021-06-03 12:12:38 +02001707 ERR(session, "User \"%s\" authenticated, but requested another authentication.", session->username);
Michal Vasko086311b2016-01-08 09:53:11 +01001708 ssh_message_reply_default(msg);
1709 return 0;
romanf578cd52023-10-19 09:47:40 +02001710 } else if (!state || !opts) {
1711 /* these two parameters should always be set during an authentication,
1712 * however do a check just in case something goes really wrong, since they
1713 * are not needed for other types of messages
1714 */
1715 ERRINT;
1716 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001717 }
1718
romanbe162202024-05-22 14:19:23 +02001719 /* get libyang ctx from session and ietf-ssh-server yang model from the ctx */
1720 ctx = nc_session_get_ctx(session);
1721 mod = ly_ctx_get_module_latest(ctx, "ietf-ssh-server");
1722 if (!mod) {
1723 ERRINT;
1724 return 1;
romanf578cd52023-10-19 09:47:40 +02001725 }
1726
romanbe162202024-05-22 14:19:23 +02001727 /* check if local-users-supported feature is enabled */
1728 rc = lys_feature_value(mod, "local-users-supported");
1729 if (!rc) {
roman5858e6d2024-05-23 09:18:22 +02001730 /* using users from the YANG data */
romanbe162202024-05-22 14:19:23 +02001731 local_users_supported = 1;
1732 } else if (rc == LY_ENOT) {
roman5858e6d2024-05-23 09:18:22 +02001733 /* using users from the system */
romanbe162202024-05-22 14:19:23 +02001734 local_users_supported = 0;
romanf578cd52023-10-19 09:47:40 +02001735 } else {
romanbe162202024-05-22 14:19:23 +02001736 ERRINT;
1737 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001738 }
1739
romanbe162202024-05-22 14:19:23 +02001740 /* authenticate */
1741 return nc_server_ssh_auth(session, opts, msg, subtype, str_subtype, local_users_supported, state);
Michal Vasko086311b2016-01-08 09:53:11 +01001742 } else if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
Michal Vasko0df67562016-01-21 15:50:11 +01001743 if ((type == SSH_REQUEST_CHANNEL_OPEN) && ((enum ssh_channel_type_e)subtype == SSH_CHANNEL_SESSION)) {
romanbe162202024-05-22 14:19:23 +02001744 if (nc_server_ssh_channel_open(session, msg)) {
Michal Vasko086311b2016-01-08 09:53:11 +01001745 ssh_message_reply_default(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001746 }
Michal Vasko086311b2016-01-08 09:53:11 +01001747 return 0;
Michal Vasko96164bf2016-01-21 15:41:58 +01001748
Michal Vasko0df67562016-01-21 15:50:11 +01001749 } else if ((type == SSH_REQUEST_CHANNEL) && ((enum ssh_channel_requests_e)subtype == SSH_CHANNEL_REQUEST_SUBSYSTEM)) {
romanbe162202024-05-22 14:19:23 +02001750 if (nc_server_ssh_channel_subsystem(session, ssh_message_channel_request_channel(msg),
Michal Vasko96164bf2016-01-21 15:41:58 +01001751 ssh_message_channel_request_subsystem(msg))) {
Michal Vasko086311b2016-01-08 09:53:11 +01001752 ssh_message_reply_default(msg);
Michal Vasko96164bf2016-01-21 15:41:58 +01001753 } else {
1754 ssh_message_channel_request_reply_success(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001755 }
1756 return 0;
1757 }
1758 }
1759
1760 /* we did not process it */
1761 return 1;
1762}
1763
Michal Vasko1a38c862016-01-15 15:50:07 +01001764/* ret 1 on success, 0 on timeout, -1 on error */
Michal Vasko086311b2016-01-08 09:53:11 +01001765static int
romanf578cd52023-10-19 09:47:40 +02001766nc_accept_ssh_session_open_netconf_channel(struct nc_session *session, struct nc_server_ssh_opts *opts, int timeout)
Michal Vasko086311b2016-01-08 09:53:11 +01001767{
roman6ece9c52022-06-22 09:29:17 +02001768 struct timespec ts_timeout;
romanf578cd52023-10-19 09:47:40 +02001769 ssh_message msg;
Michal Vasko086311b2016-01-08 09:53:11 +01001770
romanf578cd52023-10-19 09:47:40 +02001771 if (timeout) {
1772 nc_timeouttime_get(&ts_timeout, timeout * 1000);
Michal Vasko36c7be82017-02-22 13:37:59 +01001773 }
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001774 while (1) {
1775 if (!nc_session_is_connected(session)) {
romanf578cd52023-10-19 09:47:40 +02001776 ERR(session, "Communication SSH socket unexpectedly closed.");
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001777 return -1;
1778 }
1779
romanf578cd52023-10-19 09:47:40 +02001780 msg = ssh_message_get(session->ti.libssh.session);
1781 if (msg) {
1782 if (nc_session_ssh_msg(session, opts, msg, NULL)) {
1783 ssh_message_reply_default(msg);
1784 }
1785 ssh_message_free(msg);
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001786 }
1787
romanf578cd52023-10-19 09:47:40 +02001788 if (session->ti.libssh.channel && session->flags & NC_SESSION_SSH_SUBSYS_NETCONF) {
Michal Vasko1a38c862016-01-15 15:50:07 +01001789 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001790 }
1791
Michal Vasko086311b2016-01-08 09:53:11 +01001792 usleep(NC_TIMEOUT_STEP);
roman0b7e6982024-04-29 11:11:52 +02001793 if (timeout && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
roman6ece9c52022-06-22 09:29:17 +02001794 /* timeout */
1795 ERR(session, "Failed to start \"netconf\" SSH subsystem for too long, disconnecting.");
1796 break;
Michal Vasko36c7be82017-02-22 13:37:59 +01001797 }
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001798 }
Michal Vasko086311b2016-01-08 09:53:11 +01001799
Michal Vasko1a38c862016-01-15 15:50:07 +01001800 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001801}
1802
Michal Vaskof3c41e32022-09-09 11:22:21 +02001803/**
1804 * @brief Set hostkeys to be used for an SSH bind.
1805 *
1806 * @param[in] sbind SSH bind to use.
1807 * @param[in] hostkeys Array of hostkeys.
1808 * @param[in] hostkey_count Count of @p hostkeys.
1809 * @return 0 on success.
1810 * @return -1 on error.
1811 */
Michal Vasko4c1fb492017-01-30 14:31:07 +01001812static int
romanf578cd52023-10-19 09:47:40 +02001813nc_ssh_bind_add_hostkeys(ssh_bind sbind, struct nc_server_ssh_opts *opts, uint16_t hostkey_count)
Michal Vasko4c1fb492017-01-30 14:31:07 +01001814{
romanf578cd52023-10-19 09:47:40 +02001815 uint16_t i;
roman6dfdc0d2023-11-09 13:25:27 +01001816 char *privkey_path;
Michal Vaskoddce1212019-05-24 09:58:49 +02001817 int ret;
romanf578cd52023-10-19 09:47:40 +02001818 struct nc_asymmetric_key *key = NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +01001819
1820 for (i = 0; i < hostkey_count; ++i) {
roman6dfdc0d2023-11-09 13:25:27 +01001821 privkey_path = NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +01001822
romanf578cd52023-10-19 09:47:40 +02001823 /* get the asymmetric key */
1824 if (opts->hostkeys[i].store == NC_STORE_LOCAL) {
1825 /* stored locally */
1826 key = &opts->hostkeys[i].key;
1827 } else {
1828 /* keystore reference, need to get it */
1829 if (nc_server_ssh_ks_ref_get_key(opts->hostkeys[i].ks_ref, &key)) {
Michal Vasko4c1fb492017-01-30 14:31:07 +01001830 return -1;
1831 }
1832 }
1833
romanbe162202024-05-22 14:19:23 +02001834 privkey_path = nc_server_ssh_privkey_data_to_tmp_file(key->privkey_data, nc_privkey_format_to_str(key->privkey_type));
romanf578cd52023-10-19 09:47:40 +02001835 if (!privkey_path) {
1836 ERR(NULL, "Temporarily storing a host key into a file failed (%s).", strerror(errno));
1837 return -1;
1838 }
1839
Michal Vasko4c1fb492017-01-30 14:31:07 +01001840 ret = ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY, privkey_path);
1841
1842 /* cleanup */
roman6dfdc0d2023-11-09 13:25:27 +01001843 if (unlink(privkey_path)) {
Michal Vasko05532772021-06-03 12:12:38 +02001844 WRN(NULL, "Removing a temporary host key file \"%s\" failed (%s).", privkey_path, strerror(errno));
Michal Vasko4c1fb492017-01-30 14:31:07 +01001845 }
Michal Vasko4c1fb492017-01-30 14:31:07 +01001846
1847 if (ret != SSH_OK) {
romanf578cd52023-10-19 09:47:40 +02001848 ERR(NULL, "Failed to set hostkey \"%s\" (%s).", opts->hostkeys[i].name, privkey_path);
Michal Vasko80075de2017-07-10 11:38:52 +02001849 }
1850 free(privkey_path);
1851
1852 if (ret != SSH_OK) {
Michal Vasko4c1fb492017-01-30 14:31:07 +01001853 return -1;
1854 }
1855 }
1856
1857 return 0;
1858}
1859
Michal Vasko09d700f2022-09-08 10:21:40 +02001860static int
romanf578cd52023-10-19 09:47:40 +02001861nc_accept_ssh_session_auth(struct nc_session *session, struct nc_server_ssh_opts *opts)
Michal Vasko3031aae2016-01-27 16:07:18 +01001862{
roman6ece9c52022-06-22 09:29:17 +02001863 struct timespec ts_timeout;
roman41a11e42022-06-22 09:27:08 +02001864 ssh_message msg;
romanf578cd52023-10-19 09:47:40 +02001865 struct nc_auth_state state = {0};
Michal Vasko086311b2016-01-08 09:53:11 +01001866
Michal Vasko086311b2016-01-08 09:53:11 +01001867 /* authenticate */
Michal Vasko36c7be82017-02-22 13:37:59 +01001868 if (opts->auth_timeout) {
Michal Vaskod8a74192023-02-06 15:51:50 +01001869 nc_timeouttime_get(&ts_timeout, opts->auth_timeout * 1000);
Michal Vasko36c7be82017-02-22 13:37:59 +01001870 }
1871 while (1) {
Michal Vasko2a7d4732016-01-15 09:24:46 +01001872 if (!nc_session_is_connected(session)) {
Michal Vasko05532772021-06-03 12:12:38 +02001873 ERR(session, "Communication SSH socket unexpectedly closed.");
Michal Vasko2a7d4732016-01-15 09:24:46 +01001874 return -1;
1875 }
1876
roman41a11e42022-06-22 09:27:08 +02001877 msg = ssh_message_get(session->ti.libssh.session);
1878 if (msg) {
romanf578cd52023-10-19 09:47:40 +02001879 if (nc_session_ssh_msg(session, opts, msg, &state)) {
roman41a11e42022-06-22 09:27:08 +02001880 ssh_message_reply_default(msg);
1881 }
1882 ssh_message_free(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001883 }
1884
Michal Vasko36c7be82017-02-22 13:37:59 +01001885 if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
1886 break;
1887 }
1888
Michal Vasko086311b2016-01-08 09:53:11 +01001889 usleep(NC_TIMEOUT_STEP);
romanea0edaa2023-10-26 12:16:25 +02001890 if (opts->auth_timeout && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
roman6ece9c52022-06-22 09:29:17 +02001891 /* timeout */
1892 break;
Michal Vasko36c7be82017-02-22 13:37:59 +01001893 }
1894 }
Michal Vasko086311b2016-01-08 09:53:11 +01001895
1896 if (!(session->flags & NC_SESSION_SSH_AUTHENTICATED)) {
1897 /* timeout */
Michal Vaskoc13da702017-02-07 10:57:57 +01001898 if (session->username) {
Michal Vasko05532772021-06-03 12:12:38 +02001899 ERR(session, "User \"%s\" failed to authenticate for too long, disconnecting.", session->username);
Michal Vaskoc13da702017-02-07 10:57:57 +01001900 } else {
Michal Vasko05532772021-06-03 12:12:38 +02001901 ERR(session, "User failed to authenticate for too long, disconnecting.");
Michal Vaskoc13da702017-02-07 10:57:57 +01001902 }
Michal Vasko1a38c862016-01-15 15:50:07 +01001903 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001904 }
1905
Michal Vasko09d700f2022-09-08 10:21:40 +02001906 return 1;
1907}
1908
1909int
romanf578cd52023-10-19 09:47:40 +02001910nc_accept_ssh_session(struct nc_session *session, struct nc_server_ssh_opts *opts, int sock, int timeout)
Michal Vasko09d700f2022-09-08 10:21:40 +02001911{
1912 ssh_bind sbind = NULL;
Michal Vasko09d700f2022-09-08 10:21:40 +02001913 int rc = 1, r;
1914 struct timespec ts_timeout;
roman4cc0cd52023-04-14 09:12:29 +02001915 const char *err_msg;
Michal Vasko09d700f2022-09-08 10:21:40 +02001916
Michal Vasko09d700f2022-09-08 10:21:40 +02001917 /* other transport-specific data */
roman506354a2024-04-11 09:37:22 +02001918 session->ti_type = NC_TI_SSH;
Michal Vasko09d700f2022-09-08 10:21:40 +02001919 session->ti.libssh.session = ssh_new();
1920 if (!session->ti.libssh.session) {
1921 ERR(NULL, "Failed to initialize a new SSH session.");
1922 rc = -1;
1923 goto cleanup;
1924 }
1925
1926 sbind = ssh_bind_new();
1927 if (!sbind) {
1928 ERR(session, "Failed to create an SSH bind.");
1929 rc = -1;
1930 goto cleanup;
1931 }
1932
1933 /* configure host keys */
romanf578cd52023-10-19 09:47:40 +02001934 if (nc_ssh_bind_add_hostkeys(sbind, opts, opts->hostkey_count)) {
1935 rc = -1;
1936 goto cleanup;
1937 }
1938
1939 /* configure supported algorithms */
1940 if (opts->hostkey_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY_ALGORITHMS, opts->hostkey_algs)) {
1941 rc = -1;
1942 goto cleanup;
1943 }
1944 if (opts->encryption_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_CIPHERS_S_C, opts->encryption_algs)) {
1945 rc = -1;
1946 goto cleanup;
1947 }
1948 if (opts->kex_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_KEY_EXCHANGE, opts->kex_algs)) {
1949 rc = -1;
1950 goto cleanup;
1951 }
1952 if (opts->mac_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HMAC_S_C, opts->mac_algs)) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001953 rc = -1;
1954 goto cleanup;
1955 }
1956
1957 /* accept new connection on the bind */
1958 if (ssh_bind_accept_fd(sbind, session->ti.libssh.session, sock) == SSH_ERROR) {
1959 ERR(session, "SSH failed to accept a new connection (%s).", ssh_get_error(sbind));
1960 rc = -1;
1961 goto cleanup;
1962 }
1963 sock = -1;
1964
romanf578cd52023-10-19 09:47:40 +02001965 /* set to non-blocking */
Michal Vasko09d700f2022-09-08 10:21:40 +02001966 ssh_set_blocking(session->ti.libssh.session, 0);
1967
1968 if (timeout > -1) {
Michal Vaskod8a74192023-02-06 15:51:50 +01001969 nc_timeouttime_get(&ts_timeout, timeout);
Michal Vasko09d700f2022-09-08 10:21:40 +02001970 }
1971 while ((r = ssh_handle_key_exchange(session->ti.libssh.session)) == SSH_AGAIN) {
1972 /* this tends to take longer */
1973 usleep(NC_TIMEOUT_STEP * 20);
Michal Vaskod8a74192023-02-06 15:51:50 +01001974 if ((timeout > -1) && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001975 break;
1976 }
1977 }
1978 if (r == SSH_AGAIN) {
1979 ERR(session, "SSH key exchange timeout.");
1980 rc = 0;
1981 goto cleanup;
1982 } else if (r != SSH_OK) {
roman4cc0cd52023-04-14 09:12:29 +02001983 err_msg = ssh_get_error(session->ti.libssh.session);
1984 if (err_msg[0] == '\0') {
1985 err_msg = "hostkey algorithm generated from the hostkey most likely not found in the set of configured hostkey algorithms";
1986 }
1987 ERR(session, "SSH key exchange error (%s).", err_msg);
Michal Vasko09d700f2022-09-08 10:21:40 +02001988 rc = -1;
1989 goto cleanup;
1990 }
1991
romane5675b12024-03-05 14:26:23 +01001992 /* authenticate, store auth_timeout in session so we can retrieve it in kb interactive API */
1993 session->data = &opts->auth_timeout;
1994 rc = nc_accept_ssh_session_auth(session, opts);
1995 session->data = NULL;
1996 if (rc != 1) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001997 goto cleanup;
1998 }
1999
Michal Vasko09d700f2022-09-08 10:21:40 +02002000 /* open channel and request 'netconf' subsystem */
romanf578cd52023-10-19 09:47:40 +02002001 if ((rc = nc_accept_ssh_session_open_netconf_channel(session, opts, timeout)) != 1) {
Michal Vasko09d700f2022-09-08 10:21:40 +02002002 goto cleanup;
Michal Vasko086311b2016-01-08 09:53:11 +01002003 }
2004
Michal Vasko09d700f2022-09-08 10:21:40 +02002005cleanup:
2006 if (sock > -1) {
2007 close(sock);
2008 }
2009 ssh_bind_free(sbind);
2010 return rc;
Michal Vasko086311b2016-01-08 09:53:11 +01002011}
2012
Michal Vasko71090fc2016-05-24 16:37:28 +02002013API NC_MSG_TYPE
2014nc_session_accept_ssh_channel(struct nc_session *orig_session, struct nc_session **session)
2015{
2016 NC_MSG_TYPE msgtype;
2017 struct nc_session *new_session = NULL;
Michal Vasko9f6275e2017-10-05 13:50:05 +02002018 struct timespec ts_cur;
Michal Vasko71090fc2016-05-24 16:37:28 +02002019
roman40672412023-05-04 11:10:22 +02002020 NC_CHECK_ARG_RET(orig_session, orig_session, session, NC_MSG_ERROR);
Michal Vasko71090fc2016-05-24 16:37:28 +02002021
roman506354a2024-04-11 09:37:22 +02002022 if ((orig_session->status == NC_STATUS_RUNNING) && (orig_session->ti_type == NC_TI_SSH) &&
Michal Vaskob83a3fa2021-05-26 09:53:42 +02002023 orig_session->ti.libssh.next) {
Michal Vasko71090fc2016-05-24 16:37:28 +02002024 for (new_session = orig_session->ti.libssh.next;
2025 new_session != orig_session;
2026 new_session = new_session->ti.libssh.next) {
Michal Vaskob83a3fa2021-05-26 09:53:42 +02002027 if ((new_session->status == NC_STATUS_STARTING) && new_session->ti.libssh.channel &&
2028 (new_session->flags & NC_SESSION_SSH_SUBSYS_NETCONF)) {
Michal Vasko71090fc2016-05-24 16:37:28 +02002029 /* we found our session */
2030 break;
2031 }
2032 }
2033 if (new_session == orig_session) {
2034 new_session = NULL;
2035 }
2036 }
2037
2038 if (!new_session) {
Michal Vasko05532772021-06-03 12:12:38 +02002039 ERR(orig_session, "Session does not have a NETCONF SSH channel ready.");
Michal Vasko71090fc2016-05-24 16:37:28 +02002040 return NC_MSG_ERROR;
2041 }
2042
2043 /* assign new SID atomically */
Michal Vasko5bd4a3f2021-06-17 16:40:10 +02002044 new_session->id = ATOMIC_INC_RELAXED(server_opts.new_session_id);
Michal Vasko71090fc2016-05-24 16:37:28 +02002045
2046 /* NETCONF handshake */
Michal Vasko131120a2018-05-29 15:44:02 +02002047 msgtype = nc_handshake_io(new_session);
Michal Vasko71090fc2016-05-24 16:37:28 +02002048 if (msgtype != NC_MSG_HELLO) {
2049 return msgtype;
2050 }
2051
Michal Vaskod8a74192023-02-06 15:51:50 +01002052 nc_realtime_get(&ts_cur);
roman44efa322023-11-03 13:57:25 +01002053 new_session->opts.server.session_start = ts_cur;
Michal Vaskod8a74192023-02-06 15:51:50 +01002054 nc_timeouttime_get(&ts_cur, 0);
Michal Vasko9f6275e2017-10-05 13:50:05 +02002055 new_session->opts.server.last_rpc = ts_cur.tv_sec;
Michal Vasko71090fc2016-05-24 16:37:28 +02002056 new_session->status = NC_STATUS_RUNNING;
2057 *session = new_session;
2058
2059 return msgtype;
2060}
2061
2062API NC_MSG_TYPE
Michal Vasko96164bf2016-01-21 15:41:58 +01002063nc_ps_accept_ssh_channel(struct nc_pollsession *ps, struct nc_session **session)
Michal Vasko086311b2016-01-08 09:53:11 +01002064{
Michal Vaskobdcf2362016-07-26 11:35:43 +02002065 uint8_t q_id;
Michal Vasko71090fc2016-05-24 16:37:28 +02002066 NC_MSG_TYPE msgtype;
Michal Vaskoe4300a82017-05-24 10:35:42 +02002067 struct nc_session *new_session = NULL, *cur_session;
Michal Vasko9f6275e2017-10-05 13:50:05 +02002068 struct timespec ts_cur;
Michal Vaskoc61c4492016-01-25 11:13:34 +01002069 uint16_t i;
Michal Vasko086311b2016-01-08 09:53:11 +01002070
roman40672412023-05-04 11:10:22 +02002071 NC_CHECK_ARG_RET(NULL, ps, session, NC_MSG_ERROR);
Michal Vasko086311b2016-01-08 09:53:11 +01002072
Michal Vasko48a63ed2016-03-01 09:48:21 +01002073 /* LOCK */
Michal Vasko227f8ff2016-07-26 14:08:59 +02002074 if (nc_ps_lock(ps, &q_id, __func__)) {
Michal Vasko71090fc2016-05-24 16:37:28 +02002075 return NC_MSG_ERROR;
Michal Vaskof04a52a2016-04-07 10:52:10 +02002076 }
Michal Vasko48a63ed2016-03-01 09:48:21 +01002077
Michal Vasko96164bf2016-01-21 15:41:58 +01002078 for (i = 0; i < ps->session_count; ++i) {
fanchanghu3d4e7212017-08-09 09:42:30 +08002079 cur_session = ps->sessions[i]->session;
roman506354a2024-04-11 09:37:22 +02002080 if ((cur_session->status == NC_STATUS_RUNNING) && (cur_session->ti_type == NC_TI_SSH) &&
Michal Vaskob83a3fa2021-05-26 09:53:42 +02002081 cur_session->ti.libssh.next) {
Michal Vasko96164bf2016-01-21 15:41:58 +01002082 /* an SSH session with more channels */
Michal Vaskoe4300a82017-05-24 10:35:42 +02002083 for (new_session = cur_session->ti.libssh.next;
2084 new_session != cur_session;
Michal Vasko96164bf2016-01-21 15:41:58 +01002085 new_session = new_session->ti.libssh.next) {
Michal Vaskob83a3fa2021-05-26 09:53:42 +02002086 if ((new_session->status == NC_STATUS_STARTING) && new_session->ti.libssh.channel &&
2087 (new_session->flags & NC_SESSION_SSH_SUBSYS_NETCONF)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01002088 /* we found our session */
2089 break;
2090 }
2091 }
Michal Vaskoe4300a82017-05-24 10:35:42 +02002092 if (new_session != cur_session) {
Michal Vasko96164bf2016-01-21 15:41:58 +01002093 break;
2094 }
Michal Vaskofb89d772016-01-08 12:25:35 +01002095
Michal Vasko96164bf2016-01-21 15:41:58 +01002096 new_session = NULL;
2097 }
2098 }
Michal Vaskofb89d772016-01-08 12:25:35 +01002099
Michal Vasko48a63ed2016-03-01 09:48:21 +01002100 /* UNLOCK */
Michal Vasko227f8ff2016-07-26 14:08:59 +02002101 nc_ps_unlock(ps, q_id, __func__);
Michal Vasko48a63ed2016-03-01 09:48:21 +01002102
Michal Vasko96164bf2016-01-21 15:41:58 +01002103 if (!new_session) {
Michal Vasko05532772021-06-03 12:12:38 +02002104 ERR(NULL, "No session with a NETCONF SSH channel ready was found.");
Michal Vasko71090fc2016-05-24 16:37:28 +02002105 return NC_MSG_ERROR;
Michal Vasko96164bf2016-01-21 15:41:58 +01002106 }
2107
2108 /* assign new SID atomically */
Michal Vasko5bd4a3f2021-06-17 16:40:10 +02002109 new_session->id = ATOMIC_INC_RELAXED(server_opts.new_session_id);
Michal Vaskofb89d772016-01-08 12:25:35 +01002110
Michal Vasko086311b2016-01-08 09:53:11 +01002111 /* NETCONF handshake */
Michal Vasko131120a2018-05-29 15:44:02 +02002112 msgtype = nc_handshake_io(new_session);
Michal Vasko71090fc2016-05-24 16:37:28 +02002113 if (msgtype != NC_MSG_HELLO) {
2114 return msgtype;
Michal Vasko086311b2016-01-08 09:53:11 +01002115 }
Michal Vasko48a63ed2016-03-01 09:48:21 +01002116
Michal Vaskod8a74192023-02-06 15:51:50 +01002117 nc_realtime_get(&ts_cur);
roman44efa322023-11-03 13:57:25 +01002118 new_session->opts.server.session_start = ts_cur;
Michal Vaskod8a74192023-02-06 15:51:50 +01002119 nc_timeouttime_get(&ts_cur, 0);
Michal Vasko9f6275e2017-10-05 13:50:05 +02002120 new_session->opts.server.last_rpc = ts_cur.tv_sec;
Michal Vasko086311b2016-01-08 09:53:11 +01002121 new_session->status = NC_STATUS_RUNNING;
Michal Vasko96164bf2016-01-21 15:41:58 +01002122 *session = new_session;
Michal Vasko086311b2016-01-08 09:53:11 +01002123
Michal Vasko71090fc2016-05-24 16:37:28 +02002124 return msgtype;
Michal Vasko086311b2016-01-08 09:53:11 +01002125}