blob: 71f4ce2f78b2667a2489f1f4a0ccf3ac029310ce [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
287 /* check if the path format contains any tokens */
288 if (strstr(path_fmt, "%h") || strstr(path_fmt, "%U") || strstr(path_fmt, "%u") || strstr(path_fmt, "%%")) {
289 /* get pw */
290 pw = nc_getpw(0, username, &pw_buf, &buf, &buf_len);
291 if (!pw) {
292 ERR(NULL, "Unable to get passwd entry for user \"%s\".", username);
293 ret = 1;
294 goto cleanup;
295 }
296
297 /* convert UID to a string */
298 uid = nc_server_ssh_uid_to_str(pw->pw_uid);
299 if (!uid) {
300 ret = 1;
301 goto cleanup;
302 }
303 } else {
304 /* no tokens, just copy the path and return */
305 *out_path = strdup(path_fmt);
306 NC_CHECK_ERRMEM_RET(!*out_path, 1);
307 goto cleanup;
308 }
309
310 /* go over characters from format, copy them to path and interpret tokens correctly */
311 for (i = 0; path_fmt[i]; i++) {
312 if (have_percent) {
313 /* special token, need to convert it */
314 if (path_fmt[i] == '%') {
315 ret = nc_server_ssh_str_append('%', NULL, &size, &idx, &path);
316 } else if (path_fmt[i] == 'h') {
317 /* user home */
318 ret = nc_server_ssh_str_append(0, pw->pw_dir, &size, &idx, &path);
319 } else if (path_fmt[i] == 'u') {
320 /* username */
321 ret = nc_server_ssh_str_append(0, username, &size, &idx, &path);
322 } else if (path_fmt[i] == 'U') {
323 /* UID */
324 ret = nc_server_ssh_str_append(0, uid, &size, &idx, &path);
325 } else {
326 ERR(NULL, "Failed to parse system public keys path format \"%s\".", server_opts.authkey_path_fmt);
327 ret = 1;
328 }
329
330 have_percent = 0;
331 } else {
332 if (path_fmt[i] == '%') {
333 have_percent = 1;
334 } else {
335 /* ordinary character with no meaning */
336 ret = nc_server_ssh_str_append(path_fmt[i], NULL, &size, &idx, &path);
337 }
338 }
339
340 if (ret) {
341 free(path);
342 goto cleanup;
343 }
344 }
345
346 *out_path = path;
347cleanup:
348 free(uid);
349 free(buf);
350 return ret;
351}
352
roman1ea193e2024-05-22 14:16:41 +0200353/**
354 * @brief Read public keys from the authorized keys file.
355 *
356 * @param[in] path Path to the authorized keys file.
357 * @param[out] pubkeys Public keys.
358 * @param[out] pubkey_count Public key count.
359 * @return 0 on success, 1 on error.
360 */
romana9ec3362023-12-21 10:59:57 +0100361static int
362nc_server_ssh_read_authorized_keys_file(const char *path, struct nc_public_key **pubkeys, uint16_t *pubkey_count)
363{
roman1ea193e2024-05-22 14:16:41 +0200364 int ret = 0, rc, line_num = 0;
romana9ec3362023-12-21 10:59:57 +0100365 FILE *f = NULL;
366 char *line = NULL, *ptr, *ptr2;
367 size_t n;
368 enum ssh_keytypes_e ktype;
369
370 NC_CHECK_ARG_RET(NULL, path, pubkeys, 1);
371
372 *pubkeys = NULL;
373 *pubkey_count = 0;
374
375 f = fopen(path, "r");
376 if (!f) {
377 ERR(NULL, "Unable to open \"%s\" (%s).", path, strerror(errno));
378 ret = 1;
379 goto cleanup;
380 }
381
382 while (getline(&line, &n, f) > -1) {
383 ++line_num;
384 if ((line[0] == '#') || (line[0] == '\n')) {
385 /* comment or empty line */
386 continue;
387 }
388
389 /* separate key type */
390 ptr = line;
391 for (ptr2 = ptr; ptr2[0] && !isspace(ptr2[0]); ptr2++) {}
392 if (!ptr2[0]) {
393 ERR(NULL, "Invalid format of authorized keys file \"%s\" on line %d.", path, line_num);
394 ret = 1;
395 goto cleanup;
396 }
397 ptr2[0] = '\0';
398
399 /* detect key type */
400 ktype = ssh_key_type_from_name(ptr);
401 if ((ktype != SSH_KEYTYPE_RSA) && (ktype != SSH_KEYTYPE_ECDSA_P256) && (ktype != SSH_KEYTYPE_ECDSA_P384) &&
402 (ktype != SSH_KEYTYPE_ECDSA_P521) && (ktype != SSH_KEYTYPE_ED25519)) {
403 WRN(NULL, "Unsupported key type \"%s\" in authorized keys file \"%s\" on line %d.", ptr, path, line_num);
404 continue;
405 }
406
407 /* get key data */
408 ptr = ptr2 + 1;
409 for (ptr2 = ptr; ptr2[0] && !isspace(ptr2[0]); ptr2++) {}
410 ptr2[0] = '\0';
411
412 /* add the key */
413 *pubkeys = nc_realloc(*pubkeys, (*pubkey_count + 1) * sizeof **pubkeys);
414 NC_CHECK_ERRMEM_GOTO(!(*pubkeys), ret = 1, cleanup);
roman1ea193e2024-05-22 14:16:41 +0200415 rc = asprintf(&(*pubkeys)[*pubkey_count].name, "authorized_key_%" PRIu16, *pubkey_count);
416 NC_CHECK_ERRMEM_GOTO(rc == -1, (*pubkeys)[*pubkey_count].name = NULL; ret = 1, cleanup);
romana9ec3362023-12-21 10:59:57 +0100417 (*pubkeys)[*pubkey_count].type = NC_PUBKEY_FORMAT_SSH;
418 (*pubkeys)[*pubkey_count].data = strdup(ptr);
419 NC_CHECK_ERRMEM_GOTO(!(*pubkeys)[*pubkey_count].data, ret = 1, cleanup);
420 (*pubkey_count)++;
421 }
422
423 /* ok */
424 ret = 0;
425cleanup:
426 if (f) {
427 fclose(f);
428 }
429 free(line);
430 return ret;
431}
432
roman1ea193e2024-05-22 14:16:41 +0200433/**
434 * @brief Get user's public keys from the system.
435 *
436 * @param[in] username Username.
437 * @param[out] pubkeys User's public keys.
438 * @param[out] pubkey_count Public key count.
439 * @return 0 on success, non-zero on error.
440 */
romana9ec3362023-12-21 10:59:57 +0100441static int
442nc_server_ssh_get_system_keys(const char *username, struct nc_public_key **pubkeys, uint16_t *pubkey_count)
443{
444 int ret = 0;
445 char *path = NULL;
446
447 /* convert the path format to get the actual path */
448 ret = nc_server_ssh_get_system_keys_path(username, &path);
449 if (ret) {
450 ERR(NULL, "Getting system keys path failed.");
451 goto cleanup;
452 }
453
454 /* get the keys */
455 ret = nc_server_ssh_read_authorized_keys_file(path, pubkeys, pubkey_count);
456 if (ret) {
457 ERR(NULL, "Reading system keys failed.");
458 goto cleanup;
459 }
460
461cleanup:
462 free(path);
463 return ret;
464}
465
Michal Vaskof3c41e32022-09-09 11:22:21 +0200466/**
467 * @brief Compare hashed password with a cleartext password for a match.
468 *
469 * @param[in] pass_hash Hashed password.
470 * @param[in] pass_clear Cleartext password.
471 * @return 0 on match.
472 * @return non-zero if not a match.
473 */
Michal Vasko086311b2016-01-08 09:53:11 +0100474static int
roman814f5112023-10-19 15:51:16 +0200475auth_password_compare_pwd(const char *stored_pw, const char *received_pw)
Michal Vasko086311b2016-01-08 09:53:11 +0100476{
roman814f5112023-10-19 15:51:16 +0200477 char *received_pw_hash = NULL;
roman8b1a6c32023-10-26 13:35:22 +0200478 struct crypt_data cdata = {0};
Michal Vasko086311b2016-01-08 09:53:11 +0100479
roman814f5112023-10-19 15:51:16 +0200480 if (!stored_pw[0]) {
481 if (!received_pw[0]) {
Michal Vasko05532772021-06-03 12:12:38 +0200482 WRN(NULL, "User authentication successful with an empty password!");
Michal Vasko086311b2016-01-08 09:53:11 +0100483 return 0;
484 } else {
485 /* the user did now know he does not need any password,
486 * (which should not be used) so deny authentication */
487 return 1;
488 }
489 }
490
roman814f5112023-10-19 15:51:16 +0200491 if (!strncmp(stored_pw, "$0$", 3)) {
492 /* cleartext password, simply compare the values */
493 return strcmp(stored_pw + 3, received_pw);
494 }
495
roman814f5112023-10-19 15:51:16 +0200496 received_pw_hash = crypt_r(received_pw, stored_pw, &cdata);
roman814f5112023-10-19 15:51:16 +0200497 if (!received_pw_hash) {
roman8b1a6c32023-10-26 13:35:22 +0200498 ERR(NULL, "Hashing the password failed (%s).", strerror(errno));
Andrew Langefeld158d6fd2018-06-11 18:51:44 -0500499 return 1;
500 }
501
roman814f5112023-10-19 15:51:16 +0200502 return strcmp(received_pw_hash, stored_pw);
Michal Vasko086311b2016-01-08 09:53:11 +0100503}
504
romanf578cd52023-10-19 09:47:40 +0200505static int
506nc_sshcb_auth_password(struct nc_session *session, struct nc_auth_client *auth_client, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +0100507{
Michal Vaskoebba7602018-03-23 13:14:08 +0100508 int auth_ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +0100509
roman4f9e4422024-03-21 10:58:41 +0100510 if (!auth_client->password) {
511 VRB(session, "User \"%s\" does not have password method configured, but a request was received.", auth_client->username);
512 } else {
513 auth_ret = auth_password_compare_pwd(auth_client->password, ssh_message_auth_password(msg));
514 }
Michal Vasko086311b2016-01-08 09:53:11 +0100515
romanf578cd52023-10-19 09:47:40 +0200516 if (auth_ret) {
Michal Vaskoebba7602018-03-23 13:14:08 +0100517 ++session->opts.server.ssh_auth_attempts;
Michal Vasko05532772021-06-03 12:12:38 +0200518 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", session->username,
519 session->opts.server.ssh_auth_attempts);
Michal Vaskoebba7602018-03-23 13:14:08 +0100520 ssh_message_reply_default(msg);
521 }
romanf578cd52023-10-19 09:47:40 +0200522
523 return auth_ret;
Michal Vasko086311b2016-01-08 09:53:11 +0100524}
525
romane5675b12024-03-05 14:26:23 +0100526API int
527nc_server_ssh_kbdint_get_nanswers(const struct nc_session *session, ssh_session libssh_session)
romanc6518422023-11-30 16:39:00 +0100528{
529 int ret = 0;
530 struct timespec ts_timeout = {0};
roman56c85c02023-12-07 13:09:28 +0100531 ssh_message reply = NULL;
romane5675b12024-03-05 14:26:23 +0100532 uint16_t auth_timeout = *((uint16_t *)session->data);
533
534 NC_CHECK_ARG_RET(NULL, session, libssh_session, -1);
romanc6518422023-11-30 16:39:00 +0100535
536 if (auth_timeout) {
537 nc_timeouttime_get(&ts_timeout, auth_timeout * 1000);
538 }
539
540 /* wait for answers from the client */
541 do {
542 if (!nc_session_is_connected(session)) {
543 ERR(NULL, "SSH communication socket unexpectedly closed.");
544 ret = -1;
545 goto cleanup;
546 }
547
548 reply = ssh_message_get(libssh_session);
549 if (reply) {
550 break;
551 }
552
553 usleep(NC_TIMEOUT_STEP);
554 } while (auth_timeout && (nc_timeouttime_cur_diff(&ts_timeout) >= 1));
555 if (!reply) {
556 ERR(NULL, "Authentication timeout.");
557 ret = -1;
558 goto cleanup;
559 }
560
561 ret = ssh_userauth_kbdint_getnanswers(libssh_session);
562
563cleanup:
564 ssh_message_free(reply);
565 return ret;
566}
567
Michal Vasko0d81c572022-09-26 10:39:31 +0200568#ifdef HAVE_LIBPAM
569
roman41a11e42022-06-22 09:27:08 +0200570/**
571 * @brief PAM conversation function, which serves as a callback for exchanging messages between the client and a PAM module.
572 *
573 * @param[in] n_messages Number of messages.
574 * @param[in] msg PAM module's messages.
575 * @param[out] resp User responses.
576 * @param[in] appdata_ptr Callback's data.
roman808f3f62023-11-23 16:01:04 +0100577 * @return PAM_SUCCESS on success, PAM_BUF_ERR on memory allocation error, PAM_CONV_ERR otherwise.
roman41a11e42022-06-22 09:27:08 +0200578 */
579static int
580nc_pam_conv_clb(int n_messages, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr)
581{
582 int i, j, t, r = PAM_SUCCESS, n_answers, n_requests = n_messages;
583 const char **prompts = NULL;
584 char *echo = NULL;
585 const char *name = "Keyboard-Interactive Authentication";
586 const char *instruction = "Please enter your authentication token";
587 ssh_message reply = NULL;
588 struct nc_pam_thread_arg *clb_data = appdata_ptr;
589 ssh_session libssh_session;
roman41a11e42022-06-22 09:27:08 +0200590
591 libssh_session = clb_data->session->ti.libssh.session;
roman41a11e42022-06-22 09:27:08 +0200592
593 /* PAM_MAX_NUM_MSG == 32 by default */
594 if ((n_messages <= 0) || (n_messages >= PAM_MAX_NUM_MSG)) {
romanc6518422023-11-30 16:39:00 +0100595 ERR(clb_data->session, "Bad number of PAM messages (#%d).", n_messages);
roman41a11e42022-06-22 09:27:08 +0200596 r = PAM_CONV_ERR;
597 goto cleanup;
598 }
599
600 /* only accepting these 4 types of messages */
601 for (i = 0; i < n_messages; i++) {
602 t = msg[i]->msg_style;
603 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 +0100604 ERR(clb_data->session, "PAM conversation callback received an unexpected type of message.");
roman41a11e42022-06-22 09:27:08 +0200605 r = PAM_CONV_ERR;
606 goto cleanup;
607 }
608 }
609
610 /* display messages with errors and/or some information and count the amount of actual authentication challenges */
611 for (i = 0; i < n_messages; i++) {
612 if (msg[i]->msg_style == PAM_TEXT_INFO) {
romanc6518422023-11-30 16:39:00 +0100613 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 +0200614 n_requests--;
615 }
616 if (msg[i]->msg_style == PAM_ERROR_MSG) {
romanc6518422023-11-30 16:39:00 +0100617 ERR(clb_data->session, "PAM conversation callback received an error message (%s).", msg[i]->msg);
roman41a11e42022-06-22 09:27:08 +0200618 r = PAM_CONV_ERR;
619 goto cleanup;
620 }
621 }
622
623 /* there are no requests left for the user, only messages with some information for the client were sent */
624 if (n_requests <= 0) {
625 r = PAM_SUCCESS;
626 goto cleanup;
627 }
628
629 /* it is the PAM module's responsibility to release both, this array and the responses themselves */
630 *resp = calloc(n_requests, sizeof **resp);
631 prompts = calloc(n_requests, sizeof *prompts);
632 echo = calloc(n_requests, sizeof *echo);
roman3a95bb22023-10-26 11:07:17 +0200633 NC_CHECK_ERRMEM_GOTO(!(*resp) || !prompts || !echo, r = PAM_BUF_ERR, cleanup);
roman41a11e42022-06-22 09:27:08 +0200634
635 /* set the prompts for the user */
636 j = 0;
637 for (i = 0; i < n_messages; i++) {
638 if ((msg[i]->msg_style == PAM_PROMPT_ECHO_ON) || (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF)) {
639 prompts[j++] = msg[i]->msg;
640 }
641 }
642
643 /* iterate over all the messages and adjust the echo array accordingly */
644 j = 0;
645 for (i = 0; i < n_messages; i++) {
646 if (msg[i]->msg_style == PAM_PROMPT_ECHO_ON) {
647 echo[j++] = 1;
648 }
649 if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF) {
650 /* no need to set to 0 because of calloc */
651 j++;
652 }
653 }
654
655 /* print all the keyboard-interactive challenges to the user */
656 r = ssh_message_auth_interactive_request(clb_data->msg, name, instruction, n_requests, prompts, echo);
657 if (r != SSH_OK) {
romanc6518422023-11-30 16:39:00 +0100658 ERR(clb_data->session, "Failed to send an authentication request.");
roman41a11e42022-06-22 09:27:08 +0200659 r = PAM_CONV_ERR;
660 goto cleanup;
661 }
662
romane5675b12024-03-05 14:26:23 +0100663 n_answers = nc_server_ssh_kbdint_get_nanswers(clb_data->session, libssh_session);
romanc6518422023-11-30 16:39:00 +0100664 if (n_answers < 0) {
665 /* timeout or dc */
roman41a11e42022-06-22 09:27:08 +0200666 r = PAM_CONV_ERR;
667 goto cleanup;
romanc6518422023-11-30 16:39:00 +0100668 } else if (n_answers != n_requests) {
669 /* check if the number of answers and requests matches */
670 ERR(clb_data->session, "Expected %d response(s), got %d.", n_requests, n_answers);
roman41a11e42022-06-22 09:27:08 +0200671 r = PAM_CONV_ERR;
672 goto cleanup;
673 }
674
675 /* give the replies to a PAM module */
676 for (i = 0; i < n_answers; i++) {
677 (*resp)[i].resp = strdup(ssh_userauth_kbdint_getanswer(libssh_session, i));
678 /* it should be the caller's responsibility to free this, however if mem alloc fails,
679 * it is safer to free the responses here and set them to NULL */
680 if ((*resp)[i].resp == NULL) {
681 for (j = 0; j < i; j++) {
682 free((*resp)[j].resp);
683 (*resp)[j].resp = NULL;
684 }
685 ERRMEM;
686 r = PAM_BUF_ERR;
687 goto cleanup;
688 }
689 }
690
691cleanup:
692 ssh_message_free(reply);
693 free(prompts);
694 free(echo);
695 return r;
696}
697
698/**
699 * @brief Handles authentication via Linux PAM.
700 *
701 * @param[in] session NETCONF session.
702 * @param[in] ssh_msg SSH message with a keyboard-interactive authentication request.
703 * @return PAM_SUCCESS on success;
704 * @return PAM error otherwise.
705 */
706static int
romane5675b12024-03-05 14:26:23 +0100707nc_pam_auth(struct nc_session *session, struct nc_auth_client *client, ssh_message ssh_msg)
roman41a11e42022-06-22 09:27:08 +0200708{
709 pam_handle_t *pam_h = NULL;
710 int ret;
711 struct nc_pam_thread_arg clb_data;
712 struct pam_conv conv;
713
714 /* structure holding callback's data */
715 clb_data.msg = ssh_msg;
716 clb_data.session = session;
717
718 /* PAM conversation structure holding the callback and it's data */
719 conv.conv = nc_pam_conv_clb;
720 conv.appdata_ptr = &clb_data;
721
roman808f3f62023-11-23 16:01:04 +0100722 if (!server_opts.pam_config_name) {
romanc6518422023-11-30 16:39:00 +0100723 ERR(session, "PAM configuration filename not set.");
romanf578cd52023-10-19 09:47:40 +0200724 ret = 1;
725 goto cleanup;
726 }
727
roman41a11e42022-06-22 09:27:08 +0200728 /* initialize PAM and see if the given configuration file exists */
roman808f3f62023-11-23 16:01:04 +0100729 ret = pam_start(server_opts.pam_config_name, client->username, &conv, &pam_h);
roman41a11e42022-06-22 09:27:08 +0200730 if (ret != PAM_SUCCESS) {
romanc6518422023-11-30 16:39:00 +0100731 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200732 goto cleanup;
733 }
734
735 /* authentication based on the modules listed in the configuration file */
736 ret = pam_authenticate(pam_h, 0);
737 if (ret != PAM_SUCCESS) {
738 if (ret == PAM_ABORT) {
romanc6518422023-11-30 16:39:00 +0100739 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200740 goto cleanup;
741 } else {
romanc6518422023-11-30 16:39:00 +0100742 VRB(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200743 goto cleanup;
744 }
745 }
746
747 /* correct token entered, check other requirements(the time of the day, expired token, ...) */
748 ret = pam_acct_mgmt(pam_h, 0);
749 if ((ret != PAM_SUCCESS) && (ret != PAM_NEW_AUTHTOK_REQD)) {
romanc6518422023-11-30 16:39:00 +0100750 VRB(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200751 goto cleanup;
752 }
753
754 /* if a token has expired a new one will be generated */
755 if (ret == PAM_NEW_AUTHTOK_REQD) {
romanc6518422023-11-30 16:39:00 +0100756 VRB(session, "PAM warning occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200757 ret = pam_chauthtok(pam_h, PAM_CHANGE_EXPIRED_AUTHTOK);
758 if (ret == PAM_SUCCESS) {
romanc6518422023-11-30 16:39:00 +0100759 VRB(session, "The authentication token of user \"%s\" updated successfully.", client->username);
roman41a11e42022-06-22 09:27:08 +0200760 } else {
romanc6518422023-11-30 16:39:00 +0100761 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200762 goto cleanup;
763 }
764 }
765
766cleanup:
767 /* destroy the PAM context */
roman6dfdc0d2023-11-09 13:25:27 +0100768 if (pam_h && (pam_end(pam_h, ret) != PAM_SUCCESS)) {
romancab602e2023-11-24 11:30:32 +0100769 ERR(NULL, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200770 }
771 return ret;
772}
773
romanc6518422023-11-30 16:39:00 +0100774#elif defined (HAVE_SHADOW)
775
776static struct passwd *
777nc_server_ssh_getpwnam(const char *username, struct passwd *pwd_buf, char **buf, size_t *buf_size)
778{
779 struct passwd *pwd = NULL;
780 char *mem;
781 int r = 0;
782
783 do {
784 r = getpwnam_r(username, pwd_buf, *buf, *buf_size, &pwd);
785 if (pwd) {
786 /* entry found */
787 break;
788 }
789
790 if (r == ERANGE) {
791 /* small buffer, enlarge */
792 *buf_size <<= 2;
793 mem = realloc(*buf, *buf_size);
794 if (!mem) {
795 ERRMEM;
796 return NULL;
797 }
798 *buf = mem;
799 }
800 } while (r == ERANGE);
801
802 return pwd;
803}
804
805static struct spwd *
806nc_server_ssh_getspnam(const char *username, struct spwd *spwd_buf, char **buf, size_t *buf_size)
807{
808 struct spwd *spwd = NULL;
809 char *mem;
810 int r = 0;
811
812 do {
813# ifndef __QNXNTO__
814 r = getspnam_r(username, spwd_buf, *buf, *buf_size, &spwd);
815# else
816 spwd = getspnam_r(username, spwd_buf, *buf, *buf_size);
817# endif
818 if (spwd) {
819 /* entry found */
820 break;
821 }
822
823 if (r == ERANGE) {
824 /* small buffer, enlarge */
825 *buf_size <<= 2;
826 mem = realloc(*buf, *buf_size);
827 if (!mem) {
828 ERRMEM;
829 return NULL;
830 }
831 *buf = mem;
832 }
833 } while (r == ERANGE);
834
835 return spwd;
836}
837
838static char *
839nc_server_ssh_get_pwd_hash(const char *username)
840{
841 struct passwd *pwd, pwd_buf;
842 struct spwd *spwd, spwd_buf;
843 char *pass_hash = NULL, *buf = NULL;
844 size_t buf_size = 256;
845
846 buf = malloc(buf_size);
847 NC_CHECK_ERRMEM_GOTO(!buf, , error);
848
849 pwd = nc_server_ssh_getpwnam(username, &pwd_buf, &buf, &buf_size);
850 if (!pwd) {
851 VRB(NULL, "User \"%s\" not found locally.", username);
852 goto error;
853 }
854
855 if (!strcmp(pwd->pw_passwd, "x")) {
856 spwd = nc_server_ssh_getspnam(username, &spwd_buf, &buf, &buf_size);
857 if (!spwd) {
858 VRB(NULL, "Failed to retrieve the shadow entry for \"%s\".", username);
859 goto error;
860 } else if ((spwd->sp_expire > -1) && (spwd->sp_expire <= (time(NULL) / (60 * 60 * 24)))) {
861 WRN(NULL, "User \"%s\" account has expired.", username);
862 goto error;
863 }
864
865 pass_hash = spwd->sp_pwdp;
866 } else {
867 pass_hash = pwd->pw_passwd;
868 }
869
870 if (!pass_hash) {
871 ERR(NULL, "No password could be retrieved for \"%s\".", username);
872 goto error;
873 }
874
875 /* check the hash structure for special meaning */
876 if (!strcmp(pass_hash, "*") || !strcmp(pass_hash, "!")) {
877 VRB(NULL, "User \"%s\" is not allowed to authenticate using a password.", username);
878 goto error;
879 }
880 if (!strcmp(pass_hash, "*NP*")) {
881 VRB(NULL, "Retrieving password for \"%s\" from a NIS+ server not supported.", username);
882 goto error;
883 }
884
885 pass_hash = strdup(pass_hash);
886 free(buf);
887 return pass_hash;
888
889error:
890 free(buf);
891 return NULL;
892}
893
894/**
895 * @brief Authenticate using locally stored credentials.
896 *
897 * @param[in] session Session to authenticate on.
898 * @param[in] client Client to authenticate.
romanc6518422023-11-30 16:39:00 +0100899 * @param[in] msg SSH message that originally requested kbdint authentication.
900 *
901 * @return 0 on success, non-zero otherwise.
902 */
903static int
romane5675b12024-03-05 14:26:23 +0100904nc_server_ssh_system_auth(struct nc_session *session, struct nc_auth_client *client, ssh_message msg)
romanc6518422023-11-30 16:39:00 +0100905{
906 int ret = 0, n_answers;
907 const char *name = "Keyboard-Interactive Authentication";
908 const char *instruction = "Please enter your authentication token";
909 char *prompt = NULL, *local_pw = NULL, *received_pw = NULL;
910 char echo[] = {0};
911
912 /* try to get the client's locally stored pw hash */
913 local_pw = nc_server_ssh_get_pwd_hash(client->username);
914 if (!local_pw) {
915 ERR(session, "Unable to get %s's credentials.", client->username);
916 ret = 1;
917 goto cleanup;
918 }
919
920 ret = asprintf(&prompt, "%s's password:", client->username);
921 NC_CHECK_ERRMEM_GOTO(ret == -1, prompt = NULL; ret = 1, cleanup);
922
923 /* send the password prompt to the client */
924 ret = ssh_message_auth_interactive_request(msg, name, instruction, 1, (const char **) &prompt, echo);
925 if (ret) {
926 ERR(session, "Failed to send an authentication request to client \"%s\".", client->username);
927 goto cleanup;
928 }
929
930 /* get the reply */
romane5675b12024-03-05 14:26:23 +0100931 n_answers = nc_server_ssh_kbdint_get_nanswers(session, session->ti.libssh.session);
romanc6518422023-11-30 16:39:00 +0100932 if (n_answers < 0) {
933 /* timeout or dc */
934 ret = 1;
935 goto cleanup;
936 } else if (n_answers != 1) {
937 /* only expecting a single answer */
938 ERR(session, "Unexpected amount of answers in system auth. Expected 1, got \"%d\".", n_answers);
939 ret = 1;
940 goto cleanup;
941 }
942 received_pw = strdup(ssh_userauth_kbdint_getanswer(session->ti.libssh.session, 0));
943 NC_CHECK_ERRMEM_GOTO(!received_pw, ret = 1, cleanup);
944
945 /* cmp the pw hashes */
946 ret = auth_password_compare_pwd(local_pw, received_pw);
947
948cleanup:
949 free(local_pw);
950 free(received_pw);
951 free(prompt);
952 return ret;
953}
954
955#endif
Michal Vasko0d81c572022-09-26 10:39:31 +0200956
romanf578cd52023-10-19 09:47:40 +0200957static int
romane5675b12024-03-05 14:26:23 +0100958nc_sshcb_auth_kbdint(struct nc_session *session, struct nc_auth_client *client, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +0100959{
bhart3bc2f582018-06-05 12:40:32 -0500960 int auth_ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +0100961
roman4f9e4422024-03-21 10:58:41 +0100962 if (!client->kb_int_enabled) {
963 VRB(session, "User \"%s\" does not have Keyboard-interactive method configured, but a request was received.", client->username);
964 } else if (server_opts.interactive_auth_clb) {
romanf578cd52023-10-19 09:47:40 +0200965 auth_ret = server_opts.interactive_auth_clb(session, session->ti.libssh.session, msg, server_opts.interactive_auth_data);
Michal Vasko0d81c572022-09-26 10:39:31 +0200966 } else {
967#ifdef HAVE_LIBPAM
romanc6518422023-11-30 16:39:00 +0100968 /* authenticate using PAM */
romane5675b12024-03-05 14:26:23 +0100969 if (!nc_pam_auth(session, client, msg)) {
romanc6518422023-11-30 16:39:00 +0100970 auth_ret = 0;
971 }
972#elif defined (HAVE_SHADOW)
973 /* authenticate using locally configured users */
romane5675b12024-03-05 14:26:23 +0100974 if (!nc_server_ssh_system_auth(session, client, msg)) {
Michal Vasko0d81c572022-09-26 10:39:31 +0200975 auth_ret = 0;
976 }
977#else
romanc6518422023-11-30 16:39:00 +0100978 ERR(NULL, "Keyboard-interactive method not supported.");
Michal Vasko0d81c572022-09-26 10:39:31 +0200979#endif
bhart1bb7cdb2018-07-02 15:03:30 -0500980 }
981
982 /* Authenticate message based on outcome */
romanf578cd52023-10-19 09:47:40 +0200983 if (auth_ret) {
bhart1bb7cdb2018-07-02 15:03:30 -0500984 ++session->opts.server.ssh_auth_attempts;
romanc6518422023-11-30 16:39:00 +0100985 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", client->username,
Michal Vasko05532772021-06-03 12:12:38 +0200986 session->opts.server.ssh_auth_attempts);
bhart1bb7cdb2018-07-02 15:03:30 -0500987 ssh_message_reply_default(msg);
Michal Vasko086311b2016-01-08 09:53:11 +0100988 }
romanf578cd52023-10-19 09:47:40 +0200989
990 return auth_ret;
991}
992
roman808f3f62023-11-23 16:01:04 +0100993API void
994nc_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),
995 void *user_data, void (*free_user_data)(void *user_data))
996{
romanc6518422023-11-30 16:39:00 +0100997 /* CONFIG LOCK */
998 pthread_rwlock_wrlock(&server_opts.config_lock);
999
roman808f3f62023-11-23 16:01:04 +01001000 server_opts.interactive_auth_clb = interactive_auth_clb;
1001 server_opts.interactive_auth_data = user_data;
1002 server_opts.interactive_auth_data_free = free_user_data;
romanc6518422023-11-30 16:39:00 +01001003
1004 /* CONFIG UNLOCK */
1005 pthread_rwlock_unlock(&server_opts.config_lock);
roman808f3f62023-11-23 16:01:04 +01001006}
1007
1008#ifdef HAVE_LIBPAM
1009
1010API int
1011nc_server_ssh_set_pam_conf_filename(const char *filename)
1012{
romanc6518422023-11-30 16:39:00 +01001013 int ret = 0;
1014
roman808f3f62023-11-23 16:01:04 +01001015 NC_CHECK_ARG_RET(NULL, filename, 1);
1016
romanc6518422023-11-30 16:39:00 +01001017 /* CONFIG LOCK */
1018 pthread_rwlock_wrlock(&server_opts.config_lock);
1019
roman808f3f62023-11-23 16:01:04 +01001020 free(server_opts.pam_config_name);
1021 server_opts.pam_config_name = strdup(filename);
romanc6518422023-11-30 16:39:00 +01001022 if (!server_opts.pam_config_name) {
1023 ERRMEM;
1024 ret = 1;
1025 }
1026
1027 /* CONFIG UNLOCK */
1028 pthread_rwlock_unlock(&server_opts.config_lock);
1029 return ret;
roman808f3f62023-11-23 16:01:04 +01001030}
1031
1032#else
1033
1034API int
1035nc_server_ssh_set_pam_conf_filename(const char *filename)
1036{
romanf69fbcf2023-12-14 09:24:34 +01001037 /* LibPAM not supported */
roman808f3f62023-11-23 16:01:04 +01001038 (void) filename;
roman808f3f62023-11-23 16:01:04 +01001039 return 1;
1040}
1041
1042#endif /* HAVE_LIBPAM */
1043
romana9ec3362023-12-21 10:59:57 +01001044API int
1045nc_server_ssh_set_authkey_path_format(const char *path)
1046{
1047 int ret = 0;
1048
1049 NC_CHECK_ARG_RET(NULL, path, 1);
1050
1051 /* CONFIG LOCK */
1052 pthread_rwlock_wrlock(&server_opts.config_lock);
1053
1054 free(server_opts.authkey_path_fmt);
1055 server_opts.authkey_path_fmt = strdup(path);
1056 if (!server_opts.authkey_path_fmt) {
1057 ERRMEM;
1058 ret = 1;
1059 }
1060
1061 /* CONFIG UNLOCK */
1062 pthread_rwlock_unlock(&server_opts.config_lock);
1063 return ret;
1064}
1065
roman1ea193e2024-05-22 14:16:41 +02001066/**
1067 * @brief Get the public key type from binary data.
1068 *
1069 * @param[in] buffer Binary key data, which is in the form of: 4 bytes = data length, then data of data length.
1070 * Data is in network byte order. The key has to be in the SSH2 format.
1071 * @param[out] len Length of the key type.
1072 * @return Pointer to where the key type starts in the buffer and is of the length @p len .
romanf578cd52023-10-19 09:47:40 +02001073 */
1074static const char *
romance435112024-04-23 15:12:09 +02001075nc_server_ssh_get_pubkey_type(const unsigned char *buffer, uint32_t *len)
romanf578cd52023-10-19 09:47:40 +02001076{
1077 uint32_t type_len;
1078
1079 /* copy the 4 bytes */
1080 memcpy(&type_len, buffer, sizeof type_len);
1081 /* type_len now stores the length of the key type */
1082 type_len = ntohl(type_len);
1083 *len = type_len;
1084
1085 /* move 4 bytes in the buffer, this is where the type should be */
1086 buffer += sizeof type_len;
romance435112024-04-23 15:12:09 +02001087 return (const char *)buffer;
romanf578cd52023-10-19 09:47:40 +02001088}
1089
1090/**
1091 * @brief Create ssh key from base64 pubkey data.
1092 *
1093 * @param[in] base64 base64 encoded public key.
1094 * @param[out] key created ssh key.
1095 * @return 0 on success, 1 otherwise.
1096 */
1097static int
1098nc_server_ssh_create_ssh_pubkey(const char *base64, ssh_key *key)
1099{
1100 int ret = 0;
romance435112024-04-23 15:12:09 +02001101 unsigned char *bin = NULL;
romanf578cd52023-10-19 09:47:40 +02001102 const char *pub_type = NULL;
1103 uint32_t pub_type_len = 0;
1104
roman6dfdc0d2023-11-09 13:25:27 +01001105 NC_CHECK_ARG_RET(NULL, base64, key, 1);
romanf578cd52023-10-19 09:47:40 +02001106
1107 *key = NULL;
1108
1109 /* convert base64 to binary */
roman83289292024-04-05 12:33:24 +02001110 if (nc_base64_decode_wrap(base64, &bin) == -1) {
romanf578cd52023-10-19 09:47:40 +02001111 ret = 1;
1112 goto cleanup;
1113 }
1114
1115 /* get the key type and try to import it if possible */
1116 pub_type = nc_server_ssh_get_pubkey_type(bin, &pub_type_len);
1117 if (!pub_type) {
1118 ret = 1;
1119 goto cleanup;
1120 } else if (!strncmp(pub_type, "ssh-dss", pub_type_len)) {
1121 ERR(NULL, "DSA keys are not supported.");
1122 ret = 1;
1123 goto cleanup;
1124 } else if (!strncmp(pub_type, "ssh-rsa", pub_type_len)) {
1125 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_RSA, key);
1126 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp256", pub_type_len)) {
1127 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P256, key);
1128 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp384", pub_type_len)) {
1129 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P384, key);
1130 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp521", pub_type_len)) {
1131 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P521, key);
1132 } else if (!strncmp(pub_type, "ssh-ed25519", pub_type_len)) {
1133 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ED25519, key);
1134 } else {
1135 ERR(NULL, "Public key type not recognised.");
1136 ret = 1;
1137 goto cleanup;
1138 }
1139
1140cleanup:
1141 if (ret != SSH_OK) {
1142 ERR(NULL, "Error importing public key.");
1143 }
1144 free(bin);
1145 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +01001146}
1147
Michal Vaskof3c41e32022-09-09 11:22:21 +02001148/**
1149 * @brief Compare SSH key with configured authorized keys and return the username of the matching one, if any.
1150 *
1151 * @param[in] key Presented SSH key to compare.
1152 * @return Authorized key username, NULL if no match was found.
1153 */
romanf578cd52023-10-19 09:47:40 +02001154static int
1155auth_pubkey_compare_key(ssh_key key, struct nc_auth_client *auth_client)
Michal Vasko086311b2016-01-08 09:53:11 +01001156{
Michal Vaskoe2bfcd62024-03-28 07:58:49 +01001157 uint16_t i, pubkey_count = 0;
Michal Vasko3e9d1682017-02-24 09:50:15 +01001158 int ret = 0;
romanf578cd52023-10-19 09:47:40 +02001159 ssh_key new_key = NULL;
romana9ec3362023-12-21 10:59:57 +01001160 struct nc_public_key *pubkeys = NULL;
Michal Vasko086311b2016-01-08 09:53:11 +01001161
romanf578cd52023-10-19 09:47:40 +02001162 /* get the correct public key storage */
1163 if (auth_client->store == NC_STORE_LOCAL) {
1164 pubkeys = auth_client->pubkeys;
1165 pubkey_count = auth_client->pubkey_count;
romana9ec3362023-12-21 10:59:57 +01001166 } else if (auth_client->store == NC_STORE_TRUSTSTORE) {
romanf578cd52023-10-19 09:47:40 +02001167 ret = nc_server_ssh_ts_ref_get_keys(auth_client->ts_ref, &pubkeys, &pubkey_count);
1168 if (ret) {
1169 ERR(NULL, "Error getting \"%s\"'s public keys from the truststore.", auth_client->username);
romana9ec3362023-12-21 10:59:57 +01001170 goto cleanup;
Michal Vasko17dfda92016-12-01 14:06:16 +01001171 }
romana9ec3362023-12-21 10:59:57 +01001172 } else if (auth_client->store == NC_STORE_SYSTEM) {
1173 ret = nc_server_ssh_get_system_keys(auth_client->username, &pubkeys, &pubkey_count);
1174 if (ret) {
1175 ERR(NULL, "Failed to retrieve public keys of user \"%s\" from the system.", auth_client->username);
1176 goto cleanup;
1177 }
1178 } else {
1179 ERRINT;
1180 return 1;
romanf578cd52023-10-19 09:47:40 +02001181 }
Michal Vasko17dfda92016-12-01 14:06:16 +01001182
romanf578cd52023-10-19 09:47:40 +02001183 /* try to compare all of the client's keys with the key received in the SSH message */
1184 for (i = 0; i < pubkey_count; i++) {
1185 /* create the SSH key from the data */
1186 if (nc_server_ssh_create_ssh_pubkey(pubkeys[i].data, &new_key)) {
1187 ssh_key_free(new_key);
Michal Vasko086311b2016-01-08 09:53:11 +01001188 continue;
1189 }
1190
romanf578cd52023-10-19 09:47:40 +02001191 /* compare the keys */
1192 ret = ssh_key_cmp(key, new_key, SSH_KEY_CMP_PUBLIC);
1193 if (!ret) {
Michal Vasko086311b2016-01-08 09:53:11 +01001194 break;
romanf578cd52023-10-19 09:47:40 +02001195 } else {
1196 WRN(NULL, "User's \"%s\" public key doesn't match, trying another.", auth_client->username);
1197 ssh_key_free(new_key);
Michal Vasko086311b2016-01-08 09:53:11 +01001198 }
Michal Vasko086311b2016-01-08 09:53:11 +01001199 }
romanf578cd52023-10-19 09:47:40 +02001200 if (i == pubkey_count) {
1201 ret = 1;
romana9ec3362023-12-21 10:59:57 +01001202 goto cleanup;
Michal Vasko086311b2016-01-08 09:53:11 +01001203 }
1204
romana9ec3362023-12-21 10:59:57 +01001205cleanup:
romanf578cd52023-10-19 09:47:40 +02001206 if (!ret) {
1207 /* only free a key if everything was ok, it would have already been freed otherwise */
1208 ssh_key_free(new_key);
1209 }
Michal Vaskoa05c7b12017-01-30 14:33:08 +01001210
romana9ec3362023-12-21 10:59:57 +01001211 if ((auth_client->store == NC_STORE_SYSTEM) && pubkeys) {
1212 for (i = 0; i < pubkey_count; i++) {
1213 free(pubkeys[i].name);
1214 free(pubkeys[i].data);
1215 }
1216 free(pubkeys);
1217 }
romanf578cd52023-10-19 09:47:40 +02001218 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +01001219}
1220
1221static void
romanf578cd52023-10-19 09:47:40 +02001222nc_sshcb_auth_none(struct nc_session *session, struct nc_auth_client *auth_client, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +01001223{
roman808f3f62023-11-23 16:01:04 +01001224 if (auth_client->none_enabled && !auth_client->password && !auth_client->pubkey_count && !auth_client->kb_int_enabled) {
romanf578cd52023-10-19 09:47:40 +02001225 /* only authenticate the client if he supports none and no other method */
1226 session->flags |= NC_SESSION_SSH_AUTHENTICATED;
1227 VRB(session, "User \"%s\" authenticated.", session->username);
1228 ssh_message_auth_reply_success(msg, 0);
1229 }
1230
1231 ssh_message_reply_default(msg);
1232}
1233
1234static int
1235nc_sshcb_auth_pubkey(struct nc_session *session, struct nc_auth_client *auth_client, ssh_message msg)
1236{
1237 int signature_state, ret = 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001238
roman9130fc12023-11-03 13:56:23 +01001239 if (auth_pubkey_compare_key(ssh_message_auth_pubkey(msg), auth_client)) {
1240 VRB(session, "User \"%s\" tried to use an unknown (unauthorized) public key.", session->username);
1241 ret = 1;
1242 goto fail;
Michal Vaskobd13a932016-09-14 09:00:35 +02001243 }
Michal Vaskobd13a932016-09-14 09:00:35 +02001244
Michal Vasko086311b2016-01-08 09:53:11 +01001245 signature_state = ssh_message_auth_publickey_state(msg);
romanf578cd52023-10-19 09:47:40 +02001246 if (signature_state == SSH_PUBLICKEY_STATE_NONE) {
Michal Vaskobd13a932016-09-14 09:00:35 +02001247 /* accepting only the use of a public key */
1248 ssh_message_auth_reply_pk_ok_simple(msg);
romanf578cd52023-10-19 09:47:40 +02001249 ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001250 }
1251
romanf578cd52023-10-19 09:47:40 +02001252 return ret;
Michal Vaskobd13a932016-09-14 09:00:35 +02001253
1254fail:
Michal Vasko2e6defd2016-10-07 15:48:15 +02001255 ++session->opts.server.ssh_auth_attempts;
Michal Vasko05532772021-06-03 12:12:38 +02001256 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", session->username,
1257 session->opts.server.ssh_auth_attempts);
Michal Vasko086311b2016-01-08 09:53:11 +01001258 ssh_message_reply_default(msg);
romanf578cd52023-10-19 09:47:40 +02001259
1260 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +01001261}
1262
1263static int
Michal Vasko96164bf2016-01-21 15:41:58 +01001264nc_sshcb_channel_open(struct nc_session *session, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +01001265{
Michal Vasko96164bf2016-01-21 15:41:58 +01001266 ssh_channel chan;
1267
1268 /* first channel request */
1269 if (!session->ti.libssh.channel) {
1270 if (session->status != NC_STATUS_STARTING) {
Michal Vasko9e036d52016-01-08 10:49:26 +01001271 ERRINT;
Michal Vasko086311b2016-01-08 09:53:11 +01001272 return -1;
1273 }
Michal Vasko96164bf2016-01-21 15:41:58 +01001274 chan = ssh_message_channel_request_open_reply_accept(msg);
1275 if (!chan) {
Michal Vasko05532772021-06-03 12:12:38 +02001276 ERR(session, "Failed to create a new SSH channel.");
Michal Vasko96164bf2016-01-21 15:41:58 +01001277 return -1;
1278 }
1279 session->ti.libssh.channel = chan;
Michal Vasko086311b2016-01-08 09:53:11 +01001280
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001281 /* additional channel request */
Michal Vasko96164bf2016-01-21 15:41:58 +01001282 } else {
1283 chan = ssh_message_channel_request_open_reply_accept(msg);
1284 if (!chan) {
Michal Vasko05532772021-06-03 12:12:38 +02001285 ERR(session, "Session %u: failed to create a new SSH channel.", session->id);
Michal Vasko96164bf2016-01-21 15:41:58 +01001286 return -1;
1287 }
1288 /* channel was created and libssh stored it internally in the ssh_session structure, good enough */
Michal Vasko086311b2016-01-08 09:53:11 +01001289 }
1290
Michal Vasko086311b2016-01-08 09:53:11 +01001291 return 0;
1292}
1293
1294static int
1295nc_sshcb_channel_subsystem(struct nc_session *session, ssh_channel channel, const char *subsystem)
1296{
Michal Vasko96164bf2016-01-21 15:41:58 +01001297 struct nc_session *new_session;
Michal Vasko086311b2016-01-08 09:53:11 +01001298
Michal Vasko96164bf2016-01-21 15:41:58 +01001299 if (strcmp(subsystem, "netconf")) {
Michal Vasko05532772021-06-03 12:12:38 +02001300 WRN(session, "Received an unknown subsystem \"%s\" request.", subsystem);
Michal Vasko086311b2016-01-08 09:53:11 +01001301 return -1;
1302 }
1303
Michal Vasko96164bf2016-01-21 15:41:58 +01001304 if (session->ti.libssh.channel == channel) {
1305 /* first channel requested */
1306 if (session->ti.libssh.next || (session->status != NC_STATUS_STARTING)) {
1307 ERRINT;
1308 return -1;
Michal Vasko086311b2016-01-08 09:53:11 +01001309 }
Michal Vasko96164bf2016-01-21 15:41:58 +01001310 if (session->flags & NC_SESSION_SSH_SUBSYS_NETCONF) {
Michal Vasko05532772021-06-03 12:12:38 +02001311 ERR(session, "Subsystem \"netconf\" requested for the second time.");
Michal Vasko96164bf2016-01-21 15:41:58 +01001312 return -1;
1313 }
1314
1315 session->flags |= NC_SESSION_SSH_SUBSYS_NETCONF;
Michal Vasko086311b2016-01-08 09:53:11 +01001316 } else {
Michal Vasko96164bf2016-01-21 15:41:58 +01001317 /* additional channel subsystem request, new session is ready as far as SSH is concerned */
Michal Vasko131120a2018-05-29 15:44:02 +02001318 new_session = nc_new_session(NC_SERVER, 1);
roman3a95bb22023-10-26 11:07:17 +02001319 NC_CHECK_ERRMEM_RET(!new_session, -1);
Michal Vasko96164bf2016-01-21 15:41:58 +01001320
1321 /* insert the new session */
1322 if (!session->ti.libssh.next) {
1323 new_session->ti.libssh.next = session;
1324 } else {
1325 new_session->ti.libssh.next = session->ti.libssh.next;
1326 }
1327 session->ti.libssh.next = new_session;
1328
1329 new_session->status = NC_STATUS_STARTING;
roman506354a2024-04-11 09:37:22 +02001330 new_session->ti_type = NC_TI_SSH;
Michal Vasko131120a2018-05-29 15:44:02 +02001331 new_session->io_lock = session->io_lock;
Michal Vasko96164bf2016-01-21 15:41:58 +01001332 new_session->ti.libssh.channel = channel;
1333 new_session->ti.libssh.session = session->ti.libssh.session;
Michal Vasko93224072021-11-09 12:14:28 +01001334 new_session->username = strdup(session->username);
1335 new_session->host = strdup(session->host);
Michal Vasko96164bf2016-01-21 15:41:58 +01001336 new_session->port = session->port;
Michal Vasko93224072021-11-09 12:14:28 +01001337 new_session->ctx = (struct ly_ctx *)session->ctx;
Michal Vasko83d15322018-09-27 09:44:02 +02001338 new_session->flags = NC_SESSION_SSH_AUTHENTICATED | NC_SESSION_SSH_SUBSYS_NETCONF | NC_SESSION_SHAREDCTX;
Michal Vasko086311b2016-01-08 09:53:11 +01001339 }
1340
1341 return 0;
1342}
1343
Michal Vasko96164bf2016-01-21 15:41:58 +01001344int
romanf578cd52023-10-19 09:47:40 +02001345nc_session_ssh_msg(struct nc_session *session, struct nc_server_ssh_opts *opts, ssh_message msg, struct nc_auth_state *state)
Michal Vasko086311b2016-01-08 09:53:11 +01001346{
1347 const char *str_type, *str_subtype = NULL, *username;
romanf578cd52023-10-19 09:47:40 +02001348 int subtype, type, libssh_auth_methods = 0, ret = 0;
1349 uint16_t i;
1350 struct nc_auth_client *auth_client = NULL;
roman78df0fa2023-11-02 10:33:57 +01001351 struct nc_endpt *referenced_endpt;
Michal Vasko086311b2016-01-08 09:53:11 +01001352
1353 type = ssh_message_type(msg);
1354 subtype = ssh_message_subtype(msg);
1355
1356 switch (type) {
1357 case SSH_REQUEST_AUTH:
1358 str_type = "request-auth";
1359 switch (subtype) {
1360 case SSH_AUTH_METHOD_NONE:
1361 str_subtype = "none";
1362 break;
1363 case SSH_AUTH_METHOD_PASSWORD:
1364 str_subtype = "password";
1365 break;
1366 case SSH_AUTH_METHOD_PUBLICKEY:
1367 str_subtype = "publickey";
1368 break;
1369 case SSH_AUTH_METHOD_HOSTBASED:
1370 str_subtype = "hostbased";
1371 break;
1372 case SSH_AUTH_METHOD_INTERACTIVE:
1373 str_subtype = "interactive";
1374 break;
1375 case SSH_AUTH_METHOD_GSSAPI_MIC:
1376 str_subtype = "gssapi-mic";
1377 break;
1378 }
1379 break;
1380
1381 case SSH_REQUEST_CHANNEL_OPEN:
1382 str_type = "request-channel-open";
1383 switch (subtype) {
1384 case SSH_CHANNEL_SESSION:
1385 str_subtype = "session";
1386 break;
1387 case SSH_CHANNEL_DIRECT_TCPIP:
1388 str_subtype = "direct-tcpip";
1389 break;
1390 case SSH_CHANNEL_FORWARDED_TCPIP:
1391 str_subtype = "forwarded-tcpip";
1392 break;
1393 case (int)SSH_CHANNEL_X11:
1394 str_subtype = "channel-x11";
1395 break;
1396 case SSH_CHANNEL_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001397 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001398 default:
1399 str_subtype = "unknown";
1400 break;
1401 }
1402 break;
1403
1404 case SSH_REQUEST_CHANNEL:
1405 str_type = "request-channel";
1406 switch (subtype) {
1407 case SSH_CHANNEL_REQUEST_PTY:
1408 str_subtype = "pty";
1409 break;
1410 case SSH_CHANNEL_REQUEST_EXEC:
1411 str_subtype = "exec";
1412 break;
1413 case SSH_CHANNEL_REQUEST_SHELL:
1414 str_subtype = "shell";
1415 break;
1416 case SSH_CHANNEL_REQUEST_ENV:
1417 str_subtype = "env";
1418 break;
1419 case SSH_CHANNEL_REQUEST_SUBSYSTEM:
1420 str_subtype = "subsystem";
1421 break;
1422 case SSH_CHANNEL_REQUEST_WINDOW_CHANGE:
1423 str_subtype = "window-change";
1424 break;
1425 case SSH_CHANNEL_REQUEST_X11:
1426 str_subtype = "x11";
1427 break;
1428 case SSH_CHANNEL_REQUEST_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001429 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001430 default:
1431 str_subtype = "unknown";
1432 break;
1433 }
1434 break;
1435
1436 case SSH_REQUEST_SERVICE:
1437 str_type = "request-service";
1438 str_subtype = ssh_message_service_service(msg);
1439 break;
1440
1441 case SSH_REQUEST_GLOBAL:
1442 str_type = "request-global";
1443 switch (subtype) {
1444 case SSH_GLOBAL_REQUEST_TCPIP_FORWARD:
1445 str_subtype = "tcpip-forward";
1446 break;
1447 case SSH_GLOBAL_REQUEST_CANCEL_TCPIP_FORWARD:
1448 str_subtype = "cancel-tcpip-forward";
1449 break;
1450 case SSH_GLOBAL_REQUEST_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001451 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001452 default:
1453 str_subtype = "unknown";
1454 break;
1455 }
1456 break;
1457
1458 default:
1459 str_type = "unknown";
1460 str_subtype = "unknown";
1461 break;
1462 }
1463
Michal Vasko05532772021-06-03 12:12:38 +02001464 VRB(session, "Received an SSH message \"%s\" of subtype \"%s\".", str_type, str_subtype);
Michal Vasko5e0edd82020-07-29 15:26:13 +02001465 if (!session || (session->status == NC_STATUS_CLOSING) || (session->status == NC_STATUS_INVALID)) {
Michal Vaskoce319162016-02-03 15:33:08 +01001466 /* "valid" situation if, for example, receiving some auth or channel request timeouted,
1467 * but we got it now, during session free */
Michal Vasko05532772021-06-03 12:12:38 +02001468 VRB(session, "SSH message arrived on a %s session, the request will be denied.",
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001469 (session && session->status == NC_STATUS_CLOSING ? "closing" : "invalid"));
Michal Vaskoce319162016-02-03 15:33:08 +01001470 ssh_message_reply_default(msg);
1471 return 0;
1472 }
Michal Vasko086311b2016-01-08 09:53:11 +01001473
1474 /*
1475 * process known messages
1476 */
1477 if (type == SSH_REQUEST_AUTH) {
1478 if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
Michal Vasko05532772021-06-03 12:12:38 +02001479 ERR(session, "User \"%s\" authenticated, but requested another authentication.", session->username);
Michal Vasko086311b2016-01-08 09:53:11 +01001480 ssh_message_reply_default(msg);
1481 return 0;
romanf578cd52023-10-19 09:47:40 +02001482 } else if (!state || !opts) {
1483 /* these two parameters should always be set during an authentication,
1484 * however do a check just in case something goes really wrong, since they
1485 * are not needed for other types of messages
1486 */
1487 ERRINT;
1488 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001489 }
1490
Michal Vasko086311b2016-01-08 09:53:11 +01001491 /* save the username, do not let the client change it */
1492 username = ssh_message_auth_user(msg);
romanf578cd52023-10-19 09:47:40 +02001493 assert(username);
1494
1495 for (i = 0; i < opts->client_count; i++) {
1496 if (!strcmp(opts->auth_clients[i].username, username)) {
1497 auth_client = &opts->auth_clients[i];
1498 break;
1499 }
1500 }
1501
1502 if (!auth_client) {
roman78df0fa2023-11-02 10:33:57 +01001503 if (opts->referenced_endpt_name) {
1504 /* client not known by the endpt, but it references another one so try it */
1505 if (nc_server_get_referenced_endpt(opts->referenced_endpt_name, &referenced_endpt)) {
1506 ERRINT;
1507 return 1;
1508 }
1509
1510 return nc_session_ssh_msg(session, referenced_endpt->opts.ssh, msg, state);
Michal Vasko086311b2016-01-08 09:53:11 +01001511 }
1512
roman545879e2024-01-19 14:43:46 +01001513 /* user not known, set his authentication methods to public key only so that
1514 * there is no interaction and it will simply be denied */
romanf578cd52023-10-19 09:47:40 +02001515 ERR(NULL, "User \"%s\" not known by the server.", username);
roman545879e2024-01-19 14:43:46 +01001516 ssh_set_auth_methods(session->ti.libssh.session, SSH_AUTH_METHOD_PUBLICKEY);
romanf578cd52023-10-19 09:47:40 +02001517 ssh_message_reply_default(msg);
1518 return 0;
1519 }
1520
1521 if (!session->username) {
Michal Vasko93224072021-11-09 12:14:28 +01001522 session->username = strdup(username);
romanf578cd52023-10-19 09:47:40 +02001523
1524 /* configure and count accepted auth methods */
1525 if (auth_client->store == NC_STORE_LOCAL) {
1526 if (auth_client->pubkey_count) {
1527 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1528 }
romana9ec3362023-12-21 10:59:57 +01001529 } else if (auth_client->store == NC_STORE_TRUSTSTORE) {
1530 if (auth_client->ts_ref) {
1531 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1532 }
1533 } else if (auth_client->store == NC_STORE_SYSTEM) {
romanf578cd52023-10-19 09:47:40 +02001534 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1535 }
1536 if (auth_client->password) {
1537 state->auth_method_count++;
1538 libssh_auth_methods |= SSH_AUTH_METHOD_PASSWORD;
1539 }
roman808f3f62023-11-23 16:01:04 +01001540 if (auth_client->kb_int_enabled) {
romanf578cd52023-10-19 09:47:40 +02001541 state->auth_method_count++;
1542 libssh_auth_methods |= SSH_AUTH_METHOD_INTERACTIVE;
1543 }
roman808f3f62023-11-23 16:01:04 +01001544 if (auth_client->none_enabled) {
romanf578cd52023-10-19 09:47:40 +02001545 libssh_auth_methods |= SSH_AUTH_METHOD_NONE;
1546 }
1547
1548 if (libssh_auth_methods & SSH_AUTH_METHOD_PUBLICKEY) {
1549 state->auth_method_count++;
1550 }
1551
1552 ssh_set_auth_methods(session->ti.libssh.session, libssh_auth_methods);
1553 } else {
Michal Vasko086311b2016-01-08 09:53:11 +01001554 if (strcmp(username, session->username)) {
romanf578cd52023-10-19 09:47:40 +02001555 /* changing username not allowed */
Michal Vasko05532772021-06-03 12:12:38 +02001556 ERR(session, "User \"%s\" changed its username to \"%s\".", session->username, username);
Michal Vasko086311b2016-01-08 09:53:11 +01001557 session->status = NC_STATUS_INVALID;
Michal Vasko428087d2016-01-14 16:04:28 +01001558 session->term_reason = NC_SESSION_TERM_OTHER;
Michal Vasko086311b2016-01-08 09:53:11 +01001559 return 1;
1560 }
1561 }
1562
romanf578cd52023-10-19 09:47:40 +02001563 /* try authenticating, the user must authenticate via all of his configured auth methods */
Michal Vasko086311b2016-01-08 09:53:11 +01001564 if (subtype == SSH_AUTH_METHOD_NONE) {
romanf578cd52023-10-19 09:47:40 +02001565 nc_sshcb_auth_none(session, auth_client, msg);
1566 ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001567 } else if (subtype == SSH_AUTH_METHOD_PASSWORD) {
romanf578cd52023-10-19 09:47:40 +02001568 ret = nc_sshcb_auth_password(session, auth_client, msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001569 } else if (subtype == SSH_AUTH_METHOD_PUBLICKEY) {
romanf578cd52023-10-19 09:47:40 +02001570 ret = nc_sshcb_auth_pubkey(session, auth_client, msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001571 } else if (subtype == SSH_AUTH_METHOD_INTERACTIVE) {
romane5675b12024-03-05 14:26:23 +01001572 ret = nc_sshcb_auth_kbdint(session, auth_client, msg);
roman4f9e4422024-03-21 10:58:41 +01001573 } else {
1574 VRB(session, "Authentication method \"%s\" not supported.", str_subtype);
1575 ssh_message_reply_default(msg);
1576 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001577 }
romanf578cd52023-10-19 09:47:40 +02001578
1579 if (!ret) {
1580 state->auth_success_count++;
1581 }
1582
1583 if (!ret && (state->auth_success_count < state->auth_method_count)) {
1584 /* success, but he needs to do another method */
1585 VRB(session, "User \"%s\" partially authenticated, but still needs to authenticate via the rest of his configured methods.", username);
1586 ssh_message_auth_reply_success(msg, 1);
1587 } else if (!ret && (state->auth_success_count == state->auth_method_count)) {
1588 /* authenticated */
1589 ssh_message_auth_reply_success(msg, 0);
1590 session->flags |= NC_SESSION_SSH_AUTHENTICATED;
1591 VRB(session, "User \"%s\" authenticated.", username);
1592 }
1593
1594 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001595 } else if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
Michal Vasko0df67562016-01-21 15:50:11 +01001596 if ((type == SSH_REQUEST_CHANNEL_OPEN) && ((enum ssh_channel_type_e)subtype == SSH_CHANNEL_SESSION)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001597 if (nc_sshcb_channel_open(session, msg)) {
Michal Vasko086311b2016-01-08 09:53:11 +01001598 ssh_message_reply_default(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001599 }
Michal Vasko086311b2016-01-08 09:53:11 +01001600 return 0;
Michal Vasko96164bf2016-01-21 15:41:58 +01001601
Michal Vasko0df67562016-01-21 15:50:11 +01001602 } else if ((type == SSH_REQUEST_CHANNEL) && ((enum ssh_channel_requests_e)subtype == SSH_CHANNEL_REQUEST_SUBSYSTEM)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001603 if (nc_sshcb_channel_subsystem(session, ssh_message_channel_request_channel(msg),
1604 ssh_message_channel_request_subsystem(msg))) {
Michal Vasko086311b2016-01-08 09:53:11 +01001605 ssh_message_reply_default(msg);
Michal Vasko96164bf2016-01-21 15:41:58 +01001606 } else {
1607 ssh_message_channel_request_reply_success(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001608 }
1609 return 0;
1610 }
1611 }
1612
1613 /* we did not process it */
1614 return 1;
1615}
1616
Michal Vasko1a38c862016-01-15 15:50:07 +01001617/* ret 1 on success, 0 on timeout, -1 on error */
Michal Vasko086311b2016-01-08 09:53:11 +01001618static int
romanf578cd52023-10-19 09:47:40 +02001619nc_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 +01001620{
roman6ece9c52022-06-22 09:29:17 +02001621 struct timespec ts_timeout;
romanf578cd52023-10-19 09:47:40 +02001622 ssh_message msg;
Michal Vasko086311b2016-01-08 09:53:11 +01001623
romanf578cd52023-10-19 09:47:40 +02001624 if (timeout) {
1625 nc_timeouttime_get(&ts_timeout, timeout * 1000);
Michal Vasko36c7be82017-02-22 13:37:59 +01001626 }
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001627 while (1) {
1628 if (!nc_session_is_connected(session)) {
romanf578cd52023-10-19 09:47:40 +02001629 ERR(session, "Communication SSH socket unexpectedly closed.");
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001630 return -1;
1631 }
1632
romanf578cd52023-10-19 09:47:40 +02001633 msg = ssh_message_get(session->ti.libssh.session);
1634 if (msg) {
1635 if (nc_session_ssh_msg(session, opts, msg, NULL)) {
1636 ssh_message_reply_default(msg);
1637 }
1638 ssh_message_free(msg);
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001639 }
1640
romanf578cd52023-10-19 09:47:40 +02001641 if (session->ti.libssh.channel && session->flags & NC_SESSION_SSH_SUBSYS_NETCONF) {
Michal Vasko1a38c862016-01-15 15:50:07 +01001642 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001643 }
1644
Michal Vasko086311b2016-01-08 09:53:11 +01001645 usleep(NC_TIMEOUT_STEP);
roman0b7e6982024-04-29 11:11:52 +02001646 if (timeout && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
roman6ece9c52022-06-22 09:29:17 +02001647 /* timeout */
1648 ERR(session, "Failed to start \"netconf\" SSH subsystem for too long, disconnecting.");
1649 break;
Michal Vasko36c7be82017-02-22 13:37:59 +01001650 }
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001651 }
Michal Vasko086311b2016-01-08 09:53:11 +01001652
Michal Vasko1a38c862016-01-15 15:50:07 +01001653 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001654}
1655
Michal Vaskof3c41e32022-09-09 11:22:21 +02001656/**
1657 * @brief Set hostkeys to be used for an SSH bind.
1658 *
1659 * @param[in] sbind SSH bind to use.
1660 * @param[in] hostkeys Array of hostkeys.
1661 * @param[in] hostkey_count Count of @p hostkeys.
1662 * @return 0 on success.
1663 * @return -1 on error.
1664 */
Michal Vasko4c1fb492017-01-30 14:31:07 +01001665static int
romanf578cd52023-10-19 09:47:40 +02001666nc_ssh_bind_add_hostkeys(ssh_bind sbind, struct nc_server_ssh_opts *opts, uint16_t hostkey_count)
Michal Vasko4c1fb492017-01-30 14:31:07 +01001667{
romanf578cd52023-10-19 09:47:40 +02001668 uint16_t i;
roman6dfdc0d2023-11-09 13:25:27 +01001669 char *privkey_path;
Michal Vaskoddce1212019-05-24 09:58:49 +02001670 int ret;
romanf578cd52023-10-19 09:47:40 +02001671 struct nc_asymmetric_key *key = NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +01001672
1673 for (i = 0; i < hostkey_count; ++i) {
roman6dfdc0d2023-11-09 13:25:27 +01001674 privkey_path = NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +01001675
romanf578cd52023-10-19 09:47:40 +02001676 /* get the asymmetric key */
1677 if (opts->hostkeys[i].store == NC_STORE_LOCAL) {
1678 /* stored locally */
1679 key = &opts->hostkeys[i].key;
1680 } else {
1681 /* keystore reference, need to get it */
1682 if (nc_server_ssh_ks_ref_get_key(opts->hostkeys[i].ks_ref, &key)) {
Michal Vasko4c1fb492017-01-30 14:31:07 +01001683 return -1;
1684 }
1685 }
1686
romanf578cd52023-10-19 09:47:40 +02001687 privkey_path = base64der_privkey_to_tmp_file(key->privkey_data, nc_privkey_format_to_str(key->privkey_type));
1688 if (!privkey_path) {
1689 ERR(NULL, "Temporarily storing a host key into a file failed (%s).", strerror(errno));
1690 return -1;
1691 }
1692
Michal Vasko4c1fb492017-01-30 14:31:07 +01001693 ret = ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY, privkey_path);
1694
1695 /* cleanup */
roman6dfdc0d2023-11-09 13:25:27 +01001696 if (unlink(privkey_path)) {
Michal Vasko05532772021-06-03 12:12:38 +02001697 WRN(NULL, "Removing a temporary host key file \"%s\" failed (%s).", privkey_path, strerror(errno));
Michal Vasko4c1fb492017-01-30 14:31:07 +01001698 }
Michal Vasko4c1fb492017-01-30 14:31:07 +01001699
1700 if (ret != SSH_OK) {
romanf578cd52023-10-19 09:47:40 +02001701 ERR(NULL, "Failed to set hostkey \"%s\" (%s).", opts->hostkeys[i].name, privkey_path);
Michal Vasko80075de2017-07-10 11:38:52 +02001702 }
1703 free(privkey_path);
1704
1705 if (ret != SSH_OK) {
Michal Vasko4c1fb492017-01-30 14:31:07 +01001706 return -1;
1707 }
1708 }
1709
1710 return 0;
1711}
1712
Michal Vasko09d700f2022-09-08 10:21:40 +02001713static int
romanf578cd52023-10-19 09:47:40 +02001714nc_accept_ssh_session_auth(struct nc_session *session, struct nc_server_ssh_opts *opts)
Michal Vasko3031aae2016-01-27 16:07:18 +01001715{
roman6ece9c52022-06-22 09:29:17 +02001716 struct timespec ts_timeout;
roman41a11e42022-06-22 09:27:08 +02001717 ssh_message msg;
romanf578cd52023-10-19 09:47:40 +02001718 struct nc_auth_state state = {0};
Michal Vasko086311b2016-01-08 09:53:11 +01001719
Michal Vasko086311b2016-01-08 09:53:11 +01001720 /* authenticate */
Michal Vasko36c7be82017-02-22 13:37:59 +01001721 if (opts->auth_timeout) {
Michal Vaskod8a74192023-02-06 15:51:50 +01001722 nc_timeouttime_get(&ts_timeout, opts->auth_timeout * 1000);
Michal Vasko36c7be82017-02-22 13:37:59 +01001723 }
1724 while (1) {
Michal Vasko2a7d4732016-01-15 09:24:46 +01001725 if (!nc_session_is_connected(session)) {
Michal Vasko05532772021-06-03 12:12:38 +02001726 ERR(session, "Communication SSH socket unexpectedly closed.");
Michal Vasko2a7d4732016-01-15 09:24:46 +01001727 return -1;
1728 }
1729
roman41a11e42022-06-22 09:27:08 +02001730 msg = ssh_message_get(session->ti.libssh.session);
1731 if (msg) {
romanf578cd52023-10-19 09:47:40 +02001732 if (nc_session_ssh_msg(session, opts, msg, &state)) {
roman41a11e42022-06-22 09:27:08 +02001733 ssh_message_reply_default(msg);
1734 }
1735 ssh_message_free(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001736 }
1737
Michal Vasko36c7be82017-02-22 13:37:59 +01001738 if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
1739 break;
1740 }
1741
Michal Vasko145ae672017-02-07 10:57:27 +01001742 if (session->opts.server.ssh_auth_attempts >= opts->auth_attempts) {
Michal Vasko05532772021-06-03 12:12:38 +02001743 ERR(session, "Too many failed authentication attempts of user \"%s\".", session->username);
Michal Vasko145ae672017-02-07 10:57:27 +01001744 return -1;
1745 }
1746
Michal Vasko086311b2016-01-08 09:53:11 +01001747 usleep(NC_TIMEOUT_STEP);
romanea0edaa2023-10-26 12:16:25 +02001748 if (opts->auth_timeout && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
roman6ece9c52022-06-22 09:29:17 +02001749 /* timeout */
1750 break;
Michal Vasko36c7be82017-02-22 13:37:59 +01001751 }
1752 }
Michal Vasko086311b2016-01-08 09:53:11 +01001753
1754 if (!(session->flags & NC_SESSION_SSH_AUTHENTICATED)) {
1755 /* timeout */
Michal Vaskoc13da702017-02-07 10:57:57 +01001756 if (session->username) {
Michal Vasko05532772021-06-03 12:12:38 +02001757 ERR(session, "User \"%s\" failed to authenticate for too long, disconnecting.", session->username);
Michal Vaskoc13da702017-02-07 10:57:57 +01001758 } else {
Michal Vasko05532772021-06-03 12:12:38 +02001759 ERR(session, "User failed to authenticate for too long, disconnecting.");
Michal Vaskoc13da702017-02-07 10:57:57 +01001760 }
Michal Vasko1a38c862016-01-15 15:50:07 +01001761 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001762 }
1763
Michal Vasko09d700f2022-09-08 10:21:40 +02001764 return 1;
1765}
1766
1767int
romanf578cd52023-10-19 09:47:40 +02001768nc_accept_ssh_session(struct nc_session *session, struct nc_server_ssh_opts *opts, int sock, int timeout)
Michal Vasko09d700f2022-09-08 10:21:40 +02001769{
1770 ssh_bind sbind = NULL;
Michal Vasko09d700f2022-09-08 10:21:40 +02001771 int rc = 1, r;
1772 struct timespec ts_timeout;
roman4cc0cd52023-04-14 09:12:29 +02001773 const char *err_msg;
Michal Vasko09d700f2022-09-08 10:21:40 +02001774
Michal Vasko09d700f2022-09-08 10:21:40 +02001775 /* other transport-specific data */
roman506354a2024-04-11 09:37:22 +02001776 session->ti_type = NC_TI_SSH;
Michal Vasko09d700f2022-09-08 10:21:40 +02001777 session->ti.libssh.session = ssh_new();
1778 if (!session->ti.libssh.session) {
1779 ERR(NULL, "Failed to initialize a new SSH session.");
1780 rc = -1;
1781 goto cleanup;
1782 }
1783
1784 sbind = ssh_bind_new();
1785 if (!sbind) {
1786 ERR(session, "Failed to create an SSH bind.");
1787 rc = -1;
1788 goto cleanup;
1789 }
1790
1791 /* configure host keys */
romanf578cd52023-10-19 09:47:40 +02001792 if (nc_ssh_bind_add_hostkeys(sbind, opts, opts->hostkey_count)) {
1793 rc = -1;
1794 goto cleanup;
1795 }
1796
1797 /* configure supported algorithms */
1798 if (opts->hostkey_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY_ALGORITHMS, opts->hostkey_algs)) {
1799 rc = -1;
1800 goto cleanup;
1801 }
1802 if (opts->encryption_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_CIPHERS_S_C, opts->encryption_algs)) {
1803 rc = -1;
1804 goto cleanup;
1805 }
1806 if (opts->kex_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_KEY_EXCHANGE, opts->kex_algs)) {
1807 rc = -1;
1808 goto cleanup;
1809 }
1810 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 +02001811 rc = -1;
1812 goto cleanup;
1813 }
1814
1815 /* accept new connection on the bind */
1816 if (ssh_bind_accept_fd(sbind, session->ti.libssh.session, sock) == SSH_ERROR) {
1817 ERR(session, "SSH failed to accept a new connection (%s).", ssh_get_error(sbind));
1818 rc = -1;
1819 goto cleanup;
1820 }
1821 sock = -1;
1822
romanf578cd52023-10-19 09:47:40 +02001823 /* set to non-blocking */
Michal Vasko09d700f2022-09-08 10:21:40 +02001824 ssh_set_blocking(session->ti.libssh.session, 0);
1825
1826 if (timeout > -1) {
Michal Vaskod8a74192023-02-06 15:51:50 +01001827 nc_timeouttime_get(&ts_timeout, timeout);
Michal Vasko09d700f2022-09-08 10:21:40 +02001828 }
1829 while ((r = ssh_handle_key_exchange(session->ti.libssh.session)) == SSH_AGAIN) {
1830 /* this tends to take longer */
1831 usleep(NC_TIMEOUT_STEP * 20);
Michal Vaskod8a74192023-02-06 15:51:50 +01001832 if ((timeout > -1) && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001833 break;
1834 }
1835 }
1836 if (r == SSH_AGAIN) {
1837 ERR(session, "SSH key exchange timeout.");
1838 rc = 0;
1839 goto cleanup;
1840 } else if (r != SSH_OK) {
roman4cc0cd52023-04-14 09:12:29 +02001841 err_msg = ssh_get_error(session->ti.libssh.session);
1842 if (err_msg[0] == '\0') {
1843 err_msg = "hostkey algorithm generated from the hostkey most likely not found in the set of configured hostkey algorithms";
1844 }
1845 ERR(session, "SSH key exchange error (%s).", err_msg);
Michal Vasko09d700f2022-09-08 10:21:40 +02001846 rc = -1;
1847 goto cleanup;
1848 }
1849
romane5675b12024-03-05 14:26:23 +01001850 /* authenticate, store auth_timeout in session so we can retrieve it in kb interactive API */
1851 session->data = &opts->auth_timeout;
1852 rc = nc_accept_ssh_session_auth(session, opts);
1853 session->data = NULL;
1854 if (rc != 1) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001855 goto cleanup;
1856 }
1857
Michal Vasko09d700f2022-09-08 10:21:40 +02001858 /* open channel and request 'netconf' subsystem */
romanf578cd52023-10-19 09:47:40 +02001859 if ((rc = nc_accept_ssh_session_open_netconf_channel(session, opts, timeout)) != 1) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001860 goto cleanup;
Michal Vasko086311b2016-01-08 09:53:11 +01001861 }
1862
Michal Vasko09d700f2022-09-08 10:21:40 +02001863cleanup:
1864 if (sock > -1) {
1865 close(sock);
1866 }
1867 ssh_bind_free(sbind);
1868 return rc;
Michal Vasko086311b2016-01-08 09:53:11 +01001869}
1870
Michal Vasko71090fc2016-05-24 16:37:28 +02001871API NC_MSG_TYPE
1872nc_session_accept_ssh_channel(struct nc_session *orig_session, struct nc_session **session)
1873{
1874 NC_MSG_TYPE msgtype;
1875 struct nc_session *new_session = NULL;
Michal Vasko9f6275e2017-10-05 13:50:05 +02001876 struct timespec ts_cur;
Michal Vasko71090fc2016-05-24 16:37:28 +02001877
roman40672412023-05-04 11:10:22 +02001878 NC_CHECK_ARG_RET(orig_session, orig_session, session, NC_MSG_ERROR);
Michal Vasko71090fc2016-05-24 16:37:28 +02001879
roman506354a2024-04-11 09:37:22 +02001880 if ((orig_session->status == NC_STATUS_RUNNING) && (orig_session->ti_type == NC_TI_SSH) &&
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001881 orig_session->ti.libssh.next) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001882 for (new_session = orig_session->ti.libssh.next;
1883 new_session != orig_session;
1884 new_session = new_session->ti.libssh.next) {
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001885 if ((new_session->status == NC_STATUS_STARTING) && new_session->ti.libssh.channel &&
1886 (new_session->flags & NC_SESSION_SSH_SUBSYS_NETCONF)) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001887 /* we found our session */
1888 break;
1889 }
1890 }
1891 if (new_session == orig_session) {
1892 new_session = NULL;
1893 }
1894 }
1895
1896 if (!new_session) {
Michal Vasko05532772021-06-03 12:12:38 +02001897 ERR(orig_session, "Session does not have a NETCONF SSH channel ready.");
Michal Vasko71090fc2016-05-24 16:37:28 +02001898 return NC_MSG_ERROR;
1899 }
1900
1901 /* assign new SID atomically */
Michal Vasko5bd4a3f2021-06-17 16:40:10 +02001902 new_session->id = ATOMIC_INC_RELAXED(server_opts.new_session_id);
Michal Vasko71090fc2016-05-24 16:37:28 +02001903
1904 /* NETCONF handshake */
Michal Vasko131120a2018-05-29 15:44:02 +02001905 msgtype = nc_handshake_io(new_session);
Michal Vasko71090fc2016-05-24 16:37:28 +02001906 if (msgtype != NC_MSG_HELLO) {
1907 return msgtype;
1908 }
1909
Michal Vaskod8a74192023-02-06 15:51:50 +01001910 nc_realtime_get(&ts_cur);
roman44efa322023-11-03 13:57:25 +01001911 new_session->opts.server.session_start = ts_cur;
Michal Vaskod8a74192023-02-06 15:51:50 +01001912 nc_timeouttime_get(&ts_cur, 0);
Michal Vasko9f6275e2017-10-05 13:50:05 +02001913 new_session->opts.server.last_rpc = ts_cur.tv_sec;
Michal Vasko71090fc2016-05-24 16:37:28 +02001914 new_session->status = NC_STATUS_RUNNING;
1915 *session = new_session;
1916
1917 return msgtype;
1918}
1919
1920API NC_MSG_TYPE
Michal Vasko96164bf2016-01-21 15:41:58 +01001921nc_ps_accept_ssh_channel(struct nc_pollsession *ps, struct nc_session **session)
Michal Vasko086311b2016-01-08 09:53:11 +01001922{
Michal Vaskobdcf2362016-07-26 11:35:43 +02001923 uint8_t q_id;
Michal Vasko71090fc2016-05-24 16:37:28 +02001924 NC_MSG_TYPE msgtype;
Michal Vaskoe4300a82017-05-24 10:35:42 +02001925 struct nc_session *new_session = NULL, *cur_session;
Michal Vasko9f6275e2017-10-05 13:50:05 +02001926 struct timespec ts_cur;
Michal Vaskoc61c4492016-01-25 11:13:34 +01001927 uint16_t i;
Michal Vasko086311b2016-01-08 09:53:11 +01001928
roman40672412023-05-04 11:10:22 +02001929 NC_CHECK_ARG_RET(NULL, ps, session, NC_MSG_ERROR);
Michal Vasko086311b2016-01-08 09:53:11 +01001930
Michal Vasko48a63ed2016-03-01 09:48:21 +01001931 /* LOCK */
Michal Vasko227f8ff2016-07-26 14:08:59 +02001932 if (nc_ps_lock(ps, &q_id, __func__)) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001933 return NC_MSG_ERROR;
Michal Vaskof04a52a2016-04-07 10:52:10 +02001934 }
Michal Vasko48a63ed2016-03-01 09:48:21 +01001935
Michal Vasko96164bf2016-01-21 15:41:58 +01001936 for (i = 0; i < ps->session_count; ++i) {
fanchanghu3d4e7212017-08-09 09:42:30 +08001937 cur_session = ps->sessions[i]->session;
roman506354a2024-04-11 09:37:22 +02001938 if ((cur_session->status == NC_STATUS_RUNNING) && (cur_session->ti_type == NC_TI_SSH) &&
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001939 cur_session->ti.libssh.next) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001940 /* an SSH session with more channels */
Michal Vaskoe4300a82017-05-24 10:35:42 +02001941 for (new_session = cur_session->ti.libssh.next;
1942 new_session != cur_session;
Michal Vasko96164bf2016-01-21 15:41:58 +01001943 new_session = new_session->ti.libssh.next) {
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001944 if ((new_session->status == NC_STATUS_STARTING) && new_session->ti.libssh.channel &&
1945 (new_session->flags & NC_SESSION_SSH_SUBSYS_NETCONF)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001946 /* we found our session */
1947 break;
1948 }
1949 }
Michal Vaskoe4300a82017-05-24 10:35:42 +02001950 if (new_session != cur_session) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001951 break;
1952 }
Michal Vaskofb89d772016-01-08 12:25:35 +01001953
Michal Vasko96164bf2016-01-21 15:41:58 +01001954 new_session = NULL;
1955 }
1956 }
Michal Vaskofb89d772016-01-08 12:25:35 +01001957
Michal Vasko48a63ed2016-03-01 09:48:21 +01001958 /* UNLOCK */
Michal Vasko227f8ff2016-07-26 14:08:59 +02001959 nc_ps_unlock(ps, q_id, __func__);
Michal Vasko48a63ed2016-03-01 09:48:21 +01001960
Michal Vasko96164bf2016-01-21 15:41:58 +01001961 if (!new_session) {
Michal Vasko05532772021-06-03 12:12:38 +02001962 ERR(NULL, "No session with a NETCONF SSH channel ready was found.");
Michal Vasko71090fc2016-05-24 16:37:28 +02001963 return NC_MSG_ERROR;
Michal Vasko96164bf2016-01-21 15:41:58 +01001964 }
1965
1966 /* assign new SID atomically */
Michal Vasko5bd4a3f2021-06-17 16:40:10 +02001967 new_session->id = ATOMIC_INC_RELAXED(server_opts.new_session_id);
Michal Vaskofb89d772016-01-08 12:25:35 +01001968
Michal Vasko086311b2016-01-08 09:53:11 +01001969 /* NETCONF handshake */
Michal Vasko131120a2018-05-29 15:44:02 +02001970 msgtype = nc_handshake_io(new_session);
Michal Vasko71090fc2016-05-24 16:37:28 +02001971 if (msgtype != NC_MSG_HELLO) {
1972 return msgtype;
Michal Vasko086311b2016-01-08 09:53:11 +01001973 }
Michal Vasko48a63ed2016-03-01 09:48:21 +01001974
Michal Vaskod8a74192023-02-06 15:51:50 +01001975 nc_realtime_get(&ts_cur);
roman44efa322023-11-03 13:57:25 +01001976 new_session->opts.server.session_start = ts_cur;
Michal Vaskod8a74192023-02-06 15:51:50 +01001977 nc_timeouttime_get(&ts_cur, 0);
Michal Vasko9f6275e2017-10-05 13:50:05 +02001978 new_session->opts.server.last_rpc = ts_cur.tv_sec;
Michal Vasko086311b2016-01-08 09:53:11 +01001979 new_session->status = NC_STATUS_RUNNING;
Michal Vasko96164bf2016-01-21 15:41:58 +01001980 *session = new_session;
Michal Vasko086311b2016-01-08 09:53:11 +01001981
Michal Vasko71090fc2016-05-24 16:37:28 +02001982 return msgtype;
Michal Vasko086311b2016-01-08 09:53:11 +01001983}