blob: 71a60f1fbfc36342040af86ce7389cff665be37f [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.
roman127f1ec2024-08-22 10:52:45 +02001441 * @param[in,out] auth_state Authentication state.
romanbe162202024-05-22 14:19:23 +02001442 * @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,
roman127f1ec2024-08-22 10:52:45 +02001446 int method, const char *str_method, int local_users_supported, struct nc_auth_state *auth_state)
Michal Vasko086311b2016-01-08 09:53:11 +01001447{
romanbe162202024-05-22 14:19:23 +02001448 const char *username;
roman127f1ec2024-08-22 10:52:45 +02001449 int 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,
roman127f1ec2024-08-22 10:52:45 +02001476 str_method, local_users_supported, auth_state);
romanbe162202024-05-22 14:19:23 +02001477 }
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) */
roman127f1ec2024-08-22 10:52:45 +02001498 auth_state->methods |= SSH_AUTH_METHOD_PUBLICKEY;
1499 auth_state->method_count++;
romanbe162202024-05-22 14:19:23 +02001500 }
1501 if (auth_client->password) {
roman127f1ec2024-08-22 10:52:45 +02001502 auth_state->methods |= SSH_AUTH_METHOD_PASSWORD;
1503 auth_state->method_count++;
romanbe162202024-05-22 14:19:23 +02001504 }
1505 if (auth_client->kb_int_enabled) {
roman127f1ec2024-08-22 10:52:45 +02001506 auth_state->methods |= SSH_AUTH_METHOD_INTERACTIVE;
1507 auth_state->method_count++;
romanbe162202024-05-22 14:19:23 +02001508 }
1509 if (auth_client->none_enabled) {
roman127f1ec2024-08-22 10:52:45 +02001510 auth_state->methods |= SSH_AUTH_METHOD_NONE;
1511 auth_state->method_count++;
romanbe162202024-05-22 14:19:23 +02001512 }
1513 } else {
1514 /* no local users meaning pw, pubkey and kbdint methods are supported, method count is set to 1,
roman127f1ec2024-08-22 10:52:45 +02001515 * because only one method is needed for successful auth */
1516 auth_state->methods = SSH_AUTH_METHOD_PUBLICKEY | SSH_AUTH_METHOD_PASSWORD | SSH_AUTH_METHOD_INTERACTIVE;
1517 auth_state->method_count = 1;
romanbe162202024-05-22 14:19:23 +02001518 }
1519
roman127f1ec2024-08-22 10:52:45 +02001520 ssh_set_auth_methods(session->ti.libssh.session, auth_state->methods);
romanbe162202024-05-22 14:19:23 +02001521 } 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) {
roman127f1ec2024-08-22 10:52:45 +02001550 auth_state->success_methods |= method;
1551 auth_state->success_count++;
romanbe162202024-05-22 14:19:23 +02001552
roman127f1ec2024-08-22 10:52:45 +02001553 if (auth_state->success_count < auth_state->method_count) {
romanbe162202024-05-22 14:19:23 +02001554 /* success, but he needs to do another method */
1555 VRB(session, "User \"%s\" partially authenticated, but still needs to authenticate via the rest of his configured methods.", username);
roman127f1ec2024-08-22 10:52:45 +02001556 ssh_set_auth_methods(session->ti.libssh.session, auth_state->methods & ~auth_state->success_methods);
romanbe162202024-05-22 14:19:23 +02001557 ssh_message_auth_reply_success(msg, 1);
1558 } else {
1559 /* authenticated */
1560 ssh_message_auth_reply_success(msg, 0);
1561 session->flags |= NC_SESSION_SSH_AUTHENTICATED;
1562 VRB(session, "User \"%s\" authenticated.", username);
1563 }
1564 } else if (ret == 1) {
1565 /* failed attempt, msg wasnt yet replied to */
1566 ++session->opts.server.ssh_auth_attempts;
1567 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", session->username,
1568 session->opts.server.ssh_auth_attempts);
1569 ssh_message_reply_default(msg);
1570 }
1571
1572 return 0;
1573}
1574
1575int
roman127f1ec2024-08-22 10:52:45 +02001576nc_session_ssh_msg(struct nc_session *session, struct nc_server_ssh_opts *opts, ssh_message msg, struct nc_auth_state *auth_state)
romanbe162202024-05-22 14:19:23 +02001577{
1578 const char *str_type, *str_subtype = NULL;
1579 int subtype, type, rc, local_users_supported;
1580 const struct ly_ctx *ctx;
1581 struct lys_module *mod;
1582
Michal Vasko086311b2016-01-08 09:53:11 +01001583 type = ssh_message_type(msg);
1584 subtype = ssh_message_subtype(msg);
1585
1586 switch (type) {
1587 case SSH_REQUEST_AUTH:
1588 str_type = "request-auth";
1589 switch (subtype) {
1590 case SSH_AUTH_METHOD_NONE:
1591 str_subtype = "none";
1592 break;
1593 case SSH_AUTH_METHOD_PASSWORD:
1594 str_subtype = "password";
1595 break;
1596 case SSH_AUTH_METHOD_PUBLICKEY:
1597 str_subtype = "publickey";
1598 break;
1599 case SSH_AUTH_METHOD_HOSTBASED:
1600 str_subtype = "hostbased";
1601 break;
1602 case SSH_AUTH_METHOD_INTERACTIVE:
1603 str_subtype = "interactive";
1604 break;
1605 case SSH_AUTH_METHOD_GSSAPI_MIC:
1606 str_subtype = "gssapi-mic";
1607 break;
1608 }
1609 break;
1610
1611 case SSH_REQUEST_CHANNEL_OPEN:
1612 str_type = "request-channel-open";
1613 switch (subtype) {
1614 case SSH_CHANNEL_SESSION:
1615 str_subtype = "session";
1616 break;
1617 case SSH_CHANNEL_DIRECT_TCPIP:
1618 str_subtype = "direct-tcpip";
1619 break;
1620 case SSH_CHANNEL_FORWARDED_TCPIP:
1621 str_subtype = "forwarded-tcpip";
1622 break;
1623 case (int)SSH_CHANNEL_X11:
1624 str_subtype = "channel-x11";
1625 break;
1626 case SSH_CHANNEL_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001627 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001628 default:
1629 str_subtype = "unknown";
1630 break;
1631 }
1632 break;
1633
1634 case SSH_REQUEST_CHANNEL:
1635 str_type = "request-channel";
1636 switch (subtype) {
1637 case SSH_CHANNEL_REQUEST_PTY:
1638 str_subtype = "pty";
1639 break;
1640 case SSH_CHANNEL_REQUEST_EXEC:
1641 str_subtype = "exec";
1642 break;
1643 case SSH_CHANNEL_REQUEST_SHELL:
1644 str_subtype = "shell";
1645 break;
1646 case SSH_CHANNEL_REQUEST_ENV:
1647 str_subtype = "env";
1648 break;
1649 case SSH_CHANNEL_REQUEST_SUBSYSTEM:
1650 str_subtype = "subsystem";
1651 break;
1652 case SSH_CHANNEL_REQUEST_WINDOW_CHANGE:
1653 str_subtype = "window-change";
1654 break;
1655 case SSH_CHANNEL_REQUEST_X11:
1656 str_subtype = "x11";
1657 break;
1658 case SSH_CHANNEL_REQUEST_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001659 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001660 default:
1661 str_subtype = "unknown";
1662 break;
1663 }
1664 break;
1665
1666 case SSH_REQUEST_SERVICE:
1667 str_type = "request-service";
1668 str_subtype = ssh_message_service_service(msg);
1669 break;
1670
1671 case SSH_REQUEST_GLOBAL:
1672 str_type = "request-global";
1673 switch (subtype) {
1674 case SSH_GLOBAL_REQUEST_TCPIP_FORWARD:
1675 str_subtype = "tcpip-forward";
1676 break;
1677 case SSH_GLOBAL_REQUEST_CANCEL_TCPIP_FORWARD:
1678 str_subtype = "cancel-tcpip-forward";
1679 break;
1680 case SSH_GLOBAL_REQUEST_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001681 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001682 default:
1683 str_subtype = "unknown";
1684 break;
1685 }
1686 break;
1687
1688 default:
1689 str_type = "unknown";
1690 str_subtype = "unknown";
1691 break;
1692 }
1693
Michal Vasko05532772021-06-03 12:12:38 +02001694 VRB(session, "Received an SSH message \"%s\" of subtype \"%s\".", str_type, str_subtype);
Michal Vasko5e0edd82020-07-29 15:26:13 +02001695 if (!session || (session->status == NC_STATUS_CLOSING) || (session->status == NC_STATUS_INVALID)) {
Michal Vaskoce319162016-02-03 15:33:08 +01001696 /* "valid" situation if, for example, receiving some auth or channel request timeouted,
1697 * but we got it now, during session free */
Michal Vasko05532772021-06-03 12:12:38 +02001698 VRB(session, "SSH message arrived on a %s session, the request will be denied.",
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001699 (session && session->status == NC_STATUS_CLOSING ? "closing" : "invalid"));
Michal Vaskoce319162016-02-03 15:33:08 +01001700 ssh_message_reply_default(msg);
1701 return 0;
1702 }
Michal Vasko086311b2016-01-08 09:53:11 +01001703
1704 /*
1705 * process known messages
1706 */
1707 if (type == SSH_REQUEST_AUTH) {
1708 if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
Michal Vasko05532772021-06-03 12:12:38 +02001709 ERR(session, "User \"%s\" authenticated, but requested another authentication.", session->username);
Michal Vasko086311b2016-01-08 09:53:11 +01001710 ssh_message_reply_default(msg);
1711 return 0;
roman127f1ec2024-08-22 10:52:45 +02001712 } else if (!auth_state || !opts) {
romanf578cd52023-10-19 09:47:40 +02001713 /* these two parameters should always be set during an authentication,
1714 * however do a check just in case something goes really wrong, since they
1715 * are not needed for other types of messages
1716 */
1717 ERRINT;
1718 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001719 }
1720
romanbe162202024-05-22 14:19:23 +02001721 /* get libyang ctx from session and ietf-ssh-server yang model from the ctx */
1722 ctx = nc_session_get_ctx(session);
1723 mod = ly_ctx_get_module_latest(ctx, "ietf-ssh-server");
1724 if (!mod) {
1725 ERRINT;
1726 return 1;
romanf578cd52023-10-19 09:47:40 +02001727 }
1728
romanbe162202024-05-22 14:19:23 +02001729 /* check if local-users-supported feature is enabled */
1730 rc = lys_feature_value(mod, "local-users-supported");
1731 if (!rc) {
roman5858e6d2024-05-23 09:18:22 +02001732 /* using users from the YANG data */
romanbe162202024-05-22 14:19:23 +02001733 local_users_supported = 1;
1734 } else if (rc == LY_ENOT) {
roman5858e6d2024-05-23 09:18:22 +02001735 /* using users from the system */
romanbe162202024-05-22 14:19:23 +02001736 local_users_supported = 0;
romanf578cd52023-10-19 09:47:40 +02001737 } else {
romanbe162202024-05-22 14:19:23 +02001738 ERRINT;
1739 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001740 }
1741
romanbe162202024-05-22 14:19:23 +02001742 /* authenticate */
roman127f1ec2024-08-22 10:52:45 +02001743 return nc_server_ssh_auth(session, opts, msg, subtype, str_subtype, local_users_supported, auth_state);
Michal Vasko086311b2016-01-08 09:53:11 +01001744 } else if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
Michal Vasko0df67562016-01-21 15:50:11 +01001745 if ((type == SSH_REQUEST_CHANNEL_OPEN) && ((enum ssh_channel_type_e)subtype == SSH_CHANNEL_SESSION)) {
romanbe162202024-05-22 14:19:23 +02001746 if (nc_server_ssh_channel_open(session, msg)) {
Michal Vasko086311b2016-01-08 09:53:11 +01001747 ssh_message_reply_default(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001748 }
Michal Vasko086311b2016-01-08 09:53:11 +01001749 return 0;
Michal Vasko96164bf2016-01-21 15:41:58 +01001750
Michal Vasko0df67562016-01-21 15:50:11 +01001751 } else if ((type == SSH_REQUEST_CHANNEL) && ((enum ssh_channel_requests_e)subtype == SSH_CHANNEL_REQUEST_SUBSYSTEM)) {
romanbe162202024-05-22 14:19:23 +02001752 if (nc_server_ssh_channel_subsystem(session, ssh_message_channel_request_channel(msg),
Michal Vasko96164bf2016-01-21 15:41:58 +01001753 ssh_message_channel_request_subsystem(msg))) {
Michal Vasko086311b2016-01-08 09:53:11 +01001754 ssh_message_reply_default(msg);
Michal Vasko96164bf2016-01-21 15:41:58 +01001755 } else {
1756 ssh_message_channel_request_reply_success(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001757 }
1758 return 0;
1759 }
1760 }
1761
1762 /* we did not process it */
1763 return 1;
1764}
1765
Michal Vasko1a38c862016-01-15 15:50:07 +01001766/* ret 1 on success, 0 on timeout, -1 on error */
Michal Vasko086311b2016-01-08 09:53:11 +01001767static int
romanf578cd52023-10-19 09:47:40 +02001768nc_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 +01001769{
roman6ece9c52022-06-22 09:29:17 +02001770 struct timespec ts_timeout;
romanf578cd52023-10-19 09:47:40 +02001771 ssh_message msg;
Michal Vasko086311b2016-01-08 09:53:11 +01001772
romanf578cd52023-10-19 09:47:40 +02001773 if (timeout) {
1774 nc_timeouttime_get(&ts_timeout, timeout * 1000);
Michal Vasko36c7be82017-02-22 13:37:59 +01001775 }
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001776 while (1) {
1777 if (!nc_session_is_connected(session)) {
romanf578cd52023-10-19 09:47:40 +02001778 ERR(session, "Communication SSH socket unexpectedly closed.");
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001779 return -1;
1780 }
1781
romanf578cd52023-10-19 09:47:40 +02001782 msg = ssh_message_get(session->ti.libssh.session);
1783 if (msg) {
1784 if (nc_session_ssh_msg(session, opts, msg, NULL)) {
1785 ssh_message_reply_default(msg);
1786 }
1787 ssh_message_free(msg);
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001788 }
1789
romanf578cd52023-10-19 09:47:40 +02001790 if (session->ti.libssh.channel && session->flags & NC_SESSION_SSH_SUBSYS_NETCONF) {
Michal Vasko1a38c862016-01-15 15:50:07 +01001791 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001792 }
1793
Michal Vasko086311b2016-01-08 09:53:11 +01001794 usleep(NC_TIMEOUT_STEP);
roman0b7e6982024-04-29 11:11:52 +02001795 if (timeout && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
roman6ece9c52022-06-22 09:29:17 +02001796 /* timeout */
1797 ERR(session, "Failed to start \"netconf\" SSH subsystem for too long, disconnecting.");
1798 break;
Michal Vasko36c7be82017-02-22 13:37:59 +01001799 }
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001800 }
Michal Vasko086311b2016-01-08 09:53:11 +01001801
Michal Vasko1a38c862016-01-15 15:50:07 +01001802 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001803}
1804
Michal Vaskof3c41e32022-09-09 11:22:21 +02001805/**
1806 * @brief Set hostkeys to be used for an SSH bind.
1807 *
1808 * @param[in] sbind SSH bind to use.
1809 * @param[in] hostkeys Array of hostkeys.
1810 * @param[in] hostkey_count Count of @p hostkeys.
1811 * @return 0 on success.
1812 * @return -1 on error.
1813 */
Michal Vasko4c1fb492017-01-30 14:31:07 +01001814static int
romanf578cd52023-10-19 09:47:40 +02001815nc_ssh_bind_add_hostkeys(ssh_bind sbind, struct nc_server_ssh_opts *opts, uint16_t hostkey_count)
Michal Vasko4c1fb492017-01-30 14:31:07 +01001816{
romanf578cd52023-10-19 09:47:40 +02001817 uint16_t i;
roman6dfdc0d2023-11-09 13:25:27 +01001818 char *privkey_path;
Michal Vaskoddce1212019-05-24 09:58:49 +02001819 int ret;
romanf578cd52023-10-19 09:47:40 +02001820 struct nc_asymmetric_key *key = NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +01001821
1822 for (i = 0; i < hostkey_count; ++i) {
roman6dfdc0d2023-11-09 13:25:27 +01001823 privkey_path = NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +01001824
romanf578cd52023-10-19 09:47:40 +02001825 /* get the asymmetric key */
1826 if (opts->hostkeys[i].store == NC_STORE_LOCAL) {
1827 /* stored locally */
1828 key = &opts->hostkeys[i].key;
1829 } else {
1830 /* keystore reference, need to get it */
1831 if (nc_server_ssh_ks_ref_get_key(opts->hostkeys[i].ks_ref, &key)) {
Michal Vasko4c1fb492017-01-30 14:31:07 +01001832 return -1;
1833 }
1834 }
1835
romanbe162202024-05-22 14:19:23 +02001836 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 +02001837 if (!privkey_path) {
1838 ERR(NULL, "Temporarily storing a host key into a file failed (%s).", strerror(errno));
1839 return -1;
1840 }
1841
Michal Vasko4c1fb492017-01-30 14:31:07 +01001842 ret = ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY, privkey_path);
1843
1844 /* cleanup */
roman6dfdc0d2023-11-09 13:25:27 +01001845 if (unlink(privkey_path)) {
Michal Vasko05532772021-06-03 12:12:38 +02001846 WRN(NULL, "Removing a temporary host key file \"%s\" failed (%s).", privkey_path, strerror(errno));
Michal Vasko4c1fb492017-01-30 14:31:07 +01001847 }
Michal Vasko4c1fb492017-01-30 14:31:07 +01001848
1849 if (ret != SSH_OK) {
romanf578cd52023-10-19 09:47:40 +02001850 ERR(NULL, "Failed to set hostkey \"%s\" (%s).", opts->hostkeys[i].name, privkey_path);
Michal Vasko80075de2017-07-10 11:38:52 +02001851 }
1852 free(privkey_path);
1853
1854 if (ret != SSH_OK) {
Michal Vasko4c1fb492017-01-30 14:31:07 +01001855 return -1;
1856 }
1857 }
1858
1859 return 0;
1860}
1861
Michal Vasko09d700f2022-09-08 10:21:40 +02001862static int
romanf578cd52023-10-19 09:47:40 +02001863nc_accept_ssh_session_auth(struct nc_session *session, struct nc_server_ssh_opts *opts)
Michal Vasko3031aae2016-01-27 16:07:18 +01001864{
roman6ece9c52022-06-22 09:29:17 +02001865 struct timespec ts_timeout;
roman41a11e42022-06-22 09:27:08 +02001866 ssh_message msg;
roman127f1ec2024-08-22 10:52:45 +02001867 struct nc_auth_state auth_state = {0};
Michal Vasko086311b2016-01-08 09:53:11 +01001868
Michal Vasko086311b2016-01-08 09:53:11 +01001869 /* authenticate */
Michal Vasko36c7be82017-02-22 13:37:59 +01001870 if (opts->auth_timeout) {
Michal Vaskod8a74192023-02-06 15:51:50 +01001871 nc_timeouttime_get(&ts_timeout, opts->auth_timeout * 1000);
Michal Vasko36c7be82017-02-22 13:37:59 +01001872 }
1873 while (1) {
Michal Vasko2a7d4732016-01-15 09:24:46 +01001874 if (!nc_session_is_connected(session)) {
Michal Vasko05532772021-06-03 12:12:38 +02001875 ERR(session, "Communication SSH socket unexpectedly closed.");
Michal Vasko2a7d4732016-01-15 09:24:46 +01001876 return -1;
1877 }
1878
roman41a11e42022-06-22 09:27:08 +02001879 msg = ssh_message_get(session->ti.libssh.session);
1880 if (msg) {
roman127f1ec2024-08-22 10:52:45 +02001881 if (nc_session_ssh_msg(session, opts, msg, &auth_state)) {
roman41a11e42022-06-22 09:27:08 +02001882 ssh_message_reply_default(msg);
1883 }
1884 ssh_message_free(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001885 }
1886
Michal Vasko36c7be82017-02-22 13:37:59 +01001887 if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
1888 break;
1889 }
1890
Michal Vasko086311b2016-01-08 09:53:11 +01001891 usleep(NC_TIMEOUT_STEP);
romanea0edaa2023-10-26 12:16:25 +02001892 if (opts->auth_timeout && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
roman6ece9c52022-06-22 09:29:17 +02001893 /* timeout */
1894 break;
Michal Vasko36c7be82017-02-22 13:37:59 +01001895 }
1896 }
Michal Vasko086311b2016-01-08 09:53:11 +01001897
1898 if (!(session->flags & NC_SESSION_SSH_AUTHENTICATED)) {
1899 /* timeout */
Michal Vaskoc13da702017-02-07 10:57:57 +01001900 if (session->username) {
Michal Vasko05532772021-06-03 12:12:38 +02001901 ERR(session, "User \"%s\" failed to authenticate for too long, disconnecting.", session->username);
Michal Vaskoc13da702017-02-07 10:57:57 +01001902 } else {
Michal Vasko05532772021-06-03 12:12:38 +02001903 ERR(session, "User failed to authenticate for too long, disconnecting.");
Michal Vaskoc13da702017-02-07 10:57:57 +01001904 }
Michal Vasko1a38c862016-01-15 15:50:07 +01001905 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001906 }
1907
Michal Vasko09d700f2022-09-08 10:21:40 +02001908 return 1;
1909}
1910
1911int
romanf578cd52023-10-19 09:47:40 +02001912nc_accept_ssh_session(struct nc_session *session, struct nc_server_ssh_opts *opts, int sock, int timeout)
Michal Vasko09d700f2022-09-08 10:21:40 +02001913{
1914 ssh_bind sbind = NULL;
Michal Vasko09d700f2022-09-08 10:21:40 +02001915 int rc = 1, r;
1916 struct timespec ts_timeout;
roman4cc0cd52023-04-14 09:12:29 +02001917 const char *err_msg;
Michal Vasko09d700f2022-09-08 10:21:40 +02001918
Michal Vasko09d700f2022-09-08 10:21:40 +02001919 /* other transport-specific data */
roman506354a2024-04-11 09:37:22 +02001920 session->ti_type = NC_TI_SSH;
Michal Vasko09d700f2022-09-08 10:21:40 +02001921 session->ti.libssh.session = ssh_new();
1922 if (!session->ti.libssh.session) {
1923 ERR(NULL, "Failed to initialize a new SSH session.");
1924 rc = -1;
1925 goto cleanup;
1926 }
1927
1928 sbind = ssh_bind_new();
1929 if (!sbind) {
1930 ERR(session, "Failed to create an SSH bind.");
1931 rc = -1;
1932 goto cleanup;
1933 }
1934
1935 /* configure host keys */
romanf578cd52023-10-19 09:47:40 +02001936 if (nc_ssh_bind_add_hostkeys(sbind, opts, opts->hostkey_count)) {
1937 rc = -1;
1938 goto cleanup;
1939 }
1940
1941 /* configure supported algorithms */
1942 if (opts->hostkey_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY_ALGORITHMS, opts->hostkey_algs)) {
1943 rc = -1;
1944 goto cleanup;
1945 }
1946 if (opts->encryption_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_CIPHERS_S_C, opts->encryption_algs)) {
1947 rc = -1;
1948 goto cleanup;
1949 }
1950 if (opts->kex_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_KEY_EXCHANGE, opts->kex_algs)) {
1951 rc = -1;
1952 goto cleanup;
1953 }
1954 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 +02001955 rc = -1;
1956 goto cleanup;
1957 }
1958
1959 /* accept new connection on the bind */
1960 if (ssh_bind_accept_fd(sbind, session->ti.libssh.session, sock) == SSH_ERROR) {
1961 ERR(session, "SSH failed to accept a new connection (%s).", ssh_get_error(sbind));
1962 rc = -1;
1963 goto cleanup;
1964 }
1965 sock = -1;
1966
romanf578cd52023-10-19 09:47:40 +02001967 /* set to non-blocking */
Michal Vasko09d700f2022-09-08 10:21:40 +02001968 ssh_set_blocking(session->ti.libssh.session, 0);
1969
1970 if (timeout > -1) {
Michal Vaskod8a74192023-02-06 15:51:50 +01001971 nc_timeouttime_get(&ts_timeout, timeout);
Michal Vasko09d700f2022-09-08 10:21:40 +02001972 }
1973 while ((r = ssh_handle_key_exchange(session->ti.libssh.session)) == SSH_AGAIN) {
1974 /* this tends to take longer */
1975 usleep(NC_TIMEOUT_STEP * 20);
Michal Vaskod8a74192023-02-06 15:51:50 +01001976 if ((timeout > -1) && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001977 break;
1978 }
1979 }
1980 if (r == SSH_AGAIN) {
1981 ERR(session, "SSH key exchange timeout.");
1982 rc = 0;
1983 goto cleanup;
1984 } else if (r != SSH_OK) {
roman4cc0cd52023-04-14 09:12:29 +02001985 err_msg = ssh_get_error(session->ti.libssh.session);
1986 if (err_msg[0] == '\0') {
1987 err_msg = "hostkey algorithm generated from the hostkey most likely not found in the set of configured hostkey algorithms";
1988 }
1989 ERR(session, "SSH key exchange error (%s).", err_msg);
Michal Vasko09d700f2022-09-08 10:21:40 +02001990 rc = -1;
1991 goto cleanup;
1992 }
1993
romane5675b12024-03-05 14:26:23 +01001994 /* authenticate, store auth_timeout in session so we can retrieve it in kb interactive API */
1995 session->data = &opts->auth_timeout;
1996 rc = nc_accept_ssh_session_auth(session, opts);
1997 session->data = NULL;
1998 if (rc != 1) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001999 goto cleanup;
2000 }
2001
Michal Vasko09d700f2022-09-08 10:21:40 +02002002 /* open channel and request 'netconf' subsystem */
romanf578cd52023-10-19 09:47:40 +02002003 if ((rc = nc_accept_ssh_session_open_netconf_channel(session, opts, timeout)) != 1) {
Michal Vasko09d700f2022-09-08 10:21:40 +02002004 goto cleanup;
Michal Vasko086311b2016-01-08 09:53:11 +01002005 }
2006
Michal Vasko09d700f2022-09-08 10:21:40 +02002007cleanup:
2008 if (sock > -1) {
2009 close(sock);
2010 }
2011 ssh_bind_free(sbind);
2012 return rc;
Michal Vasko086311b2016-01-08 09:53:11 +01002013}
2014
Michal Vasko71090fc2016-05-24 16:37:28 +02002015API NC_MSG_TYPE
2016nc_session_accept_ssh_channel(struct nc_session *orig_session, struct nc_session **session)
2017{
2018 NC_MSG_TYPE msgtype;
2019 struct nc_session *new_session = NULL;
Michal Vasko9f6275e2017-10-05 13:50:05 +02002020 struct timespec ts_cur;
Michal Vasko71090fc2016-05-24 16:37:28 +02002021
roman40672412023-05-04 11:10:22 +02002022 NC_CHECK_ARG_RET(orig_session, orig_session, session, NC_MSG_ERROR);
Michal Vasko71090fc2016-05-24 16:37:28 +02002023
roman506354a2024-04-11 09:37:22 +02002024 if ((orig_session->status == NC_STATUS_RUNNING) && (orig_session->ti_type == NC_TI_SSH) &&
Michal Vaskob83a3fa2021-05-26 09:53:42 +02002025 orig_session->ti.libssh.next) {
Michal Vasko71090fc2016-05-24 16:37:28 +02002026 for (new_session = orig_session->ti.libssh.next;
2027 new_session != orig_session;
2028 new_session = new_session->ti.libssh.next) {
Michal Vaskob83a3fa2021-05-26 09:53:42 +02002029 if ((new_session->status == NC_STATUS_STARTING) && new_session->ti.libssh.channel &&
2030 (new_session->flags & NC_SESSION_SSH_SUBSYS_NETCONF)) {
Michal Vasko71090fc2016-05-24 16:37:28 +02002031 /* we found our session */
2032 break;
2033 }
2034 }
2035 if (new_session == orig_session) {
2036 new_session = NULL;
2037 }
2038 }
2039
2040 if (!new_session) {
Michal Vasko05532772021-06-03 12:12:38 +02002041 ERR(orig_session, "Session does not have a NETCONF SSH channel ready.");
Michal Vasko71090fc2016-05-24 16:37:28 +02002042 return NC_MSG_ERROR;
2043 }
2044
2045 /* assign new SID atomically */
Michal Vasko5bd4a3f2021-06-17 16:40:10 +02002046 new_session->id = ATOMIC_INC_RELAXED(server_opts.new_session_id);
Michal Vasko71090fc2016-05-24 16:37:28 +02002047
2048 /* NETCONF handshake */
Michal Vasko131120a2018-05-29 15:44:02 +02002049 msgtype = nc_handshake_io(new_session);
Michal Vasko71090fc2016-05-24 16:37:28 +02002050 if (msgtype != NC_MSG_HELLO) {
2051 return msgtype;
2052 }
2053
Michal Vaskod8a74192023-02-06 15:51:50 +01002054 nc_realtime_get(&ts_cur);
roman44efa322023-11-03 13:57:25 +01002055 new_session->opts.server.session_start = ts_cur;
Michal Vaskod8a74192023-02-06 15:51:50 +01002056 nc_timeouttime_get(&ts_cur, 0);
Michal Vasko9f6275e2017-10-05 13:50:05 +02002057 new_session->opts.server.last_rpc = ts_cur.tv_sec;
Michal Vasko71090fc2016-05-24 16:37:28 +02002058 new_session->status = NC_STATUS_RUNNING;
2059 *session = new_session;
2060
2061 return msgtype;
2062}
2063
2064API NC_MSG_TYPE
Michal Vasko96164bf2016-01-21 15:41:58 +01002065nc_ps_accept_ssh_channel(struct nc_pollsession *ps, struct nc_session **session)
Michal Vasko086311b2016-01-08 09:53:11 +01002066{
Michal Vaskobdcf2362016-07-26 11:35:43 +02002067 uint8_t q_id;
Michal Vasko71090fc2016-05-24 16:37:28 +02002068 NC_MSG_TYPE msgtype;
Michal Vaskoe4300a82017-05-24 10:35:42 +02002069 struct nc_session *new_session = NULL, *cur_session;
Michal Vasko9f6275e2017-10-05 13:50:05 +02002070 struct timespec ts_cur;
Michal Vaskoc61c4492016-01-25 11:13:34 +01002071 uint16_t i;
Michal Vasko086311b2016-01-08 09:53:11 +01002072
roman40672412023-05-04 11:10:22 +02002073 NC_CHECK_ARG_RET(NULL, ps, session, NC_MSG_ERROR);
Michal Vasko086311b2016-01-08 09:53:11 +01002074
Michal Vasko48a63ed2016-03-01 09:48:21 +01002075 /* LOCK */
Michal Vasko227f8ff2016-07-26 14:08:59 +02002076 if (nc_ps_lock(ps, &q_id, __func__)) {
Michal Vasko71090fc2016-05-24 16:37:28 +02002077 return NC_MSG_ERROR;
Michal Vaskof04a52a2016-04-07 10:52:10 +02002078 }
Michal Vasko48a63ed2016-03-01 09:48:21 +01002079
Michal Vasko96164bf2016-01-21 15:41:58 +01002080 for (i = 0; i < ps->session_count; ++i) {
fanchanghu3d4e7212017-08-09 09:42:30 +08002081 cur_session = ps->sessions[i]->session;
roman506354a2024-04-11 09:37:22 +02002082 if ((cur_session->status == NC_STATUS_RUNNING) && (cur_session->ti_type == NC_TI_SSH) &&
Michal Vaskob83a3fa2021-05-26 09:53:42 +02002083 cur_session->ti.libssh.next) {
Michal Vasko96164bf2016-01-21 15:41:58 +01002084 /* an SSH session with more channels */
Michal Vaskoe4300a82017-05-24 10:35:42 +02002085 for (new_session = cur_session->ti.libssh.next;
2086 new_session != cur_session;
Michal Vasko96164bf2016-01-21 15:41:58 +01002087 new_session = new_session->ti.libssh.next) {
Michal Vaskob83a3fa2021-05-26 09:53:42 +02002088 if ((new_session->status == NC_STATUS_STARTING) && new_session->ti.libssh.channel &&
2089 (new_session->flags & NC_SESSION_SSH_SUBSYS_NETCONF)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01002090 /* we found our session */
2091 break;
2092 }
2093 }
Michal Vaskoe4300a82017-05-24 10:35:42 +02002094 if (new_session != cur_session) {
Michal Vasko96164bf2016-01-21 15:41:58 +01002095 break;
2096 }
Michal Vaskofb89d772016-01-08 12:25:35 +01002097
Michal Vasko96164bf2016-01-21 15:41:58 +01002098 new_session = NULL;
2099 }
2100 }
Michal Vaskofb89d772016-01-08 12:25:35 +01002101
Michal Vasko48a63ed2016-03-01 09:48:21 +01002102 /* UNLOCK */
Michal Vasko227f8ff2016-07-26 14:08:59 +02002103 nc_ps_unlock(ps, q_id, __func__);
Michal Vasko48a63ed2016-03-01 09:48:21 +01002104
Michal Vasko96164bf2016-01-21 15:41:58 +01002105 if (!new_session) {
Michal Vasko05532772021-06-03 12:12:38 +02002106 ERR(NULL, "No session with a NETCONF SSH channel ready was found.");
Michal Vasko71090fc2016-05-24 16:37:28 +02002107 return NC_MSG_ERROR;
Michal Vasko96164bf2016-01-21 15:41:58 +01002108 }
2109
2110 /* assign new SID atomically */
Michal Vasko5bd4a3f2021-06-17 16:40:10 +02002111 new_session->id = ATOMIC_INC_RELAXED(server_opts.new_session_id);
Michal Vaskofb89d772016-01-08 12:25:35 +01002112
Michal Vasko086311b2016-01-08 09:53:11 +01002113 /* NETCONF handshake */
Michal Vasko131120a2018-05-29 15:44:02 +02002114 msgtype = nc_handshake_io(new_session);
Michal Vasko71090fc2016-05-24 16:37:28 +02002115 if (msgtype != NC_MSG_HELLO) {
2116 return msgtype;
Michal Vasko086311b2016-01-08 09:53:11 +01002117 }
Michal Vasko48a63ed2016-03-01 09:48:21 +01002118
Michal Vaskod8a74192023-02-06 15:51:50 +01002119 nc_realtime_get(&ts_cur);
roman44efa322023-11-03 13:57:25 +01002120 new_session->opts.server.session_start = ts_cur;
Michal Vaskod8a74192023-02-06 15:51:50 +01002121 nc_timeouttime_get(&ts_cur, 0);
Michal Vasko9f6275e2017-10-05 13:50:05 +02002122 new_session->opts.server.last_rpc = ts_cur.tv_sec;
Michal Vasko086311b2016-01-08 09:53:11 +01002123 new_session->status = NC_STATUS_RUNNING;
Michal Vasko96164bf2016-01-21 15:41:58 +01002124 *session = new_session;
Michal Vasko086311b2016-01-08 09:53:11 +01002125
Michal Vasko71090fc2016-05-24 16:37:28 +02002126 return msgtype;
Michal Vasko086311b2016-01-08 09:53:11 +01002127}