blob: c31b7f133bc829131ac3d3c73b8acae2f2739966 [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
Michal Vasko4c1fb492017-01-30 14:31:07 +010051static char *
romanf578cd52023-10-19 09:47:40 +020052base64der_privkey_to_tmp_file(const char *in, const char *privkey_format)
Michal Vasko086311b2016-01-08 09:53:11 +010053{
Michal Vasko4c1fb492017-01-30 14:31:07 +010054 char path[12] = "/tmp/XXXXXX";
55 int fd, written;
romanf578cd52023-10-19 09:47:40 +020056 unsigned len;
Michal Vasko27252692017-03-21 15:34:13 +010057 mode_t umode;
Michal Vasko4c1fb492017-01-30 14:31:07 +010058 FILE *file;
59
romanf578cd52023-10-19 09:47:40 +020060 NC_CHECK_ARG_RET(NULL, in, NULL);
Michal Vasko086311b2016-01-08 09:53:11 +010061
mekleob31878b2019-09-09 14:10:47 +020062 umode = umask(0177);
Michal Vasko4c1fb492017-01-30 14:31:07 +010063 fd = mkstemp(path);
Michal Vasko27252692017-03-21 15:34:13 +010064 umask(umode);
Michal Vasko4c1fb492017-01-30 14:31:07 +010065 if (fd == -1) {
66 return NULL;
67 }
68
Michal Vasko3964a832018-09-18 14:37:39 +020069 file = fdopen(fd, "w");
Michal Vasko4c1fb492017-01-30 14:31:07 +010070 if (!file) {
71 close(fd);
72 return NULL;
73 }
74
romanf578cd52023-10-19 09:47:40 +020075 /* write header */
romand0fe5952024-03-21 15:59:33 +010076 written = fwrite("-----BEGIN", 1, 10, file);
romanf578cd52023-10-19 09:47:40 +020077 if (privkey_format) {
78 written += fwrite(privkey_format, 1, strlen(privkey_format), file);
romanf578cd52023-10-19 09:47:40 +020079 written += fwrite("PRIVATE KEY-----\n", 1, 17, file);
romand0fe5952024-03-21 15:59:33 +010080 } else {
81 written += fwrite(" PRIVATE KEY-----\n", 1, 18, file);
romanf578cd52023-10-19 09:47:40 +020082 }
Michal Vasko68177b72020-04-27 15:46:53 +020083
romanf578cd52023-10-19 09:47:40 +020084 /* write data */
85 written += fwrite(in, 1, strlen(in), file);
86
87 /* write footer */
romand0fe5952024-03-21 15:59:33 +010088 written += fwrite("\n-----END", 1, 9, file);
romanf578cd52023-10-19 09:47:40 +020089 if (privkey_format) {
90 written += fwrite(privkey_format, 1, strlen(privkey_format), file);
romanf578cd52023-10-19 09:47:40 +020091 written += fwrite("PRIVATE KEY-----", 1, 16, file);
romand0fe5952024-03-21 15:59:33 +010092 } else {
93 written += fwrite(" PRIVATE KEY-----", 1, 17, file);
romanf578cd52023-10-19 09:47:40 +020094 }
95
96 fclose(file);
97
98 /* checksum */
99 if (privkey_format) {
romand0fe5952024-03-21 15:59:33 +0100100 len = 10 + strlen(privkey_format) + 17 + strlen(in) + 9 + strlen(privkey_format) + 16;
romanf578cd52023-10-19 09:47:40 +0200101 } else {
romand0fe5952024-03-21 15:59:33 +0100102 len = 10 + 18 + strlen(in) + 9 + 17;
romanf578cd52023-10-19 09:47:40 +0200103 }
104
105 if ((unsigned)written != len) {
106 unlink(path);
107 return NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +0100108 }
109
110 return strdup(path);
111}
112
113static int
romanf578cd52023-10-19 09:47:40 +0200114nc_server_ssh_ks_ref_get_key(const char *referenced_name, struct nc_asymmetric_key **askey)
Michal Vasko4c1fb492017-01-30 14:31:07 +0100115{
romanf578cd52023-10-19 09:47:40 +0200116 uint16_t i;
117 struct nc_keystore *ks = &server_opts.keystore;
Michal Vaskofbfe8b62017-02-14 10:22:30 +0100118
romanf578cd52023-10-19 09:47:40 +0200119 *askey = NULL;
Michal Vaskod45e25a2016-01-08 15:48:44 +0100120
romanf578cd52023-10-19 09:47:40 +0200121 /* lookup name */
122 for (i = 0; i < ks->asym_key_count; i++) {
123 if (!strcmp(referenced_name, ks->asym_keys[i].name)) {
124 break;
Michal Vaskofbfe8b62017-02-14 10:22:30 +0100125 }
126 }
127
romanf578cd52023-10-19 09:47:40 +0200128 if (i == ks->asym_key_count) {
129 ERR(NULL, "Keystore entry \"%s\" not found.", referenced_name);
130 return 1;
Michal Vaskoe2713da2016-08-22 16:06:40 +0200131 }
Michal Vasko7d255882017-02-09 13:35:08 +0100132
romanf578cd52023-10-19 09:47:40 +0200133 *askey = &ks->asym_keys[i];
134
135 /* check if the referenced public key is SubjectPublicKeyInfo */
136 if ((*askey)->pubkey_data && nc_is_pk_subject_public_key_info((*askey)->pubkey_data)) {
137 ERR(NULL, "The public key of the referenced hostkey \"%s\" is in the SubjectPublicKeyInfo format, "
138 "which is not allowed in the SSH!", referenced_name);
139 return 1;
Michal Vasko7d255882017-02-09 13:35:08 +0100140 }
Michal Vaskoe2713da2016-08-22 16:06:40 +0200141
Michal Vasko5fcc7142016-02-02 12:21:10 +0100142 return 0;
Michal Vaskob05053d2016-01-22 16:12:06 +0100143}
144
romanf578cd52023-10-19 09:47:40 +0200145static int
146nc_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 +0100147{
romanf578cd52023-10-19 09:47:40 +0200148 uint16_t i, j;
149 struct nc_truststore *ts = &server_opts.truststore;
Michal Vasko3031aae2016-01-27 16:07:18 +0100150
romanf578cd52023-10-19 09:47:40 +0200151 *pubkeys = NULL;
152 *pubkey_count = 0;
153
154 /* lookup name */
155 for (i = 0; i < ts->pub_bag_count; i++) {
156 if (!strcmp(referenced_name, ts->pub_bags[i].name)) {
157 break;
158 }
Michal Vasko3031aae2016-01-27 16:07:18 +0100159 }
Michal Vaskoc46b3df2021-07-26 09:30:05 +0200160
romanf578cd52023-10-19 09:47:40 +0200161 if (i == ts->pub_bag_count) {
162 ERR(NULL, "Truststore entry \"%s\" not found.", referenced_name);
163 return 1;
164 }
Michal Vaskoc46b3df2021-07-26 09:30:05 +0200165
romanf578cd52023-10-19 09:47:40 +0200166 /* check if any of the referenced public keys is SubjectPublicKeyInfo */
167 for (j = 0; j < ts->pub_bags[i].pubkey_count; j++) {
168 if (nc_is_pk_subject_public_key_info(ts->pub_bags[i].pubkeys[j].data)) {
169 ERR(NULL, "A public key of the referenced public key bag \"%s\" is in the SubjectPublicKeyInfo format, "
170 "which is not allowed in the SSH!", referenced_name);
171 return 1;
172 }
173 }
Michal Vasko3031aae2016-01-27 16:07:18 +0100174
romanf578cd52023-10-19 09:47:40 +0200175 *pubkeys = ts->pub_bags[i].pubkeys;
176 *pubkey_count = ts->pub_bags[i].pubkey_count;
177 return 0;
Michal Vaskob05053d2016-01-22 16:12:06 +0100178}
179
romana9ec3362023-12-21 10:59:57 +0100180static char *
181nc_server_ssh_uid_to_str(uid_t uid)
182{
183 int buf_len;
184 char *uid_str;
185
186 /* get the number of digits and alloc */
187 buf_len = snprintf(NULL, 0, "%u", uid);
188 uid_str = malloc(buf_len + 1);
189 NC_CHECK_ERRMEM_RET(!uid_str, NULL);
190
191 /* convert to string */
192 sprintf(uid_str, "%u", uid);
193 uid_str[buf_len] = '\0';
194 return uid_str;
195}
196
197static int
198nc_server_ssh_str_append(const char src_c, const char *src_str, int *size, int *idx, char **dst)
199{
200 int src_size, allocate = 0, ret;
201
202 /* get size of char/string we want to append */
203 if (src_str) {
204 src_size = strlen(src_str);
205 } else {
206 src_size = 1;
207 }
208
209 /* check if we have enough space, if not realloc */
210 while ((src_size + *idx) >= *size) {
211 (*size) += 16;
212 allocate = 1;
213 }
214 if (allocate) {
215 *dst = nc_realloc(*dst, *size);
216 NC_CHECK_ERRMEM_RET(!*dst, 1);
217 }
218
219 /* append the char/string */
220 if (src_str) {
221 ret = sprintf(*dst + *idx, "%s", src_str);
222 } else {
223 ret = sprintf(*dst + *idx, "%c", src_c);
224 }
225 if (ret < 0) {
226 return 1;
227 }
228
229 *idx += ret;
230 return 0;
231}
232
233static int
234nc_server_ssh_get_system_keys_path(const char *username, char **out_path)
235{
236 int ret = 0, i, have_percent = 0, size = 0, idx = 0;
237 const char *path_fmt = server_opts.authkey_path_fmt;
238 char *path = NULL, *buf = NULL, *uid = NULL;
239 struct passwd *pw, pw_buf;
240 size_t buf_len = 0;
241
242 /* check if the path format contains any tokens */
243 if (strstr(path_fmt, "%h") || strstr(path_fmt, "%U") || strstr(path_fmt, "%u") || strstr(path_fmt, "%%")) {
244 /* get pw */
245 pw = nc_getpw(0, username, &pw_buf, &buf, &buf_len);
246 if (!pw) {
247 ERR(NULL, "Unable to get passwd entry for user \"%s\".", username);
248 ret = 1;
249 goto cleanup;
250 }
251
252 /* convert UID to a string */
253 uid = nc_server_ssh_uid_to_str(pw->pw_uid);
254 if (!uid) {
255 ret = 1;
256 goto cleanup;
257 }
258 } else {
259 /* no tokens, just copy the path and return */
260 *out_path = strdup(path_fmt);
261 NC_CHECK_ERRMEM_RET(!*out_path, 1);
262 goto cleanup;
263 }
264
265 /* go over characters from format, copy them to path and interpret tokens correctly */
266 for (i = 0; path_fmt[i]; i++) {
267 if (have_percent) {
268 /* special token, need to convert it */
269 if (path_fmt[i] == '%') {
270 ret = nc_server_ssh_str_append('%', NULL, &size, &idx, &path);
271 } else if (path_fmt[i] == 'h') {
272 /* user home */
273 ret = nc_server_ssh_str_append(0, pw->pw_dir, &size, &idx, &path);
274 } else if (path_fmt[i] == 'u') {
275 /* username */
276 ret = nc_server_ssh_str_append(0, username, &size, &idx, &path);
277 } else if (path_fmt[i] == 'U') {
278 /* UID */
279 ret = nc_server_ssh_str_append(0, uid, &size, &idx, &path);
280 } else {
281 ERR(NULL, "Failed to parse system public keys path format \"%s\".", server_opts.authkey_path_fmt);
282 ret = 1;
283 }
284
285 have_percent = 0;
286 } else {
287 if (path_fmt[i] == '%') {
288 have_percent = 1;
289 } else {
290 /* ordinary character with no meaning */
291 ret = nc_server_ssh_str_append(path_fmt[i], NULL, &size, &idx, &path);
292 }
293 }
294
295 if (ret) {
296 free(path);
297 goto cleanup;
298 }
299 }
300
301 *out_path = path;
302cleanup:
303 free(uid);
304 free(buf);
305 return ret;
306}
307
308/* reads public keys from authorized_keys-like file */
309static int
310nc_server_ssh_read_authorized_keys_file(const char *path, struct nc_public_key **pubkeys, uint16_t *pubkey_count)
311{
312 int ret = 0, line_num = 0;
313 FILE *f = NULL;
314 char *line = NULL, *ptr, *ptr2;
315 size_t n;
316 enum ssh_keytypes_e ktype;
317
318 NC_CHECK_ARG_RET(NULL, path, pubkeys, 1);
319
320 *pubkeys = NULL;
321 *pubkey_count = 0;
322
323 f = fopen(path, "r");
324 if (!f) {
325 ERR(NULL, "Unable to open \"%s\" (%s).", path, strerror(errno));
326 ret = 1;
327 goto cleanup;
328 }
329
330 while (getline(&line, &n, f) > -1) {
331 ++line_num;
332 if ((line[0] == '#') || (line[0] == '\n')) {
333 /* comment or empty line */
334 continue;
335 }
336
337 /* separate key type */
338 ptr = line;
339 for (ptr2 = ptr; ptr2[0] && !isspace(ptr2[0]); ptr2++) {}
340 if (!ptr2[0]) {
341 ERR(NULL, "Invalid format of authorized keys file \"%s\" on line %d.", path, line_num);
342 ret = 1;
343 goto cleanup;
344 }
345 ptr2[0] = '\0';
346
347 /* detect key type */
348 ktype = ssh_key_type_from_name(ptr);
349 if ((ktype != SSH_KEYTYPE_RSA) && (ktype != SSH_KEYTYPE_ECDSA_P256) && (ktype != SSH_KEYTYPE_ECDSA_P384) &&
350 (ktype != SSH_KEYTYPE_ECDSA_P521) && (ktype != SSH_KEYTYPE_ED25519)) {
351 WRN(NULL, "Unsupported key type \"%s\" in authorized keys file \"%s\" on line %d.", ptr, path, line_num);
352 continue;
353 }
354
355 /* get key data */
356 ptr = ptr2 + 1;
357 for (ptr2 = ptr; ptr2[0] && !isspace(ptr2[0]); ptr2++) {}
358 ptr2[0] = '\0';
359
360 /* add the key */
361 *pubkeys = nc_realloc(*pubkeys, (*pubkey_count + 1) * sizeof **pubkeys);
362 NC_CHECK_ERRMEM_GOTO(!(*pubkeys), ret = 1, cleanup);
363 ret = asprintf(&(*pubkeys)[*pubkey_count].name, "authorized_key_%" PRIu16, *pubkey_count);
364 NC_CHECK_ERRMEM_GOTO(ret == -1, (*pubkeys)[*pubkey_count].name = NULL; ret = 1, cleanup);
365 (*pubkeys)[*pubkey_count].type = NC_PUBKEY_FORMAT_SSH;
366 (*pubkeys)[*pubkey_count].data = strdup(ptr);
367 NC_CHECK_ERRMEM_GOTO(!(*pubkeys)[*pubkey_count].data, ret = 1, cleanup);
368 (*pubkey_count)++;
369 }
370
371 /* ok */
372 ret = 0;
373cleanup:
374 if (f) {
375 fclose(f);
376 }
377 free(line);
378 return ret;
379}
380
381static int
382nc_server_ssh_get_system_keys(const char *username, struct nc_public_key **pubkeys, uint16_t *pubkey_count)
383{
384 int ret = 0;
385 char *path = NULL;
386
387 /* convert the path format to get the actual path */
388 ret = nc_server_ssh_get_system_keys_path(username, &path);
389 if (ret) {
390 ERR(NULL, "Getting system keys path failed.");
391 goto cleanup;
392 }
393
394 /* get the keys */
395 ret = nc_server_ssh_read_authorized_keys_file(path, pubkeys, pubkey_count);
396 if (ret) {
397 ERR(NULL, "Reading system keys failed.");
398 goto cleanup;
399 }
400
401cleanup:
402 free(path);
403 return ret;
404}
405
Michal Vaskof3c41e32022-09-09 11:22:21 +0200406/**
407 * @brief Compare hashed password with a cleartext password for a match.
408 *
409 * @param[in] pass_hash Hashed password.
410 * @param[in] pass_clear Cleartext password.
411 * @return 0 on match.
412 * @return non-zero if not a match.
413 */
Michal Vasko086311b2016-01-08 09:53:11 +0100414static int
roman814f5112023-10-19 15:51:16 +0200415auth_password_compare_pwd(const char *stored_pw, const char *received_pw)
Michal Vasko086311b2016-01-08 09:53:11 +0100416{
roman814f5112023-10-19 15:51:16 +0200417 char *received_pw_hash = NULL;
roman8b1a6c32023-10-26 13:35:22 +0200418 struct crypt_data cdata = {0};
Michal Vasko086311b2016-01-08 09:53:11 +0100419
roman814f5112023-10-19 15:51:16 +0200420 if (!stored_pw[0]) {
421 if (!received_pw[0]) {
Michal Vasko05532772021-06-03 12:12:38 +0200422 WRN(NULL, "User authentication successful with an empty password!");
Michal Vasko086311b2016-01-08 09:53:11 +0100423 return 0;
424 } else {
425 /* the user did now know he does not need any password,
426 * (which should not be used) so deny authentication */
427 return 1;
428 }
429 }
430
roman814f5112023-10-19 15:51:16 +0200431 if (!strncmp(stored_pw, "$0$", 3)) {
432 /* cleartext password, simply compare the values */
433 return strcmp(stored_pw + 3, received_pw);
434 }
435
roman814f5112023-10-19 15:51:16 +0200436 received_pw_hash = crypt_r(received_pw, stored_pw, &cdata);
roman814f5112023-10-19 15:51:16 +0200437 if (!received_pw_hash) {
roman8b1a6c32023-10-26 13:35:22 +0200438 ERR(NULL, "Hashing the password failed (%s).", strerror(errno));
Andrew Langefeld158d6fd2018-06-11 18:51:44 -0500439 return 1;
440 }
441
roman814f5112023-10-19 15:51:16 +0200442 return strcmp(received_pw_hash, stored_pw);
Michal Vasko086311b2016-01-08 09:53:11 +0100443}
444
romanf578cd52023-10-19 09:47:40 +0200445static int
446nc_sshcb_auth_password(struct nc_session *session, struct nc_auth_client *auth_client, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +0100447{
Michal Vaskoebba7602018-03-23 13:14:08 +0100448 int auth_ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +0100449
roman4f9e4422024-03-21 10:58:41 +0100450 if (!auth_client->password) {
451 VRB(session, "User \"%s\" does not have password method configured, but a request was received.", auth_client->username);
452 } else {
453 auth_ret = auth_password_compare_pwd(auth_client->password, ssh_message_auth_password(msg));
454 }
Michal Vasko086311b2016-01-08 09:53:11 +0100455
romanf578cd52023-10-19 09:47:40 +0200456 if (auth_ret) {
Michal Vaskoebba7602018-03-23 13:14:08 +0100457 ++session->opts.server.ssh_auth_attempts;
Michal Vasko05532772021-06-03 12:12:38 +0200458 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", session->username,
459 session->opts.server.ssh_auth_attempts);
Michal Vaskoebba7602018-03-23 13:14:08 +0100460 ssh_message_reply_default(msg);
461 }
romanf578cd52023-10-19 09:47:40 +0200462
463 return auth_ret;
Michal Vasko086311b2016-01-08 09:53:11 +0100464}
465
romane5675b12024-03-05 14:26:23 +0100466API int
467nc_server_ssh_kbdint_get_nanswers(const struct nc_session *session, ssh_session libssh_session)
romanc6518422023-11-30 16:39:00 +0100468{
469 int ret = 0;
470 struct timespec ts_timeout = {0};
roman56c85c02023-12-07 13:09:28 +0100471 ssh_message reply = NULL;
romane5675b12024-03-05 14:26:23 +0100472 uint16_t auth_timeout = *((uint16_t *)session->data);
473
474 NC_CHECK_ARG_RET(NULL, session, libssh_session, -1);
romanc6518422023-11-30 16:39:00 +0100475
476 if (auth_timeout) {
477 nc_timeouttime_get(&ts_timeout, auth_timeout * 1000);
478 }
479
480 /* wait for answers from the client */
481 do {
482 if (!nc_session_is_connected(session)) {
483 ERR(NULL, "SSH communication socket unexpectedly closed.");
484 ret = -1;
485 goto cleanup;
486 }
487
488 reply = ssh_message_get(libssh_session);
489 if (reply) {
490 break;
491 }
492
493 usleep(NC_TIMEOUT_STEP);
494 } while (auth_timeout && (nc_timeouttime_cur_diff(&ts_timeout) >= 1));
495 if (!reply) {
496 ERR(NULL, "Authentication timeout.");
497 ret = -1;
498 goto cleanup;
499 }
500
501 ret = ssh_userauth_kbdint_getnanswers(libssh_session);
502
503cleanup:
504 ssh_message_free(reply);
505 return ret;
506}
507
Michal Vasko0d81c572022-09-26 10:39:31 +0200508#ifdef HAVE_LIBPAM
509
roman41a11e42022-06-22 09:27:08 +0200510/**
511 * @brief PAM conversation function, which serves as a callback for exchanging messages between the client and a PAM module.
512 *
513 * @param[in] n_messages Number of messages.
514 * @param[in] msg PAM module's messages.
515 * @param[out] resp User responses.
516 * @param[in] appdata_ptr Callback's data.
roman808f3f62023-11-23 16:01:04 +0100517 * @return PAM_SUCCESS on success, PAM_BUF_ERR on memory allocation error, PAM_CONV_ERR otherwise.
roman41a11e42022-06-22 09:27:08 +0200518 */
519static int
520nc_pam_conv_clb(int n_messages, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr)
521{
522 int i, j, t, r = PAM_SUCCESS, n_answers, n_requests = n_messages;
523 const char **prompts = NULL;
524 char *echo = NULL;
525 const char *name = "Keyboard-Interactive Authentication";
526 const char *instruction = "Please enter your authentication token";
527 ssh_message reply = NULL;
528 struct nc_pam_thread_arg *clb_data = appdata_ptr;
529 ssh_session libssh_session;
roman41a11e42022-06-22 09:27:08 +0200530
531 libssh_session = clb_data->session->ti.libssh.session;
roman41a11e42022-06-22 09:27:08 +0200532
533 /* PAM_MAX_NUM_MSG == 32 by default */
534 if ((n_messages <= 0) || (n_messages >= PAM_MAX_NUM_MSG)) {
romanc6518422023-11-30 16:39:00 +0100535 ERR(clb_data->session, "Bad number of PAM messages (#%d).", n_messages);
roman41a11e42022-06-22 09:27:08 +0200536 r = PAM_CONV_ERR;
537 goto cleanup;
538 }
539
540 /* only accepting these 4 types of messages */
541 for (i = 0; i < n_messages; i++) {
542 t = msg[i]->msg_style;
543 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 +0100544 ERR(clb_data->session, "PAM conversation callback received an unexpected type of message.");
roman41a11e42022-06-22 09:27:08 +0200545 r = PAM_CONV_ERR;
546 goto cleanup;
547 }
548 }
549
550 /* display messages with errors and/or some information and count the amount of actual authentication challenges */
551 for (i = 0; i < n_messages; i++) {
552 if (msg[i]->msg_style == PAM_TEXT_INFO) {
romanc6518422023-11-30 16:39:00 +0100553 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 +0200554 n_requests--;
555 }
556 if (msg[i]->msg_style == PAM_ERROR_MSG) {
romanc6518422023-11-30 16:39:00 +0100557 ERR(clb_data->session, "PAM conversation callback received an error message (%s).", msg[i]->msg);
roman41a11e42022-06-22 09:27:08 +0200558 r = PAM_CONV_ERR;
559 goto cleanup;
560 }
561 }
562
563 /* there are no requests left for the user, only messages with some information for the client were sent */
564 if (n_requests <= 0) {
565 r = PAM_SUCCESS;
566 goto cleanup;
567 }
568
569 /* it is the PAM module's responsibility to release both, this array and the responses themselves */
570 *resp = calloc(n_requests, sizeof **resp);
571 prompts = calloc(n_requests, sizeof *prompts);
572 echo = calloc(n_requests, sizeof *echo);
roman3a95bb22023-10-26 11:07:17 +0200573 NC_CHECK_ERRMEM_GOTO(!(*resp) || !prompts || !echo, r = PAM_BUF_ERR, cleanup);
roman41a11e42022-06-22 09:27:08 +0200574
575 /* set the prompts for the user */
576 j = 0;
577 for (i = 0; i < n_messages; i++) {
578 if ((msg[i]->msg_style == PAM_PROMPT_ECHO_ON) || (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF)) {
579 prompts[j++] = msg[i]->msg;
580 }
581 }
582
583 /* iterate over all the messages and adjust the echo array accordingly */
584 j = 0;
585 for (i = 0; i < n_messages; i++) {
586 if (msg[i]->msg_style == PAM_PROMPT_ECHO_ON) {
587 echo[j++] = 1;
588 }
589 if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF) {
590 /* no need to set to 0 because of calloc */
591 j++;
592 }
593 }
594
595 /* print all the keyboard-interactive challenges to the user */
596 r = ssh_message_auth_interactive_request(clb_data->msg, name, instruction, n_requests, prompts, echo);
597 if (r != SSH_OK) {
romanc6518422023-11-30 16:39:00 +0100598 ERR(clb_data->session, "Failed to send an authentication request.");
roman41a11e42022-06-22 09:27:08 +0200599 r = PAM_CONV_ERR;
600 goto cleanup;
601 }
602
romane5675b12024-03-05 14:26:23 +0100603 n_answers = nc_server_ssh_kbdint_get_nanswers(clb_data->session, libssh_session);
romanc6518422023-11-30 16:39:00 +0100604 if (n_answers < 0) {
605 /* timeout or dc */
roman41a11e42022-06-22 09:27:08 +0200606 r = PAM_CONV_ERR;
607 goto cleanup;
romanc6518422023-11-30 16:39:00 +0100608 } else if (n_answers != n_requests) {
609 /* check if the number of answers and requests matches */
610 ERR(clb_data->session, "Expected %d response(s), got %d.", n_requests, n_answers);
roman41a11e42022-06-22 09:27:08 +0200611 r = PAM_CONV_ERR;
612 goto cleanup;
613 }
614
615 /* give the replies to a PAM module */
616 for (i = 0; i < n_answers; i++) {
617 (*resp)[i].resp = strdup(ssh_userauth_kbdint_getanswer(libssh_session, i));
618 /* it should be the caller's responsibility to free this, however if mem alloc fails,
619 * it is safer to free the responses here and set them to NULL */
620 if ((*resp)[i].resp == NULL) {
621 for (j = 0; j < i; j++) {
622 free((*resp)[j].resp);
623 (*resp)[j].resp = NULL;
624 }
625 ERRMEM;
626 r = PAM_BUF_ERR;
627 goto cleanup;
628 }
629 }
630
631cleanup:
632 ssh_message_free(reply);
633 free(prompts);
634 free(echo);
635 return r;
636}
637
638/**
639 * @brief Handles authentication via Linux PAM.
640 *
641 * @param[in] session NETCONF session.
642 * @param[in] ssh_msg SSH message with a keyboard-interactive authentication request.
643 * @return PAM_SUCCESS on success;
644 * @return PAM error otherwise.
645 */
646static int
romane5675b12024-03-05 14:26:23 +0100647nc_pam_auth(struct nc_session *session, struct nc_auth_client *client, ssh_message ssh_msg)
roman41a11e42022-06-22 09:27:08 +0200648{
649 pam_handle_t *pam_h = NULL;
650 int ret;
651 struct nc_pam_thread_arg clb_data;
652 struct pam_conv conv;
653
654 /* structure holding callback's data */
655 clb_data.msg = ssh_msg;
656 clb_data.session = session;
657
658 /* PAM conversation structure holding the callback and it's data */
659 conv.conv = nc_pam_conv_clb;
660 conv.appdata_ptr = &clb_data;
661
roman808f3f62023-11-23 16:01:04 +0100662 if (!server_opts.pam_config_name) {
romanc6518422023-11-30 16:39:00 +0100663 ERR(session, "PAM configuration filename not set.");
romanf578cd52023-10-19 09:47:40 +0200664 ret = 1;
665 goto cleanup;
666 }
667
roman41a11e42022-06-22 09:27:08 +0200668 /* initialize PAM and see if the given configuration file exists */
roman808f3f62023-11-23 16:01:04 +0100669 ret = pam_start(server_opts.pam_config_name, client->username, &conv, &pam_h);
roman41a11e42022-06-22 09:27:08 +0200670 if (ret != PAM_SUCCESS) {
romanc6518422023-11-30 16:39:00 +0100671 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200672 goto cleanup;
673 }
674
675 /* authentication based on the modules listed in the configuration file */
676 ret = pam_authenticate(pam_h, 0);
677 if (ret != PAM_SUCCESS) {
678 if (ret == PAM_ABORT) {
romanc6518422023-11-30 16:39:00 +0100679 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200680 goto cleanup;
681 } else {
romanc6518422023-11-30 16:39:00 +0100682 VRB(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200683 goto cleanup;
684 }
685 }
686
687 /* correct token entered, check other requirements(the time of the day, expired token, ...) */
688 ret = pam_acct_mgmt(pam_h, 0);
689 if ((ret != PAM_SUCCESS) && (ret != PAM_NEW_AUTHTOK_REQD)) {
romanc6518422023-11-30 16:39:00 +0100690 VRB(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200691 goto cleanup;
692 }
693
694 /* if a token has expired a new one will be generated */
695 if (ret == PAM_NEW_AUTHTOK_REQD) {
romanc6518422023-11-30 16:39:00 +0100696 VRB(session, "PAM warning occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200697 ret = pam_chauthtok(pam_h, PAM_CHANGE_EXPIRED_AUTHTOK);
698 if (ret == PAM_SUCCESS) {
romanc6518422023-11-30 16:39:00 +0100699 VRB(session, "The authentication token of user \"%s\" updated successfully.", client->username);
roman41a11e42022-06-22 09:27:08 +0200700 } else {
romanc6518422023-11-30 16:39:00 +0100701 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200702 goto cleanup;
703 }
704 }
705
706cleanup:
707 /* destroy the PAM context */
roman6dfdc0d2023-11-09 13:25:27 +0100708 if (pam_h && (pam_end(pam_h, ret) != PAM_SUCCESS)) {
romancab602e2023-11-24 11:30:32 +0100709 ERR(NULL, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200710 }
711 return ret;
712}
713
romanc6518422023-11-30 16:39:00 +0100714#elif defined (HAVE_SHADOW)
715
716static struct passwd *
717nc_server_ssh_getpwnam(const char *username, struct passwd *pwd_buf, char **buf, size_t *buf_size)
718{
719 struct passwd *pwd = NULL;
720 char *mem;
721 int r = 0;
722
723 do {
724 r = getpwnam_r(username, pwd_buf, *buf, *buf_size, &pwd);
725 if (pwd) {
726 /* entry found */
727 break;
728 }
729
730 if (r == ERANGE) {
731 /* small buffer, enlarge */
732 *buf_size <<= 2;
733 mem = realloc(*buf, *buf_size);
734 if (!mem) {
735 ERRMEM;
736 return NULL;
737 }
738 *buf = mem;
739 }
740 } while (r == ERANGE);
741
742 return pwd;
743}
744
745static struct spwd *
746nc_server_ssh_getspnam(const char *username, struct spwd *spwd_buf, char **buf, size_t *buf_size)
747{
748 struct spwd *spwd = NULL;
749 char *mem;
750 int r = 0;
751
752 do {
753# ifndef __QNXNTO__
754 r = getspnam_r(username, spwd_buf, *buf, *buf_size, &spwd);
755# else
756 spwd = getspnam_r(username, spwd_buf, *buf, *buf_size);
757# endif
758 if (spwd) {
759 /* entry found */
760 break;
761 }
762
763 if (r == ERANGE) {
764 /* small buffer, enlarge */
765 *buf_size <<= 2;
766 mem = realloc(*buf, *buf_size);
767 if (!mem) {
768 ERRMEM;
769 return NULL;
770 }
771 *buf = mem;
772 }
773 } while (r == ERANGE);
774
775 return spwd;
776}
777
778static char *
779nc_server_ssh_get_pwd_hash(const char *username)
780{
781 struct passwd *pwd, pwd_buf;
782 struct spwd *spwd, spwd_buf;
783 char *pass_hash = NULL, *buf = NULL;
784 size_t buf_size = 256;
785
786 buf = malloc(buf_size);
787 NC_CHECK_ERRMEM_GOTO(!buf, , error);
788
789 pwd = nc_server_ssh_getpwnam(username, &pwd_buf, &buf, &buf_size);
790 if (!pwd) {
791 VRB(NULL, "User \"%s\" not found locally.", username);
792 goto error;
793 }
794
795 if (!strcmp(pwd->pw_passwd, "x")) {
796 spwd = nc_server_ssh_getspnam(username, &spwd_buf, &buf, &buf_size);
797 if (!spwd) {
798 VRB(NULL, "Failed to retrieve the shadow entry for \"%s\".", username);
799 goto error;
800 } else if ((spwd->sp_expire > -1) && (spwd->sp_expire <= (time(NULL) / (60 * 60 * 24)))) {
801 WRN(NULL, "User \"%s\" account has expired.", username);
802 goto error;
803 }
804
805 pass_hash = spwd->sp_pwdp;
806 } else {
807 pass_hash = pwd->pw_passwd;
808 }
809
810 if (!pass_hash) {
811 ERR(NULL, "No password could be retrieved for \"%s\".", username);
812 goto error;
813 }
814
815 /* check the hash structure for special meaning */
816 if (!strcmp(pass_hash, "*") || !strcmp(pass_hash, "!")) {
817 VRB(NULL, "User \"%s\" is not allowed to authenticate using a password.", username);
818 goto error;
819 }
820 if (!strcmp(pass_hash, "*NP*")) {
821 VRB(NULL, "Retrieving password for \"%s\" from a NIS+ server not supported.", username);
822 goto error;
823 }
824
825 pass_hash = strdup(pass_hash);
826 free(buf);
827 return pass_hash;
828
829error:
830 free(buf);
831 return NULL;
832}
833
834/**
835 * @brief Authenticate using locally stored credentials.
836 *
837 * @param[in] session Session to authenticate on.
838 * @param[in] client Client to authenticate.
romanc6518422023-11-30 16:39:00 +0100839 * @param[in] msg SSH message that originally requested kbdint authentication.
840 *
841 * @return 0 on success, non-zero otherwise.
842 */
843static int
romane5675b12024-03-05 14:26:23 +0100844nc_server_ssh_system_auth(struct nc_session *session, struct nc_auth_client *client, ssh_message msg)
romanc6518422023-11-30 16:39:00 +0100845{
846 int ret = 0, n_answers;
847 const char *name = "Keyboard-Interactive Authentication";
848 const char *instruction = "Please enter your authentication token";
849 char *prompt = NULL, *local_pw = NULL, *received_pw = NULL;
850 char echo[] = {0};
851
852 /* try to get the client's locally stored pw hash */
853 local_pw = nc_server_ssh_get_pwd_hash(client->username);
854 if (!local_pw) {
855 ERR(session, "Unable to get %s's credentials.", client->username);
856 ret = 1;
857 goto cleanup;
858 }
859
860 ret = asprintf(&prompt, "%s's password:", client->username);
861 NC_CHECK_ERRMEM_GOTO(ret == -1, prompt = NULL; ret = 1, cleanup);
862
863 /* send the password prompt to the client */
864 ret = ssh_message_auth_interactive_request(msg, name, instruction, 1, (const char **) &prompt, echo);
865 if (ret) {
866 ERR(session, "Failed to send an authentication request to client \"%s\".", client->username);
867 goto cleanup;
868 }
869
870 /* get the reply */
romane5675b12024-03-05 14:26:23 +0100871 n_answers = nc_server_ssh_kbdint_get_nanswers(session, session->ti.libssh.session);
romanc6518422023-11-30 16:39:00 +0100872 if (n_answers < 0) {
873 /* timeout or dc */
874 ret = 1;
875 goto cleanup;
876 } else if (n_answers != 1) {
877 /* only expecting a single answer */
878 ERR(session, "Unexpected amount of answers in system auth. Expected 1, got \"%d\".", n_answers);
879 ret = 1;
880 goto cleanup;
881 }
882 received_pw = strdup(ssh_userauth_kbdint_getanswer(session->ti.libssh.session, 0));
883 NC_CHECK_ERRMEM_GOTO(!received_pw, ret = 1, cleanup);
884
885 /* cmp the pw hashes */
886 ret = auth_password_compare_pwd(local_pw, received_pw);
887
888cleanup:
889 free(local_pw);
890 free(received_pw);
891 free(prompt);
892 return ret;
893}
894
895#endif
Michal Vasko0d81c572022-09-26 10:39:31 +0200896
romanf578cd52023-10-19 09:47:40 +0200897static int
romane5675b12024-03-05 14:26:23 +0100898nc_sshcb_auth_kbdint(struct nc_session *session, struct nc_auth_client *client, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +0100899{
bhart3bc2f582018-06-05 12:40:32 -0500900 int auth_ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +0100901
roman4f9e4422024-03-21 10:58:41 +0100902 if (!client->kb_int_enabled) {
903 VRB(session, "User \"%s\" does not have Keyboard-interactive method configured, but a request was received.", client->username);
904 } else if (server_opts.interactive_auth_clb) {
romanf578cd52023-10-19 09:47:40 +0200905 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 +0200906 } else {
907#ifdef HAVE_LIBPAM
romanc6518422023-11-30 16:39:00 +0100908 /* authenticate using PAM */
romane5675b12024-03-05 14:26:23 +0100909 if (!nc_pam_auth(session, client, msg)) {
romanc6518422023-11-30 16:39:00 +0100910 auth_ret = 0;
911 }
912#elif defined (HAVE_SHADOW)
913 /* authenticate using locally configured users */
romane5675b12024-03-05 14:26:23 +0100914 if (!nc_server_ssh_system_auth(session, client, msg)) {
Michal Vasko0d81c572022-09-26 10:39:31 +0200915 auth_ret = 0;
916 }
917#else
romanc6518422023-11-30 16:39:00 +0100918 ERR(NULL, "Keyboard-interactive method not supported.");
Michal Vasko0d81c572022-09-26 10:39:31 +0200919#endif
bhart1bb7cdb2018-07-02 15:03:30 -0500920 }
921
922 /* Authenticate message based on outcome */
romanf578cd52023-10-19 09:47:40 +0200923 if (auth_ret) {
bhart1bb7cdb2018-07-02 15:03:30 -0500924 ++session->opts.server.ssh_auth_attempts;
romanc6518422023-11-30 16:39:00 +0100925 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", client->username,
Michal Vasko05532772021-06-03 12:12:38 +0200926 session->opts.server.ssh_auth_attempts);
bhart1bb7cdb2018-07-02 15:03:30 -0500927 ssh_message_reply_default(msg);
Michal Vasko086311b2016-01-08 09:53:11 +0100928 }
romanf578cd52023-10-19 09:47:40 +0200929
930 return auth_ret;
931}
932
roman808f3f62023-11-23 16:01:04 +0100933API void
934nc_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),
935 void *user_data, void (*free_user_data)(void *user_data))
936{
romanc6518422023-11-30 16:39:00 +0100937 /* CONFIG LOCK */
938 pthread_rwlock_wrlock(&server_opts.config_lock);
939
roman808f3f62023-11-23 16:01:04 +0100940 server_opts.interactive_auth_clb = interactive_auth_clb;
941 server_opts.interactive_auth_data = user_data;
942 server_opts.interactive_auth_data_free = free_user_data;
romanc6518422023-11-30 16:39:00 +0100943
944 /* CONFIG UNLOCK */
945 pthread_rwlock_unlock(&server_opts.config_lock);
roman808f3f62023-11-23 16:01:04 +0100946}
947
948#ifdef HAVE_LIBPAM
949
950API int
951nc_server_ssh_set_pam_conf_filename(const char *filename)
952{
romanc6518422023-11-30 16:39:00 +0100953 int ret = 0;
954
roman808f3f62023-11-23 16:01:04 +0100955 NC_CHECK_ARG_RET(NULL, filename, 1);
956
romanc6518422023-11-30 16:39:00 +0100957 /* CONFIG LOCK */
958 pthread_rwlock_wrlock(&server_opts.config_lock);
959
roman808f3f62023-11-23 16:01:04 +0100960 free(server_opts.pam_config_name);
961 server_opts.pam_config_name = strdup(filename);
romanc6518422023-11-30 16:39:00 +0100962 if (!server_opts.pam_config_name) {
963 ERRMEM;
964 ret = 1;
965 }
966
967 /* CONFIG UNLOCK */
968 pthread_rwlock_unlock(&server_opts.config_lock);
969 return ret;
roman808f3f62023-11-23 16:01:04 +0100970}
971
972#else
973
974API int
975nc_server_ssh_set_pam_conf_filename(const char *filename)
976{
romanf69fbcf2023-12-14 09:24:34 +0100977 /* LibPAM not supported */
roman808f3f62023-11-23 16:01:04 +0100978 (void) filename;
roman808f3f62023-11-23 16:01:04 +0100979 return 1;
980}
981
982#endif /* HAVE_LIBPAM */
983
romana9ec3362023-12-21 10:59:57 +0100984API int
985nc_server_ssh_set_authkey_path_format(const char *path)
986{
987 int ret = 0;
988
989 NC_CHECK_ARG_RET(NULL, path, 1);
990
991 /* CONFIG LOCK */
992 pthread_rwlock_wrlock(&server_opts.config_lock);
993
994 free(server_opts.authkey_path_fmt);
995 server_opts.authkey_path_fmt = strdup(path);
996 if (!server_opts.authkey_path_fmt) {
997 ERRMEM;
998 ret = 1;
999 }
1000
1001 /* CONFIG UNLOCK */
1002 pthread_rwlock_unlock(&server_opts.config_lock);
1003 return ret;
1004}
1005
romanf578cd52023-10-19 09:47:40 +02001006/*
1007 * Get the public key type from binary data stored in buffer.
1008 * The data is in the form of: 4 bytes = data length, then data of data length
1009 * and the data is in network byte order. The key has to be in the SSH2 format.
1010 */
1011static const char *
1012nc_server_ssh_get_pubkey_type(const char *buffer, uint32_t *len)
1013{
1014 uint32_t type_len;
1015
1016 /* copy the 4 bytes */
1017 memcpy(&type_len, buffer, sizeof type_len);
1018 /* type_len now stores the length of the key type */
1019 type_len = ntohl(type_len);
1020 *len = type_len;
1021
1022 /* move 4 bytes in the buffer, this is where the type should be */
1023 buffer += sizeof type_len;
1024 return buffer;
1025}
1026
1027/**
1028 * @brief Create ssh key from base64 pubkey data.
1029 *
1030 * @param[in] base64 base64 encoded public key.
1031 * @param[out] key created ssh key.
1032 * @return 0 on success, 1 otherwise.
1033 */
1034static int
1035nc_server_ssh_create_ssh_pubkey(const char *base64, ssh_key *key)
1036{
1037 int ret = 0;
1038 char *bin = NULL;
1039 const char *pub_type = NULL;
1040 uint32_t pub_type_len = 0;
1041
roman6dfdc0d2023-11-09 13:25:27 +01001042 NC_CHECK_ARG_RET(NULL, base64, key, 1);
romanf578cd52023-10-19 09:47:40 +02001043
1044 *key = NULL;
1045
1046 /* convert base64 to binary */
roman83289292024-04-05 12:33:24 +02001047 if (nc_base64_decode_wrap(base64, &bin) == -1) {
romanf578cd52023-10-19 09:47:40 +02001048 ERR(NULL, "Unable to decode base64.");
1049 ret = 1;
1050 goto cleanup;
1051 }
1052
1053 /* get the key type and try to import it if possible */
1054 pub_type = nc_server_ssh_get_pubkey_type(bin, &pub_type_len);
1055 if (!pub_type) {
1056 ret = 1;
1057 goto cleanup;
1058 } else if (!strncmp(pub_type, "ssh-dss", pub_type_len)) {
1059 ERR(NULL, "DSA keys are not supported.");
1060 ret = 1;
1061 goto cleanup;
1062 } else if (!strncmp(pub_type, "ssh-rsa", pub_type_len)) {
1063 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_RSA, key);
1064 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp256", pub_type_len)) {
1065 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P256, key);
1066 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp384", pub_type_len)) {
1067 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P384, key);
1068 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp521", pub_type_len)) {
1069 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P521, key);
1070 } else if (!strncmp(pub_type, "ssh-ed25519", pub_type_len)) {
1071 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ED25519, key);
1072 } else {
1073 ERR(NULL, "Public key type not recognised.");
1074 ret = 1;
1075 goto cleanup;
1076 }
1077
1078cleanup:
1079 if (ret != SSH_OK) {
1080 ERR(NULL, "Error importing public key.");
1081 }
1082 free(bin);
1083 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +01001084}
1085
Michal Vaskof3c41e32022-09-09 11:22:21 +02001086/**
1087 * @brief Compare SSH key with configured authorized keys and return the username of the matching one, if any.
1088 *
1089 * @param[in] key Presented SSH key to compare.
1090 * @return Authorized key username, NULL if no match was found.
1091 */
romanf578cd52023-10-19 09:47:40 +02001092static int
1093auth_pubkey_compare_key(ssh_key key, struct nc_auth_client *auth_client)
Michal Vasko086311b2016-01-08 09:53:11 +01001094{
Michal Vaskoe2bfcd62024-03-28 07:58:49 +01001095 uint16_t i, pubkey_count = 0;
Michal Vasko3e9d1682017-02-24 09:50:15 +01001096 int ret = 0;
romanf578cd52023-10-19 09:47:40 +02001097 ssh_key new_key = NULL;
romana9ec3362023-12-21 10:59:57 +01001098 struct nc_public_key *pubkeys = NULL;
Michal Vasko086311b2016-01-08 09:53:11 +01001099
romanf578cd52023-10-19 09:47:40 +02001100 /* get the correct public key storage */
1101 if (auth_client->store == NC_STORE_LOCAL) {
1102 pubkeys = auth_client->pubkeys;
1103 pubkey_count = auth_client->pubkey_count;
romana9ec3362023-12-21 10:59:57 +01001104 } else if (auth_client->store == NC_STORE_TRUSTSTORE) {
romanf578cd52023-10-19 09:47:40 +02001105 ret = nc_server_ssh_ts_ref_get_keys(auth_client->ts_ref, &pubkeys, &pubkey_count);
1106 if (ret) {
1107 ERR(NULL, "Error getting \"%s\"'s public keys from the truststore.", auth_client->username);
romana9ec3362023-12-21 10:59:57 +01001108 goto cleanup;
Michal Vasko17dfda92016-12-01 14:06:16 +01001109 }
romana9ec3362023-12-21 10:59:57 +01001110 } else if (auth_client->store == NC_STORE_SYSTEM) {
1111 ret = nc_server_ssh_get_system_keys(auth_client->username, &pubkeys, &pubkey_count);
1112 if (ret) {
1113 ERR(NULL, "Failed to retrieve public keys of user \"%s\" from the system.", auth_client->username);
1114 goto cleanup;
1115 }
1116 } else {
1117 ERRINT;
1118 return 1;
romanf578cd52023-10-19 09:47:40 +02001119 }
Michal Vasko17dfda92016-12-01 14:06:16 +01001120
romanf578cd52023-10-19 09:47:40 +02001121 /* try to compare all of the client's keys with the key received in the SSH message */
1122 for (i = 0; i < pubkey_count; i++) {
1123 /* create the SSH key from the data */
1124 if (nc_server_ssh_create_ssh_pubkey(pubkeys[i].data, &new_key)) {
1125 ssh_key_free(new_key);
Michal Vasko086311b2016-01-08 09:53:11 +01001126 continue;
1127 }
1128
romanf578cd52023-10-19 09:47:40 +02001129 /* compare the keys */
1130 ret = ssh_key_cmp(key, new_key, SSH_KEY_CMP_PUBLIC);
1131 if (!ret) {
Michal Vasko086311b2016-01-08 09:53:11 +01001132 break;
romanf578cd52023-10-19 09:47:40 +02001133 } else {
1134 WRN(NULL, "User's \"%s\" public key doesn't match, trying another.", auth_client->username);
1135 ssh_key_free(new_key);
Michal Vasko086311b2016-01-08 09:53:11 +01001136 }
Michal Vasko086311b2016-01-08 09:53:11 +01001137 }
romanf578cd52023-10-19 09:47:40 +02001138 if (i == pubkey_count) {
1139 ret = 1;
romana9ec3362023-12-21 10:59:57 +01001140 goto cleanup;
Michal Vasko086311b2016-01-08 09:53:11 +01001141 }
1142
romana9ec3362023-12-21 10:59:57 +01001143cleanup:
romanf578cd52023-10-19 09:47:40 +02001144 if (!ret) {
1145 /* only free a key if everything was ok, it would have already been freed otherwise */
1146 ssh_key_free(new_key);
1147 }
Michal Vaskoa05c7b12017-01-30 14:33:08 +01001148
romana9ec3362023-12-21 10:59:57 +01001149 if ((auth_client->store == NC_STORE_SYSTEM) && pubkeys) {
1150 for (i = 0; i < pubkey_count; i++) {
1151 free(pubkeys[i].name);
1152 free(pubkeys[i].data);
1153 }
1154 free(pubkeys);
1155 }
romanf578cd52023-10-19 09:47:40 +02001156 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +01001157}
1158
1159static void
romanf578cd52023-10-19 09:47:40 +02001160nc_sshcb_auth_none(struct nc_session *session, struct nc_auth_client *auth_client, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +01001161{
roman808f3f62023-11-23 16:01:04 +01001162 if (auth_client->none_enabled && !auth_client->password && !auth_client->pubkey_count && !auth_client->kb_int_enabled) {
romanf578cd52023-10-19 09:47:40 +02001163 /* only authenticate the client if he supports none and no other method */
1164 session->flags |= NC_SESSION_SSH_AUTHENTICATED;
1165 VRB(session, "User \"%s\" authenticated.", session->username);
1166 ssh_message_auth_reply_success(msg, 0);
1167 }
1168
1169 ssh_message_reply_default(msg);
1170}
1171
1172static int
1173nc_sshcb_auth_pubkey(struct nc_session *session, struct nc_auth_client *auth_client, ssh_message msg)
1174{
1175 int signature_state, ret = 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001176
roman9130fc12023-11-03 13:56:23 +01001177 if (auth_pubkey_compare_key(ssh_message_auth_pubkey(msg), auth_client)) {
1178 VRB(session, "User \"%s\" tried to use an unknown (unauthorized) public key.", session->username);
1179 ret = 1;
1180 goto fail;
Michal Vaskobd13a932016-09-14 09:00:35 +02001181 }
Michal Vaskobd13a932016-09-14 09:00:35 +02001182
Michal Vasko086311b2016-01-08 09:53:11 +01001183 signature_state = ssh_message_auth_publickey_state(msg);
romanf578cd52023-10-19 09:47:40 +02001184 if (signature_state == SSH_PUBLICKEY_STATE_NONE) {
Michal Vaskobd13a932016-09-14 09:00:35 +02001185 /* accepting only the use of a public key */
1186 ssh_message_auth_reply_pk_ok_simple(msg);
romanf578cd52023-10-19 09:47:40 +02001187 ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001188 }
1189
romanf578cd52023-10-19 09:47:40 +02001190 return ret;
Michal Vaskobd13a932016-09-14 09:00:35 +02001191
1192fail:
Michal Vasko2e6defd2016-10-07 15:48:15 +02001193 ++session->opts.server.ssh_auth_attempts;
Michal Vasko05532772021-06-03 12:12:38 +02001194 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", session->username,
1195 session->opts.server.ssh_auth_attempts);
Michal Vasko086311b2016-01-08 09:53:11 +01001196 ssh_message_reply_default(msg);
romanf578cd52023-10-19 09:47:40 +02001197
1198 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +01001199}
1200
1201static int
Michal Vasko96164bf2016-01-21 15:41:58 +01001202nc_sshcb_channel_open(struct nc_session *session, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +01001203{
Michal Vasko96164bf2016-01-21 15:41:58 +01001204 ssh_channel chan;
1205
1206 /* first channel request */
1207 if (!session->ti.libssh.channel) {
1208 if (session->status != NC_STATUS_STARTING) {
Michal Vasko9e036d52016-01-08 10:49:26 +01001209 ERRINT;
Michal Vasko086311b2016-01-08 09:53:11 +01001210 return -1;
1211 }
Michal Vasko96164bf2016-01-21 15:41:58 +01001212 chan = ssh_message_channel_request_open_reply_accept(msg);
1213 if (!chan) {
Michal Vasko05532772021-06-03 12:12:38 +02001214 ERR(session, "Failed to create a new SSH channel.");
Michal Vasko96164bf2016-01-21 15:41:58 +01001215 return -1;
1216 }
1217 session->ti.libssh.channel = chan;
Michal Vasko086311b2016-01-08 09:53:11 +01001218
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001219 /* additional channel request */
Michal Vasko96164bf2016-01-21 15:41:58 +01001220 } else {
1221 chan = ssh_message_channel_request_open_reply_accept(msg);
1222 if (!chan) {
Michal Vasko05532772021-06-03 12:12:38 +02001223 ERR(session, "Session %u: failed to create a new SSH channel.", session->id);
Michal Vasko96164bf2016-01-21 15:41:58 +01001224 return -1;
1225 }
1226 /* channel was created and libssh stored it internally in the ssh_session structure, good enough */
Michal Vasko086311b2016-01-08 09:53:11 +01001227 }
1228
Michal Vasko086311b2016-01-08 09:53:11 +01001229 return 0;
1230}
1231
1232static int
1233nc_sshcb_channel_subsystem(struct nc_session *session, ssh_channel channel, const char *subsystem)
1234{
Michal Vasko96164bf2016-01-21 15:41:58 +01001235 struct nc_session *new_session;
Michal Vasko086311b2016-01-08 09:53:11 +01001236
Michal Vasko96164bf2016-01-21 15:41:58 +01001237 if (strcmp(subsystem, "netconf")) {
Michal Vasko05532772021-06-03 12:12:38 +02001238 WRN(session, "Received an unknown subsystem \"%s\" request.", subsystem);
Michal Vasko086311b2016-01-08 09:53:11 +01001239 return -1;
1240 }
1241
Michal Vasko96164bf2016-01-21 15:41:58 +01001242 if (session->ti.libssh.channel == channel) {
1243 /* first channel requested */
1244 if (session->ti.libssh.next || (session->status != NC_STATUS_STARTING)) {
1245 ERRINT;
1246 return -1;
Michal Vasko086311b2016-01-08 09:53:11 +01001247 }
Michal Vasko96164bf2016-01-21 15:41:58 +01001248 if (session->flags & NC_SESSION_SSH_SUBSYS_NETCONF) {
Michal Vasko05532772021-06-03 12:12:38 +02001249 ERR(session, "Subsystem \"netconf\" requested for the second time.");
Michal Vasko96164bf2016-01-21 15:41:58 +01001250 return -1;
1251 }
1252
1253 session->flags |= NC_SESSION_SSH_SUBSYS_NETCONF;
Michal Vasko086311b2016-01-08 09:53:11 +01001254 } else {
Michal Vasko96164bf2016-01-21 15:41:58 +01001255 /* additional channel subsystem request, new session is ready as far as SSH is concerned */
Michal Vasko131120a2018-05-29 15:44:02 +02001256 new_session = nc_new_session(NC_SERVER, 1);
roman3a95bb22023-10-26 11:07:17 +02001257 NC_CHECK_ERRMEM_RET(!new_session, -1);
Michal Vasko96164bf2016-01-21 15:41:58 +01001258
1259 /* insert the new session */
1260 if (!session->ti.libssh.next) {
1261 new_session->ti.libssh.next = session;
1262 } else {
1263 new_session->ti.libssh.next = session->ti.libssh.next;
1264 }
1265 session->ti.libssh.next = new_session;
1266
1267 new_session->status = NC_STATUS_STARTING;
roman506354a2024-04-11 09:37:22 +02001268 new_session->ti_type = NC_TI_SSH;
Michal Vasko131120a2018-05-29 15:44:02 +02001269 new_session->io_lock = session->io_lock;
Michal Vasko96164bf2016-01-21 15:41:58 +01001270 new_session->ti.libssh.channel = channel;
1271 new_session->ti.libssh.session = session->ti.libssh.session;
Michal Vasko93224072021-11-09 12:14:28 +01001272 new_session->username = strdup(session->username);
1273 new_session->host = strdup(session->host);
Michal Vasko96164bf2016-01-21 15:41:58 +01001274 new_session->port = session->port;
Michal Vasko93224072021-11-09 12:14:28 +01001275 new_session->ctx = (struct ly_ctx *)session->ctx;
Michal Vasko83d15322018-09-27 09:44:02 +02001276 new_session->flags = NC_SESSION_SSH_AUTHENTICATED | NC_SESSION_SSH_SUBSYS_NETCONF | NC_SESSION_SHAREDCTX;
Michal Vasko086311b2016-01-08 09:53:11 +01001277 }
1278
1279 return 0;
1280}
1281
Michal Vasko96164bf2016-01-21 15:41:58 +01001282int
romanf578cd52023-10-19 09:47:40 +02001283nc_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 +01001284{
1285 const char *str_type, *str_subtype = NULL, *username;
romanf578cd52023-10-19 09:47:40 +02001286 int subtype, type, libssh_auth_methods = 0, ret = 0;
1287 uint16_t i;
1288 struct nc_auth_client *auth_client = NULL;
roman78df0fa2023-11-02 10:33:57 +01001289 struct nc_endpt *referenced_endpt;
Michal Vasko086311b2016-01-08 09:53:11 +01001290
1291 type = ssh_message_type(msg);
1292 subtype = ssh_message_subtype(msg);
1293
1294 switch (type) {
1295 case SSH_REQUEST_AUTH:
1296 str_type = "request-auth";
1297 switch (subtype) {
1298 case SSH_AUTH_METHOD_NONE:
1299 str_subtype = "none";
1300 break;
1301 case SSH_AUTH_METHOD_PASSWORD:
1302 str_subtype = "password";
1303 break;
1304 case SSH_AUTH_METHOD_PUBLICKEY:
1305 str_subtype = "publickey";
1306 break;
1307 case SSH_AUTH_METHOD_HOSTBASED:
1308 str_subtype = "hostbased";
1309 break;
1310 case SSH_AUTH_METHOD_INTERACTIVE:
1311 str_subtype = "interactive";
1312 break;
1313 case SSH_AUTH_METHOD_GSSAPI_MIC:
1314 str_subtype = "gssapi-mic";
1315 break;
1316 }
1317 break;
1318
1319 case SSH_REQUEST_CHANNEL_OPEN:
1320 str_type = "request-channel-open";
1321 switch (subtype) {
1322 case SSH_CHANNEL_SESSION:
1323 str_subtype = "session";
1324 break;
1325 case SSH_CHANNEL_DIRECT_TCPIP:
1326 str_subtype = "direct-tcpip";
1327 break;
1328 case SSH_CHANNEL_FORWARDED_TCPIP:
1329 str_subtype = "forwarded-tcpip";
1330 break;
1331 case (int)SSH_CHANNEL_X11:
1332 str_subtype = "channel-x11";
1333 break;
1334 case SSH_CHANNEL_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001335 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001336 default:
1337 str_subtype = "unknown";
1338 break;
1339 }
1340 break;
1341
1342 case SSH_REQUEST_CHANNEL:
1343 str_type = "request-channel";
1344 switch (subtype) {
1345 case SSH_CHANNEL_REQUEST_PTY:
1346 str_subtype = "pty";
1347 break;
1348 case SSH_CHANNEL_REQUEST_EXEC:
1349 str_subtype = "exec";
1350 break;
1351 case SSH_CHANNEL_REQUEST_SHELL:
1352 str_subtype = "shell";
1353 break;
1354 case SSH_CHANNEL_REQUEST_ENV:
1355 str_subtype = "env";
1356 break;
1357 case SSH_CHANNEL_REQUEST_SUBSYSTEM:
1358 str_subtype = "subsystem";
1359 break;
1360 case SSH_CHANNEL_REQUEST_WINDOW_CHANGE:
1361 str_subtype = "window-change";
1362 break;
1363 case SSH_CHANNEL_REQUEST_X11:
1364 str_subtype = "x11";
1365 break;
1366 case SSH_CHANNEL_REQUEST_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001367 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001368 default:
1369 str_subtype = "unknown";
1370 break;
1371 }
1372 break;
1373
1374 case SSH_REQUEST_SERVICE:
1375 str_type = "request-service";
1376 str_subtype = ssh_message_service_service(msg);
1377 break;
1378
1379 case SSH_REQUEST_GLOBAL:
1380 str_type = "request-global";
1381 switch (subtype) {
1382 case SSH_GLOBAL_REQUEST_TCPIP_FORWARD:
1383 str_subtype = "tcpip-forward";
1384 break;
1385 case SSH_GLOBAL_REQUEST_CANCEL_TCPIP_FORWARD:
1386 str_subtype = "cancel-tcpip-forward";
1387 break;
1388 case SSH_GLOBAL_REQUEST_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001389 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001390 default:
1391 str_subtype = "unknown";
1392 break;
1393 }
1394 break;
1395
1396 default:
1397 str_type = "unknown";
1398 str_subtype = "unknown";
1399 break;
1400 }
1401
Michal Vasko05532772021-06-03 12:12:38 +02001402 VRB(session, "Received an SSH message \"%s\" of subtype \"%s\".", str_type, str_subtype);
Michal Vasko5e0edd82020-07-29 15:26:13 +02001403 if (!session || (session->status == NC_STATUS_CLOSING) || (session->status == NC_STATUS_INVALID)) {
Michal Vaskoce319162016-02-03 15:33:08 +01001404 /* "valid" situation if, for example, receiving some auth or channel request timeouted,
1405 * but we got it now, during session free */
Michal Vasko05532772021-06-03 12:12:38 +02001406 VRB(session, "SSH message arrived on a %s session, the request will be denied.",
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001407 (session && session->status == NC_STATUS_CLOSING ? "closing" : "invalid"));
Michal Vaskoce319162016-02-03 15:33:08 +01001408 ssh_message_reply_default(msg);
1409 return 0;
1410 }
Michal Vasko086311b2016-01-08 09:53:11 +01001411
1412 /*
1413 * process known messages
1414 */
1415 if (type == SSH_REQUEST_AUTH) {
1416 if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
Michal Vasko05532772021-06-03 12:12:38 +02001417 ERR(session, "User \"%s\" authenticated, but requested another authentication.", session->username);
Michal Vasko086311b2016-01-08 09:53:11 +01001418 ssh_message_reply_default(msg);
1419 return 0;
romanf578cd52023-10-19 09:47:40 +02001420 } else if (!state || !opts) {
1421 /* these two parameters should always be set during an authentication,
1422 * however do a check just in case something goes really wrong, since they
1423 * are not needed for other types of messages
1424 */
1425 ERRINT;
1426 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001427 }
1428
Michal Vasko086311b2016-01-08 09:53:11 +01001429 /* save the username, do not let the client change it */
1430 username = ssh_message_auth_user(msg);
romanf578cd52023-10-19 09:47:40 +02001431 assert(username);
1432
1433 for (i = 0; i < opts->client_count; i++) {
1434 if (!strcmp(opts->auth_clients[i].username, username)) {
1435 auth_client = &opts->auth_clients[i];
1436 break;
1437 }
1438 }
1439
1440 if (!auth_client) {
roman78df0fa2023-11-02 10:33:57 +01001441 if (opts->referenced_endpt_name) {
1442 /* client not known by the endpt, but it references another one so try it */
1443 if (nc_server_get_referenced_endpt(opts->referenced_endpt_name, &referenced_endpt)) {
1444 ERRINT;
1445 return 1;
1446 }
1447
1448 return nc_session_ssh_msg(session, referenced_endpt->opts.ssh, msg, state);
Michal Vasko086311b2016-01-08 09:53:11 +01001449 }
1450
roman545879e2024-01-19 14:43:46 +01001451 /* user not known, set his authentication methods to public key only so that
1452 * there is no interaction and it will simply be denied */
romanf578cd52023-10-19 09:47:40 +02001453 ERR(NULL, "User \"%s\" not known by the server.", username);
roman545879e2024-01-19 14:43:46 +01001454 ssh_set_auth_methods(session->ti.libssh.session, SSH_AUTH_METHOD_PUBLICKEY);
romanf578cd52023-10-19 09:47:40 +02001455 ssh_message_reply_default(msg);
1456 return 0;
1457 }
1458
1459 if (!session->username) {
Michal Vasko93224072021-11-09 12:14:28 +01001460 session->username = strdup(username);
romanf578cd52023-10-19 09:47:40 +02001461
1462 /* configure and count accepted auth methods */
1463 if (auth_client->store == NC_STORE_LOCAL) {
1464 if (auth_client->pubkey_count) {
1465 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1466 }
romana9ec3362023-12-21 10:59:57 +01001467 } else if (auth_client->store == NC_STORE_TRUSTSTORE) {
1468 if (auth_client->ts_ref) {
1469 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1470 }
1471 } else if (auth_client->store == NC_STORE_SYSTEM) {
romanf578cd52023-10-19 09:47:40 +02001472 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1473 }
1474 if (auth_client->password) {
1475 state->auth_method_count++;
1476 libssh_auth_methods |= SSH_AUTH_METHOD_PASSWORD;
1477 }
roman808f3f62023-11-23 16:01:04 +01001478 if (auth_client->kb_int_enabled) {
romanf578cd52023-10-19 09:47:40 +02001479 state->auth_method_count++;
1480 libssh_auth_methods |= SSH_AUTH_METHOD_INTERACTIVE;
1481 }
roman808f3f62023-11-23 16:01:04 +01001482 if (auth_client->none_enabled) {
romanf578cd52023-10-19 09:47:40 +02001483 libssh_auth_methods |= SSH_AUTH_METHOD_NONE;
1484 }
1485
1486 if (libssh_auth_methods & SSH_AUTH_METHOD_PUBLICKEY) {
1487 state->auth_method_count++;
1488 }
1489
1490 ssh_set_auth_methods(session->ti.libssh.session, libssh_auth_methods);
1491 } else {
Michal Vasko086311b2016-01-08 09:53:11 +01001492 if (strcmp(username, session->username)) {
romanf578cd52023-10-19 09:47:40 +02001493 /* changing username not allowed */
Michal Vasko05532772021-06-03 12:12:38 +02001494 ERR(session, "User \"%s\" changed its username to \"%s\".", session->username, username);
Michal Vasko086311b2016-01-08 09:53:11 +01001495 session->status = NC_STATUS_INVALID;
Michal Vasko428087d2016-01-14 16:04:28 +01001496 session->term_reason = NC_SESSION_TERM_OTHER;
Michal Vasko086311b2016-01-08 09:53:11 +01001497 return 1;
1498 }
1499 }
1500
romanf578cd52023-10-19 09:47:40 +02001501 /* try authenticating, the user must authenticate via all of his configured auth methods */
Michal Vasko086311b2016-01-08 09:53:11 +01001502 if (subtype == SSH_AUTH_METHOD_NONE) {
romanf578cd52023-10-19 09:47:40 +02001503 nc_sshcb_auth_none(session, auth_client, msg);
1504 ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001505 } else if (subtype == SSH_AUTH_METHOD_PASSWORD) {
romanf578cd52023-10-19 09:47:40 +02001506 ret = nc_sshcb_auth_password(session, auth_client, msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001507 } else if (subtype == SSH_AUTH_METHOD_PUBLICKEY) {
romanf578cd52023-10-19 09:47:40 +02001508 ret = nc_sshcb_auth_pubkey(session, auth_client, msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001509 } else if (subtype == SSH_AUTH_METHOD_INTERACTIVE) {
romane5675b12024-03-05 14:26:23 +01001510 ret = nc_sshcb_auth_kbdint(session, auth_client, msg);
roman4f9e4422024-03-21 10:58:41 +01001511 } else {
1512 VRB(session, "Authentication method \"%s\" not supported.", str_subtype);
1513 ssh_message_reply_default(msg);
1514 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001515 }
romanf578cd52023-10-19 09:47:40 +02001516
1517 if (!ret) {
1518 state->auth_success_count++;
1519 }
1520
1521 if (!ret && (state->auth_success_count < state->auth_method_count)) {
1522 /* success, but he needs to do another method */
1523 VRB(session, "User \"%s\" partially authenticated, but still needs to authenticate via the rest of his configured methods.", username);
1524 ssh_message_auth_reply_success(msg, 1);
1525 } else if (!ret && (state->auth_success_count == state->auth_method_count)) {
1526 /* authenticated */
1527 ssh_message_auth_reply_success(msg, 0);
1528 session->flags |= NC_SESSION_SSH_AUTHENTICATED;
1529 VRB(session, "User \"%s\" authenticated.", username);
1530 }
1531
1532 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001533 } else if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
Michal Vasko0df67562016-01-21 15:50:11 +01001534 if ((type == SSH_REQUEST_CHANNEL_OPEN) && ((enum ssh_channel_type_e)subtype == SSH_CHANNEL_SESSION)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001535 if (nc_sshcb_channel_open(session, msg)) {
Michal Vasko086311b2016-01-08 09:53:11 +01001536 ssh_message_reply_default(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001537 }
Michal Vasko086311b2016-01-08 09:53:11 +01001538 return 0;
Michal Vasko96164bf2016-01-21 15:41:58 +01001539
Michal Vasko0df67562016-01-21 15:50:11 +01001540 } else if ((type == SSH_REQUEST_CHANNEL) && ((enum ssh_channel_requests_e)subtype == SSH_CHANNEL_REQUEST_SUBSYSTEM)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001541 if (nc_sshcb_channel_subsystem(session, ssh_message_channel_request_channel(msg),
1542 ssh_message_channel_request_subsystem(msg))) {
Michal Vasko086311b2016-01-08 09:53:11 +01001543 ssh_message_reply_default(msg);
Michal Vasko96164bf2016-01-21 15:41:58 +01001544 } else {
1545 ssh_message_channel_request_reply_success(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001546 }
1547 return 0;
1548 }
1549 }
1550
1551 /* we did not process it */
1552 return 1;
1553}
1554
Michal Vasko1a38c862016-01-15 15:50:07 +01001555/* ret 1 on success, 0 on timeout, -1 on error */
Michal Vasko086311b2016-01-08 09:53:11 +01001556static int
romanf578cd52023-10-19 09:47:40 +02001557nc_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 +01001558{
roman6ece9c52022-06-22 09:29:17 +02001559 struct timespec ts_timeout;
romanf578cd52023-10-19 09:47:40 +02001560 ssh_message msg;
Michal Vasko086311b2016-01-08 09:53:11 +01001561
romanf578cd52023-10-19 09:47:40 +02001562 if (timeout) {
1563 nc_timeouttime_get(&ts_timeout, timeout * 1000);
Michal Vasko36c7be82017-02-22 13:37:59 +01001564 }
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001565 while (1) {
1566 if (!nc_session_is_connected(session)) {
romanf578cd52023-10-19 09:47:40 +02001567 ERR(session, "Communication SSH socket unexpectedly closed.");
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001568 return -1;
1569 }
1570
romanf578cd52023-10-19 09:47:40 +02001571 msg = ssh_message_get(session->ti.libssh.session);
1572 if (msg) {
1573 if (nc_session_ssh_msg(session, opts, msg, NULL)) {
1574 ssh_message_reply_default(msg);
1575 }
1576 ssh_message_free(msg);
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001577 }
1578
romanf578cd52023-10-19 09:47:40 +02001579 if (session->ti.libssh.channel && session->flags & NC_SESSION_SSH_SUBSYS_NETCONF) {
Michal Vasko1a38c862016-01-15 15:50:07 +01001580 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001581 }
1582
Michal Vasko086311b2016-01-08 09:53:11 +01001583 usleep(NC_TIMEOUT_STEP);
roman0b7e6982024-04-29 11:11:52 +02001584 if (timeout && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
roman6ece9c52022-06-22 09:29:17 +02001585 /* timeout */
1586 ERR(session, "Failed to start \"netconf\" SSH subsystem for too long, disconnecting.");
1587 break;
Michal Vasko36c7be82017-02-22 13:37:59 +01001588 }
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001589 }
Michal Vasko086311b2016-01-08 09:53:11 +01001590
Michal Vasko1a38c862016-01-15 15:50:07 +01001591 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001592}
1593
Michal Vaskof3c41e32022-09-09 11:22:21 +02001594/**
1595 * @brief Set hostkeys to be used for an SSH bind.
1596 *
1597 * @param[in] sbind SSH bind to use.
1598 * @param[in] hostkeys Array of hostkeys.
1599 * @param[in] hostkey_count Count of @p hostkeys.
1600 * @return 0 on success.
1601 * @return -1 on error.
1602 */
Michal Vasko4c1fb492017-01-30 14:31:07 +01001603static int
romanf578cd52023-10-19 09:47:40 +02001604nc_ssh_bind_add_hostkeys(ssh_bind sbind, struct nc_server_ssh_opts *opts, uint16_t hostkey_count)
Michal Vasko4c1fb492017-01-30 14:31:07 +01001605{
romanf578cd52023-10-19 09:47:40 +02001606 uint16_t i;
roman6dfdc0d2023-11-09 13:25:27 +01001607 char *privkey_path;
Michal Vaskoddce1212019-05-24 09:58:49 +02001608 int ret;
romanf578cd52023-10-19 09:47:40 +02001609 struct nc_asymmetric_key *key = NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +01001610
1611 for (i = 0; i < hostkey_count; ++i) {
roman6dfdc0d2023-11-09 13:25:27 +01001612 privkey_path = NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +01001613
romanf578cd52023-10-19 09:47:40 +02001614 /* get the asymmetric key */
1615 if (opts->hostkeys[i].store == NC_STORE_LOCAL) {
1616 /* stored locally */
1617 key = &opts->hostkeys[i].key;
1618 } else {
1619 /* keystore reference, need to get it */
1620 if (nc_server_ssh_ks_ref_get_key(opts->hostkeys[i].ks_ref, &key)) {
Michal Vasko4c1fb492017-01-30 14:31:07 +01001621 return -1;
1622 }
1623 }
1624
romanf578cd52023-10-19 09:47:40 +02001625 privkey_path = base64der_privkey_to_tmp_file(key->privkey_data, nc_privkey_format_to_str(key->privkey_type));
1626 if (!privkey_path) {
1627 ERR(NULL, "Temporarily storing a host key into a file failed (%s).", strerror(errno));
1628 return -1;
1629 }
1630
Michal Vasko4c1fb492017-01-30 14:31:07 +01001631 ret = ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY, privkey_path);
1632
1633 /* cleanup */
roman6dfdc0d2023-11-09 13:25:27 +01001634 if (unlink(privkey_path)) {
Michal Vasko05532772021-06-03 12:12:38 +02001635 WRN(NULL, "Removing a temporary host key file \"%s\" failed (%s).", privkey_path, strerror(errno));
Michal Vasko4c1fb492017-01-30 14:31:07 +01001636 }
Michal Vasko4c1fb492017-01-30 14:31:07 +01001637
1638 if (ret != SSH_OK) {
romanf578cd52023-10-19 09:47:40 +02001639 ERR(NULL, "Failed to set hostkey \"%s\" (%s).", opts->hostkeys[i].name, privkey_path);
Michal Vasko80075de2017-07-10 11:38:52 +02001640 }
1641 free(privkey_path);
1642
1643 if (ret != SSH_OK) {
Michal Vasko4c1fb492017-01-30 14:31:07 +01001644 return -1;
1645 }
1646 }
1647
1648 return 0;
1649}
1650
Michal Vasko09d700f2022-09-08 10:21:40 +02001651static int
romanf578cd52023-10-19 09:47:40 +02001652nc_accept_ssh_session_auth(struct nc_session *session, struct nc_server_ssh_opts *opts)
Michal Vasko3031aae2016-01-27 16:07:18 +01001653{
roman6ece9c52022-06-22 09:29:17 +02001654 struct timespec ts_timeout;
roman41a11e42022-06-22 09:27:08 +02001655 ssh_message msg;
romanf578cd52023-10-19 09:47:40 +02001656 struct nc_auth_state state = {0};
Michal Vasko086311b2016-01-08 09:53:11 +01001657
Michal Vasko086311b2016-01-08 09:53:11 +01001658 /* authenticate */
Michal Vasko36c7be82017-02-22 13:37:59 +01001659 if (opts->auth_timeout) {
Michal Vaskod8a74192023-02-06 15:51:50 +01001660 nc_timeouttime_get(&ts_timeout, opts->auth_timeout * 1000);
Michal Vasko36c7be82017-02-22 13:37:59 +01001661 }
1662 while (1) {
Michal Vasko2a7d4732016-01-15 09:24:46 +01001663 if (!nc_session_is_connected(session)) {
Michal Vasko05532772021-06-03 12:12:38 +02001664 ERR(session, "Communication SSH socket unexpectedly closed.");
Michal Vasko2a7d4732016-01-15 09:24:46 +01001665 return -1;
1666 }
1667
roman41a11e42022-06-22 09:27:08 +02001668 msg = ssh_message_get(session->ti.libssh.session);
1669 if (msg) {
romanf578cd52023-10-19 09:47:40 +02001670 if (nc_session_ssh_msg(session, opts, msg, &state)) {
roman41a11e42022-06-22 09:27:08 +02001671 ssh_message_reply_default(msg);
1672 }
1673 ssh_message_free(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001674 }
1675
Michal Vasko36c7be82017-02-22 13:37:59 +01001676 if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
1677 break;
1678 }
1679
Michal Vasko145ae672017-02-07 10:57:27 +01001680 if (session->opts.server.ssh_auth_attempts >= opts->auth_attempts) {
Michal Vasko05532772021-06-03 12:12:38 +02001681 ERR(session, "Too many failed authentication attempts of user \"%s\".", session->username);
Michal Vasko145ae672017-02-07 10:57:27 +01001682 return -1;
1683 }
1684
Michal Vasko086311b2016-01-08 09:53:11 +01001685 usleep(NC_TIMEOUT_STEP);
romanea0edaa2023-10-26 12:16:25 +02001686 if (opts->auth_timeout && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
roman6ece9c52022-06-22 09:29:17 +02001687 /* timeout */
1688 break;
Michal Vasko36c7be82017-02-22 13:37:59 +01001689 }
1690 }
Michal Vasko086311b2016-01-08 09:53:11 +01001691
1692 if (!(session->flags & NC_SESSION_SSH_AUTHENTICATED)) {
1693 /* timeout */
Michal Vaskoc13da702017-02-07 10:57:57 +01001694 if (session->username) {
Michal Vasko05532772021-06-03 12:12:38 +02001695 ERR(session, "User \"%s\" failed to authenticate for too long, disconnecting.", session->username);
Michal Vaskoc13da702017-02-07 10:57:57 +01001696 } else {
Michal Vasko05532772021-06-03 12:12:38 +02001697 ERR(session, "User failed to authenticate for too long, disconnecting.");
Michal Vaskoc13da702017-02-07 10:57:57 +01001698 }
Michal Vasko1a38c862016-01-15 15:50:07 +01001699 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001700 }
1701
Michal Vasko09d700f2022-09-08 10:21:40 +02001702 return 1;
1703}
1704
1705int
romanf578cd52023-10-19 09:47:40 +02001706nc_accept_ssh_session(struct nc_session *session, struct nc_server_ssh_opts *opts, int sock, int timeout)
Michal Vasko09d700f2022-09-08 10:21:40 +02001707{
1708 ssh_bind sbind = NULL;
Michal Vasko09d700f2022-09-08 10:21:40 +02001709 int rc = 1, r;
1710 struct timespec ts_timeout;
roman4cc0cd52023-04-14 09:12:29 +02001711 const char *err_msg;
Michal Vasko09d700f2022-09-08 10:21:40 +02001712
Michal Vasko09d700f2022-09-08 10:21:40 +02001713 /* other transport-specific data */
roman506354a2024-04-11 09:37:22 +02001714 session->ti_type = NC_TI_SSH;
Michal Vasko09d700f2022-09-08 10:21:40 +02001715 session->ti.libssh.session = ssh_new();
1716 if (!session->ti.libssh.session) {
1717 ERR(NULL, "Failed to initialize a new SSH session.");
1718 rc = -1;
1719 goto cleanup;
1720 }
1721
1722 sbind = ssh_bind_new();
1723 if (!sbind) {
1724 ERR(session, "Failed to create an SSH bind.");
1725 rc = -1;
1726 goto cleanup;
1727 }
1728
1729 /* configure host keys */
romanf578cd52023-10-19 09:47:40 +02001730 if (nc_ssh_bind_add_hostkeys(sbind, opts, opts->hostkey_count)) {
1731 rc = -1;
1732 goto cleanup;
1733 }
1734
1735 /* configure supported algorithms */
1736 if (opts->hostkey_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY_ALGORITHMS, opts->hostkey_algs)) {
1737 rc = -1;
1738 goto cleanup;
1739 }
1740 if (opts->encryption_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_CIPHERS_S_C, opts->encryption_algs)) {
1741 rc = -1;
1742 goto cleanup;
1743 }
1744 if (opts->kex_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_KEY_EXCHANGE, opts->kex_algs)) {
1745 rc = -1;
1746 goto cleanup;
1747 }
1748 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 +02001749 rc = -1;
1750 goto cleanup;
1751 }
1752
1753 /* accept new connection on the bind */
1754 if (ssh_bind_accept_fd(sbind, session->ti.libssh.session, sock) == SSH_ERROR) {
1755 ERR(session, "SSH failed to accept a new connection (%s).", ssh_get_error(sbind));
1756 rc = -1;
1757 goto cleanup;
1758 }
1759 sock = -1;
1760
romanf578cd52023-10-19 09:47:40 +02001761 /* set to non-blocking */
Michal Vasko09d700f2022-09-08 10:21:40 +02001762 ssh_set_blocking(session->ti.libssh.session, 0);
1763
1764 if (timeout > -1) {
Michal Vaskod8a74192023-02-06 15:51:50 +01001765 nc_timeouttime_get(&ts_timeout, timeout);
Michal Vasko09d700f2022-09-08 10:21:40 +02001766 }
1767 while ((r = ssh_handle_key_exchange(session->ti.libssh.session)) == SSH_AGAIN) {
1768 /* this tends to take longer */
1769 usleep(NC_TIMEOUT_STEP * 20);
Michal Vaskod8a74192023-02-06 15:51:50 +01001770 if ((timeout > -1) && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001771 break;
1772 }
1773 }
1774 if (r == SSH_AGAIN) {
1775 ERR(session, "SSH key exchange timeout.");
1776 rc = 0;
1777 goto cleanup;
1778 } else if (r != SSH_OK) {
roman4cc0cd52023-04-14 09:12:29 +02001779 err_msg = ssh_get_error(session->ti.libssh.session);
1780 if (err_msg[0] == '\0') {
1781 err_msg = "hostkey algorithm generated from the hostkey most likely not found in the set of configured hostkey algorithms";
1782 }
1783 ERR(session, "SSH key exchange error (%s).", err_msg);
Michal Vasko09d700f2022-09-08 10:21:40 +02001784 rc = -1;
1785 goto cleanup;
1786 }
1787
romane5675b12024-03-05 14:26:23 +01001788 /* authenticate, store auth_timeout in session so we can retrieve it in kb interactive API */
1789 session->data = &opts->auth_timeout;
1790 rc = nc_accept_ssh_session_auth(session, opts);
1791 session->data = NULL;
1792 if (rc != 1) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001793 goto cleanup;
1794 }
1795
Michal Vasko09d700f2022-09-08 10:21:40 +02001796 /* open channel and request 'netconf' subsystem */
romanf578cd52023-10-19 09:47:40 +02001797 if ((rc = nc_accept_ssh_session_open_netconf_channel(session, opts, timeout)) != 1) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001798 goto cleanup;
Michal Vasko086311b2016-01-08 09:53:11 +01001799 }
1800
Michal Vasko09d700f2022-09-08 10:21:40 +02001801cleanup:
1802 if (sock > -1) {
1803 close(sock);
1804 }
1805 ssh_bind_free(sbind);
1806 return rc;
Michal Vasko086311b2016-01-08 09:53:11 +01001807}
1808
Michal Vasko71090fc2016-05-24 16:37:28 +02001809API NC_MSG_TYPE
1810nc_session_accept_ssh_channel(struct nc_session *orig_session, struct nc_session **session)
1811{
1812 NC_MSG_TYPE msgtype;
1813 struct nc_session *new_session = NULL;
Michal Vasko9f6275e2017-10-05 13:50:05 +02001814 struct timespec ts_cur;
Michal Vasko71090fc2016-05-24 16:37:28 +02001815
roman40672412023-05-04 11:10:22 +02001816 NC_CHECK_ARG_RET(orig_session, orig_session, session, NC_MSG_ERROR);
Michal Vasko71090fc2016-05-24 16:37:28 +02001817
roman506354a2024-04-11 09:37:22 +02001818 if ((orig_session->status == NC_STATUS_RUNNING) && (orig_session->ti_type == NC_TI_SSH) &&
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001819 orig_session->ti.libssh.next) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001820 for (new_session = orig_session->ti.libssh.next;
1821 new_session != orig_session;
1822 new_session = new_session->ti.libssh.next) {
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001823 if ((new_session->status == NC_STATUS_STARTING) && new_session->ti.libssh.channel &&
1824 (new_session->flags & NC_SESSION_SSH_SUBSYS_NETCONF)) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001825 /* we found our session */
1826 break;
1827 }
1828 }
1829 if (new_session == orig_session) {
1830 new_session = NULL;
1831 }
1832 }
1833
1834 if (!new_session) {
Michal Vasko05532772021-06-03 12:12:38 +02001835 ERR(orig_session, "Session does not have a NETCONF SSH channel ready.");
Michal Vasko71090fc2016-05-24 16:37:28 +02001836 return NC_MSG_ERROR;
1837 }
1838
1839 /* assign new SID atomically */
Michal Vasko5bd4a3f2021-06-17 16:40:10 +02001840 new_session->id = ATOMIC_INC_RELAXED(server_opts.new_session_id);
Michal Vasko71090fc2016-05-24 16:37:28 +02001841
1842 /* NETCONF handshake */
Michal Vasko131120a2018-05-29 15:44:02 +02001843 msgtype = nc_handshake_io(new_session);
Michal Vasko71090fc2016-05-24 16:37:28 +02001844 if (msgtype != NC_MSG_HELLO) {
1845 return msgtype;
1846 }
1847
Michal Vaskod8a74192023-02-06 15:51:50 +01001848 nc_realtime_get(&ts_cur);
roman44efa322023-11-03 13:57:25 +01001849 new_session->opts.server.session_start = ts_cur;
Michal Vaskod8a74192023-02-06 15:51:50 +01001850 nc_timeouttime_get(&ts_cur, 0);
Michal Vasko9f6275e2017-10-05 13:50:05 +02001851 new_session->opts.server.last_rpc = ts_cur.tv_sec;
Michal Vasko71090fc2016-05-24 16:37:28 +02001852 new_session->status = NC_STATUS_RUNNING;
1853 *session = new_session;
1854
1855 return msgtype;
1856}
1857
1858API NC_MSG_TYPE
Michal Vasko96164bf2016-01-21 15:41:58 +01001859nc_ps_accept_ssh_channel(struct nc_pollsession *ps, struct nc_session **session)
Michal Vasko086311b2016-01-08 09:53:11 +01001860{
Michal Vaskobdcf2362016-07-26 11:35:43 +02001861 uint8_t q_id;
Michal Vasko71090fc2016-05-24 16:37:28 +02001862 NC_MSG_TYPE msgtype;
Michal Vaskoe4300a82017-05-24 10:35:42 +02001863 struct nc_session *new_session = NULL, *cur_session;
Michal Vasko9f6275e2017-10-05 13:50:05 +02001864 struct timespec ts_cur;
Michal Vaskoc61c4492016-01-25 11:13:34 +01001865 uint16_t i;
Michal Vasko086311b2016-01-08 09:53:11 +01001866
roman40672412023-05-04 11:10:22 +02001867 NC_CHECK_ARG_RET(NULL, ps, session, NC_MSG_ERROR);
Michal Vasko086311b2016-01-08 09:53:11 +01001868
Michal Vasko48a63ed2016-03-01 09:48:21 +01001869 /* LOCK */
Michal Vasko227f8ff2016-07-26 14:08:59 +02001870 if (nc_ps_lock(ps, &q_id, __func__)) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001871 return NC_MSG_ERROR;
Michal Vaskof04a52a2016-04-07 10:52:10 +02001872 }
Michal Vasko48a63ed2016-03-01 09:48:21 +01001873
Michal Vasko96164bf2016-01-21 15:41:58 +01001874 for (i = 0; i < ps->session_count; ++i) {
fanchanghu3d4e7212017-08-09 09:42:30 +08001875 cur_session = ps->sessions[i]->session;
roman506354a2024-04-11 09:37:22 +02001876 if ((cur_session->status == NC_STATUS_RUNNING) && (cur_session->ti_type == NC_TI_SSH) &&
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001877 cur_session->ti.libssh.next) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001878 /* an SSH session with more channels */
Michal Vaskoe4300a82017-05-24 10:35:42 +02001879 for (new_session = cur_session->ti.libssh.next;
1880 new_session != cur_session;
Michal Vasko96164bf2016-01-21 15:41:58 +01001881 new_session = new_session->ti.libssh.next) {
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001882 if ((new_session->status == NC_STATUS_STARTING) && new_session->ti.libssh.channel &&
1883 (new_session->flags & NC_SESSION_SSH_SUBSYS_NETCONF)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001884 /* we found our session */
1885 break;
1886 }
1887 }
Michal Vaskoe4300a82017-05-24 10:35:42 +02001888 if (new_session != cur_session) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001889 break;
1890 }
Michal Vaskofb89d772016-01-08 12:25:35 +01001891
Michal Vasko96164bf2016-01-21 15:41:58 +01001892 new_session = NULL;
1893 }
1894 }
Michal Vaskofb89d772016-01-08 12:25:35 +01001895
Michal Vasko48a63ed2016-03-01 09:48:21 +01001896 /* UNLOCK */
Michal Vasko227f8ff2016-07-26 14:08:59 +02001897 nc_ps_unlock(ps, q_id, __func__);
Michal Vasko48a63ed2016-03-01 09:48:21 +01001898
Michal Vasko96164bf2016-01-21 15:41:58 +01001899 if (!new_session) {
Michal Vasko05532772021-06-03 12:12:38 +02001900 ERR(NULL, "No session with a NETCONF SSH channel ready was found.");
Michal Vasko71090fc2016-05-24 16:37:28 +02001901 return NC_MSG_ERROR;
Michal Vasko96164bf2016-01-21 15:41:58 +01001902 }
1903
1904 /* assign new SID atomically */
Michal Vasko5bd4a3f2021-06-17 16:40:10 +02001905 new_session->id = ATOMIC_INC_RELAXED(server_opts.new_session_id);
Michal Vaskofb89d772016-01-08 12:25:35 +01001906
Michal Vasko086311b2016-01-08 09:53:11 +01001907 /* NETCONF handshake */
Michal Vasko131120a2018-05-29 15:44:02 +02001908 msgtype = nc_handshake_io(new_session);
Michal Vasko71090fc2016-05-24 16:37:28 +02001909 if (msgtype != NC_MSG_HELLO) {
1910 return msgtype;
Michal Vasko086311b2016-01-08 09:53:11 +01001911 }
Michal Vasko48a63ed2016-03-01 09:48:21 +01001912
Michal Vaskod8a74192023-02-06 15:51:50 +01001913 nc_realtime_get(&ts_cur);
roman44efa322023-11-03 13:57:25 +01001914 new_session->opts.server.session_start = ts_cur;
Michal Vaskod8a74192023-02-06 15:51:50 +01001915 nc_timeouttime_get(&ts_cur, 0);
Michal Vasko9f6275e2017-10-05 13:50:05 +02001916 new_session->opts.server.last_rpc = ts_cur.tv_sec;
Michal Vasko086311b2016-01-08 09:53:11 +01001917 new_session->status = NC_STATUS_RUNNING;
Michal Vasko96164bf2016-01-21 15:41:58 +01001918 *session = new_session;
Michal Vasko086311b2016-01-08 09:53:11 +01001919
Michal Vasko71090fc2016-05-24 16:37:28 +02001920 return msgtype;
Michal Vasko086311b2016-01-08 09:53:11 +01001921}