blob: e73dfe223cb3e5b1854f79dc80c46e5671aad0b1 [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>
34#include <openssl/bio.h>
35#include <openssl/err.h>
36#include <openssl/evp.h>
Michal Vaskob83a3fa2021-05-26 09:53:42 +020037#include <pwd.h>
romanf578cd52023-10-19 09:47:40 +020038#include <stdint.h>
Michal Vasko086311b2016-01-08 09:53:11 +010039#include <stdlib.h>
40#include <string.h>
Michal Vasko27252692017-03-21 15:34:13 +010041#include <sys/stat.h>
Michal Vaskob83a3fa2021-05-26 09:53:42 +020042#include <sys/types.h>
Michal Vasko9f6275e2017-10-05 13:50:05 +020043#include <time.h>
Claus Klein22091912020-01-20 13:45:47 +010044#include <unistd.h>
Michal Vasko086311b2016-01-08 09:53:11 +010045
Michal Vasko7a20d2e2021-05-19 16:40:23 +020046#include "compat.h"
romanf578cd52023-10-19 09:47:40 +020047#include "log_p.h"
48#include "session.h"
49#include "session_p.h"
Michal Vasko086311b2016-01-08 09:53:11 +010050
51extern struct nc_server_opts server_opts;
Michal Vaskob05053d2016-01-22 16:12:06 +010052
Michal Vasko4c1fb492017-01-30 14:31:07 +010053static char *
romanf578cd52023-10-19 09:47:40 +020054base64der_privkey_to_tmp_file(const char *in, const char *privkey_format)
Michal Vasko086311b2016-01-08 09:53:11 +010055{
Michal Vasko4c1fb492017-01-30 14:31:07 +010056 char path[12] = "/tmp/XXXXXX";
57 int fd, written;
romanf578cd52023-10-19 09:47:40 +020058 unsigned len;
Michal Vasko27252692017-03-21 15:34:13 +010059 mode_t umode;
Michal Vasko4c1fb492017-01-30 14:31:07 +010060 FILE *file;
61
romanf578cd52023-10-19 09:47:40 +020062 NC_CHECK_ARG_RET(NULL, in, NULL);
Michal Vasko086311b2016-01-08 09:53:11 +010063
mekleob31878b2019-09-09 14:10:47 +020064 umode = umask(0177);
Michal Vasko4c1fb492017-01-30 14:31:07 +010065 fd = mkstemp(path);
Michal Vasko27252692017-03-21 15:34:13 +010066 umask(umode);
Michal Vasko4c1fb492017-01-30 14:31:07 +010067 if (fd == -1) {
68 return NULL;
69 }
70
Michal Vasko3964a832018-09-18 14:37:39 +020071 file = fdopen(fd, "w");
Michal Vasko4c1fb492017-01-30 14:31:07 +010072 if (!file) {
73 close(fd);
74 return NULL;
75 }
76
romanf578cd52023-10-19 09:47:40 +020077 /* write header */
romand0fe5952024-03-21 15:59:33 +010078 written = fwrite("-----BEGIN", 1, 10, file);
romanf578cd52023-10-19 09:47:40 +020079 if (privkey_format) {
80 written += fwrite(privkey_format, 1, strlen(privkey_format), file);
romanf578cd52023-10-19 09:47:40 +020081 written += fwrite("PRIVATE KEY-----\n", 1, 17, file);
romand0fe5952024-03-21 15:59:33 +010082 } else {
83 written += fwrite(" PRIVATE KEY-----\n", 1, 18, file);
romanf578cd52023-10-19 09:47:40 +020084 }
Michal Vasko68177b72020-04-27 15:46:53 +020085
romanf578cd52023-10-19 09:47:40 +020086 /* write data */
87 written += fwrite(in, 1, strlen(in), file);
88
89 /* write footer */
romand0fe5952024-03-21 15:59:33 +010090 written += fwrite("\n-----END", 1, 9, file);
romanf578cd52023-10-19 09:47:40 +020091 if (privkey_format) {
92 written += fwrite(privkey_format, 1, strlen(privkey_format), file);
romanf578cd52023-10-19 09:47:40 +020093 written += fwrite("PRIVATE KEY-----", 1, 16, file);
romand0fe5952024-03-21 15:59:33 +010094 } else {
95 written += fwrite(" PRIVATE KEY-----", 1, 17, file);
romanf578cd52023-10-19 09:47:40 +020096 }
97
98 fclose(file);
99
100 /* checksum */
101 if (privkey_format) {
romand0fe5952024-03-21 15:59:33 +0100102 len = 10 + strlen(privkey_format) + 17 + strlen(in) + 9 + strlen(privkey_format) + 16;
romanf578cd52023-10-19 09:47:40 +0200103 } else {
romand0fe5952024-03-21 15:59:33 +0100104 len = 10 + 18 + strlen(in) + 9 + 17;
romanf578cd52023-10-19 09:47:40 +0200105 }
106
107 if ((unsigned)written != len) {
108 unlink(path);
109 return NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +0100110 }
111
112 return strdup(path);
113}
114
115static int
romanf578cd52023-10-19 09:47:40 +0200116nc_server_ssh_ks_ref_get_key(const char *referenced_name, struct nc_asymmetric_key **askey)
Michal Vasko4c1fb492017-01-30 14:31:07 +0100117{
romanf578cd52023-10-19 09:47:40 +0200118 uint16_t i;
119 struct nc_keystore *ks = &server_opts.keystore;
Michal Vaskofbfe8b62017-02-14 10:22:30 +0100120
romanf578cd52023-10-19 09:47:40 +0200121 *askey = NULL;
Michal Vaskod45e25a2016-01-08 15:48:44 +0100122
romanf578cd52023-10-19 09:47:40 +0200123 /* lookup name */
124 for (i = 0; i < ks->asym_key_count; i++) {
125 if (!strcmp(referenced_name, ks->asym_keys[i].name)) {
126 break;
Michal Vaskofbfe8b62017-02-14 10:22:30 +0100127 }
128 }
129
romanf578cd52023-10-19 09:47:40 +0200130 if (i == ks->asym_key_count) {
131 ERR(NULL, "Keystore entry \"%s\" not found.", referenced_name);
132 return 1;
Michal Vaskoe2713da2016-08-22 16:06:40 +0200133 }
Michal Vasko7d255882017-02-09 13:35:08 +0100134
romanf578cd52023-10-19 09:47:40 +0200135 *askey = &ks->asym_keys[i];
136
137 /* check if the referenced public key is SubjectPublicKeyInfo */
138 if ((*askey)->pubkey_data && nc_is_pk_subject_public_key_info((*askey)->pubkey_data)) {
139 ERR(NULL, "The public key of the referenced hostkey \"%s\" is in the SubjectPublicKeyInfo format, "
140 "which is not allowed in the SSH!", referenced_name);
141 return 1;
Michal Vasko7d255882017-02-09 13:35:08 +0100142 }
Michal Vaskoe2713da2016-08-22 16:06:40 +0200143
Michal Vasko5fcc7142016-02-02 12:21:10 +0100144 return 0;
Michal Vaskob05053d2016-01-22 16:12:06 +0100145}
146
romanf578cd52023-10-19 09:47:40 +0200147static int
148nc_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 +0100149{
romanf578cd52023-10-19 09:47:40 +0200150 uint16_t i, j;
151 struct nc_truststore *ts = &server_opts.truststore;
Michal Vasko3031aae2016-01-27 16:07:18 +0100152
romanf578cd52023-10-19 09:47:40 +0200153 *pubkeys = NULL;
154 *pubkey_count = 0;
155
156 /* lookup name */
157 for (i = 0; i < ts->pub_bag_count; i++) {
158 if (!strcmp(referenced_name, ts->pub_bags[i].name)) {
159 break;
160 }
Michal Vasko3031aae2016-01-27 16:07:18 +0100161 }
Michal Vaskoc46b3df2021-07-26 09:30:05 +0200162
romanf578cd52023-10-19 09:47:40 +0200163 if (i == ts->pub_bag_count) {
164 ERR(NULL, "Truststore entry \"%s\" not found.", referenced_name);
165 return 1;
166 }
Michal Vaskoc46b3df2021-07-26 09:30:05 +0200167
romanf578cd52023-10-19 09:47:40 +0200168 /* check if any of the referenced public keys is SubjectPublicKeyInfo */
169 for (j = 0; j < ts->pub_bags[i].pubkey_count; j++) {
170 if (nc_is_pk_subject_public_key_info(ts->pub_bags[i].pubkeys[j].data)) {
171 ERR(NULL, "A public key of the referenced public key bag \"%s\" is in the SubjectPublicKeyInfo format, "
172 "which is not allowed in the SSH!", referenced_name);
173 return 1;
174 }
175 }
Michal Vasko3031aae2016-01-27 16:07:18 +0100176
romanf578cd52023-10-19 09:47:40 +0200177 *pubkeys = ts->pub_bags[i].pubkeys;
178 *pubkey_count = ts->pub_bags[i].pubkey_count;
179 return 0;
Michal Vaskob05053d2016-01-22 16:12:06 +0100180}
181
romana9ec3362023-12-21 10:59:57 +0100182static char *
183nc_server_ssh_uid_to_str(uid_t uid)
184{
185 int buf_len;
186 char *uid_str;
187
188 /* get the number of digits and alloc */
189 buf_len = snprintf(NULL, 0, "%u", uid);
190 uid_str = malloc(buf_len + 1);
191 NC_CHECK_ERRMEM_RET(!uid_str, NULL);
192
193 /* convert to string */
194 sprintf(uid_str, "%u", uid);
195 uid_str[buf_len] = '\0';
196 return uid_str;
197}
198
199static int
200nc_server_ssh_str_append(const char src_c, const char *src_str, int *size, int *idx, char **dst)
201{
202 int src_size, allocate = 0, ret;
203
204 /* get size of char/string we want to append */
205 if (src_str) {
206 src_size = strlen(src_str);
207 } else {
208 src_size = 1;
209 }
210
211 /* check if we have enough space, if not realloc */
212 while ((src_size + *idx) >= *size) {
213 (*size) += 16;
214 allocate = 1;
215 }
216 if (allocate) {
217 *dst = nc_realloc(*dst, *size);
218 NC_CHECK_ERRMEM_RET(!*dst, 1);
219 }
220
221 /* append the char/string */
222 if (src_str) {
223 ret = sprintf(*dst + *idx, "%s", src_str);
224 } else {
225 ret = sprintf(*dst + *idx, "%c", src_c);
226 }
227 if (ret < 0) {
228 return 1;
229 }
230
231 *idx += ret;
232 return 0;
233}
234
235static int
236nc_server_ssh_get_system_keys_path(const char *username, char **out_path)
237{
238 int ret = 0, i, have_percent = 0, size = 0, idx = 0;
239 const char *path_fmt = server_opts.authkey_path_fmt;
240 char *path = NULL, *buf = NULL, *uid = NULL;
241 struct passwd *pw, pw_buf;
242 size_t buf_len = 0;
243
244 /* check if the path format contains any tokens */
245 if (strstr(path_fmt, "%h") || strstr(path_fmt, "%U") || strstr(path_fmt, "%u") || strstr(path_fmt, "%%")) {
246 /* get pw */
247 pw = nc_getpw(0, username, &pw_buf, &buf, &buf_len);
248 if (!pw) {
249 ERR(NULL, "Unable to get passwd entry for user \"%s\".", username);
250 ret = 1;
251 goto cleanup;
252 }
253
254 /* convert UID to a string */
255 uid = nc_server_ssh_uid_to_str(pw->pw_uid);
256 if (!uid) {
257 ret = 1;
258 goto cleanup;
259 }
260 } else {
261 /* no tokens, just copy the path and return */
262 *out_path = strdup(path_fmt);
263 NC_CHECK_ERRMEM_RET(!*out_path, 1);
264 goto cleanup;
265 }
266
267 /* go over characters from format, copy them to path and interpret tokens correctly */
268 for (i = 0; path_fmt[i]; i++) {
269 if (have_percent) {
270 /* special token, need to convert it */
271 if (path_fmt[i] == '%') {
272 ret = nc_server_ssh_str_append('%', NULL, &size, &idx, &path);
273 } else if (path_fmt[i] == 'h') {
274 /* user home */
275 ret = nc_server_ssh_str_append(0, pw->pw_dir, &size, &idx, &path);
276 } else if (path_fmt[i] == 'u') {
277 /* username */
278 ret = nc_server_ssh_str_append(0, username, &size, &idx, &path);
279 } else if (path_fmt[i] == 'U') {
280 /* UID */
281 ret = nc_server_ssh_str_append(0, uid, &size, &idx, &path);
282 } else {
283 ERR(NULL, "Failed to parse system public keys path format \"%s\".", server_opts.authkey_path_fmt);
284 ret = 1;
285 }
286
287 have_percent = 0;
288 } else {
289 if (path_fmt[i] == '%') {
290 have_percent = 1;
291 } else {
292 /* ordinary character with no meaning */
293 ret = nc_server_ssh_str_append(path_fmt[i], NULL, &size, &idx, &path);
294 }
295 }
296
297 if (ret) {
298 free(path);
299 goto cleanup;
300 }
301 }
302
303 *out_path = path;
304cleanup:
305 free(uid);
306 free(buf);
307 return ret;
308}
309
310/* reads public keys from authorized_keys-like file */
311static int
312nc_server_ssh_read_authorized_keys_file(const char *path, struct nc_public_key **pubkeys, uint16_t *pubkey_count)
313{
314 int ret = 0, line_num = 0;
315 FILE *f = NULL;
316 char *line = NULL, *ptr, *ptr2;
317 size_t n;
318 enum ssh_keytypes_e ktype;
319
320 NC_CHECK_ARG_RET(NULL, path, pubkeys, 1);
321
322 *pubkeys = NULL;
323 *pubkey_count = 0;
324
325 f = fopen(path, "r");
326 if (!f) {
327 ERR(NULL, "Unable to open \"%s\" (%s).", path, strerror(errno));
328 ret = 1;
329 goto cleanup;
330 }
331
332 while (getline(&line, &n, f) > -1) {
333 ++line_num;
334 if ((line[0] == '#') || (line[0] == '\n')) {
335 /* comment or empty line */
336 continue;
337 }
338
339 /* separate key type */
340 ptr = line;
341 for (ptr2 = ptr; ptr2[0] && !isspace(ptr2[0]); ptr2++) {}
342 if (!ptr2[0]) {
343 ERR(NULL, "Invalid format of authorized keys file \"%s\" on line %d.", path, line_num);
344 ret = 1;
345 goto cleanup;
346 }
347 ptr2[0] = '\0';
348
349 /* detect key type */
350 ktype = ssh_key_type_from_name(ptr);
351 if ((ktype != SSH_KEYTYPE_RSA) && (ktype != SSH_KEYTYPE_ECDSA_P256) && (ktype != SSH_KEYTYPE_ECDSA_P384) &&
352 (ktype != SSH_KEYTYPE_ECDSA_P521) && (ktype != SSH_KEYTYPE_ED25519)) {
353 WRN(NULL, "Unsupported key type \"%s\" in authorized keys file \"%s\" on line %d.", ptr, path, line_num);
354 continue;
355 }
356
357 /* get key data */
358 ptr = ptr2 + 1;
359 for (ptr2 = ptr; ptr2[0] && !isspace(ptr2[0]); ptr2++) {}
360 ptr2[0] = '\0';
361
362 /* add the key */
363 *pubkeys = nc_realloc(*pubkeys, (*pubkey_count + 1) * sizeof **pubkeys);
364 NC_CHECK_ERRMEM_GOTO(!(*pubkeys), ret = 1, cleanup);
365 ret = asprintf(&(*pubkeys)[*pubkey_count].name, "authorized_key_%" PRIu16, *pubkey_count);
366 NC_CHECK_ERRMEM_GOTO(ret == -1, (*pubkeys)[*pubkey_count].name = NULL; ret = 1, cleanup);
367 (*pubkeys)[*pubkey_count].type = NC_PUBKEY_FORMAT_SSH;
368 (*pubkeys)[*pubkey_count].data = strdup(ptr);
369 NC_CHECK_ERRMEM_GOTO(!(*pubkeys)[*pubkey_count].data, ret = 1, cleanup);
370 (*pubkey_count)++;
371 }
372
373 /* ok */
374 ret = 0;
375cleanup:
376 if (f) {
377 fclose(f);
378 }
379 free(line);
380 return ret;
381}
382
383static int
384nc_server_ssh_get_system_keys(const char *username, struct nc_public_key **pubkeys, uint16_t *pubkey_count)
385{
386 int ret = 0;
387 char *path = NULL;
388
389 /* convert the path format to get the actual path */
390 ret = nc_server_ssh_get_system_keys_path(username, &path);
391 if (ret) {
392 ERR(NULL, "Getting system keys path failed.");
393 goto cleanup;
394 }
395
396 /* get the keys */
397 ret = nc_server_ssh_read_authorized_keys_file(path, pubkeys, pubkey_count);
398 if (ret) {
399 ERR(NULL, "Reading system keys failed.");
400 goto cleanup;
401 }
402
403cleanup:
404 free(path);
405 return ret;
406}
407
Michal Vaskof3c41e32022-09-09 11:22:21 +0200408/**
409 * @brief Compare hashed password with a cleartext password for a match.
410 *
411 * @param[in] pass_hash Hashed password.
412 * @param[in] pass_clear Cleartext password.
413 * @return 0 on match.
414 * @return non-zero if not a match.
415 */
Michal Vasko086311b2016-01-08 09:53:11 +0100416static int
roman814f5112023-10-19 15:51:16 +0200417auth_password_compare_pwd(const char *stored_pw, const char *received_pw)
Michal Vasko086311b2016-01-08 09:53:11 +0100418{
roman814f5112023-10-19 15:51:16 +0200419 char *received_pw_hash = NULL;
roman8b1a6c32023-10-26 13:35:22 +0200420 struct crypt_data cdata = {0};
Michal Vasko086311b2016-01-08 09:53:11 +0100421
roman814f5112023-10-19 15:51:16 +0200422 if (!stored_pw[0]) {
423 if (!received_pw[0]) {
Michal Vasko05532772021-06-03 12:12:38 +0200424 WRN(NULL, "User authentication successful with an empty password!");
Michal Vasko086311b2016-01-08 09:53:11 +0100425 return 0;
426 } else {
427 /* the user did now know he does not need any password,
428 * (which should not be used) so deny authentication */
429 return 1;
430 }
431 }
432
roman814f5112023-10-19 15:51:16 +0200433 if (!strncmp(stored_pw, "$0$", 3)) {
434 /* cleartext password, simply compare the values */
435 return strcmp(stored_pw + 3, received_pw);
436 }
437
roman814f5112023-10-19 15:51:16 +0200438 received_pw_hash = crypt_r(received_pw, stored_pw, &cdata);
roman814f5112023-10-19 15:51:16 +0200439 if (!received_pw_hash) {
roman8b1a6c32023-10-26 13:35:22 +0200440 ERR(NULL, "Hashing the password failed (%s).", strerror(errno));
Andrew Langefeld158d6fd2018-06-11 18:51:44 -0500441 return 1;
442 }
443
roman814f5112023-10-19 15:51:16 +0200444 return strcmp(received_pw_hash, stored_pw);
Michal Vasko086311b2016-01-08 09:53:11 +0100445}
446
romanf578cd52023-10-19 09:47:40 +0200447static int
448nc_sshcb_auth_password(struct nc_session *session, struct nc_auth_client *auth_client, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +0100449{
Michal Vaskoebba7602018-03-23 13:14:08 +0100450 int auth_ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +0100451
roman4f9e4422024-03-21 10:58:41 +0100452 if (!auth_client->password) {
453 VRB(session, "User \"%s\" does not have password method configured, but a request was received.", auth_client->username);
454 } else {
455 auth_ret = auth_password_compare_pwd(auth_client->password, ssh_message_auth_password(msg));
456 }
Michal Vasko086311b2016-01-08 09:53:11 +0100457
romanf578cd52023-10-19 09:47:40 +0200458 if (auth_ret) {
Michal Vaskoebba7602018-03-23 13:14:08 +0100459 ++session->opts.server.ssh_auth_attempts;
Michal Vasko05532772021-06-03 12:12:38 +0200460 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", session->username,
461 session->opts.server.ssh_auth_attempts);
Michal Vaskoebba7602018-03-23 13:14:08 +0100462 ssh_message_reply_default(msg);
463 }
romanf578cd52023-10-19 09:47:40 +0200464
465 return auth_ret;
Michal Vasko086311b2016-01-08 09:53:11 +0100466}
467
romane5675b12024-03-05 14:26:23 +0100468API int
469nc_server_ssh_kbdint_get_nanswers(const struct nc_session *session, ssh_session libssh_session)
romanc6518422023-11-30 16:39:00 +0100470{
471 int ret = 0;
472 struct timespec ts_timeout = {0};
roman56c85c02023-12-07 13:09:28 +0100473 ssh_message reply = NULL;
romane5675b12024-03-05 14:26:23 +0100474 uint16_t auth_timeout = *((uint16_t *)session->data);
475
476 NC_CHECK_ARG_RET(NULL, session, libssh_session, -1);
romanc6518422023-11-30 16:39:00 +0100477
478 if (auth_timeout) {
479 nc_timeouttime_get(&ts_timeout, auth_timeout * 1000);
480 }
481
482 /* wait for answers from the client */
483 do {
484 if (!nc_session_is_connected(session)) {
485 ERR(NULL, "SSH communication socket unexpectedly closed.");
486 ret = -1;
487 goto cleanup;
488 }
489
490 reply = ssh_message_get(libssh_session);
491 if (reply) {
492 break;
493 }
494
495 usleep(NC_TIMEOUT_STEP);
496 } while (auth_timeout && (nc_timeouttime_cur_diff(&ts_timeout) >= 1));
497 if (!reply) {
498 ERR(NULL, "Authentication timeout.");
499 ret = -1;
500 goto cleanup;
501 }
502
503 ret = ssh_userauth_kbdint_getnanswers(libssh_session);
504
505cleanup:
506 ssh_message_free(reply);
507 return ret;
508}
509
Michal Vasko0d81c572022-09-26 10:39:31 +0200510#ifdef HAVE_LIBPAM
511
roman41a11e42022-06-22 09:27:08 +0200512/**
513 * @brief PAM conversation function, which serves as a callback for exchanging messages between the client and a PAM module.
514 *
515 * @param[in] n_messages Number of messages.
516 * @param[in] msg PAM module's messages.
517 * @param[out] resp User responses.
518 * @param[in] appdata_ptr Callback's data.
roman808f3f62023-11-23 16:01:04 +0100519 * @return PAM_SUCCESS on success, PAM_BUF_ERR on memory allocation error, PAM_CONV_ERR otherwise.
roman41a11e42022-06-22 09:27:08 +0200520 */
521static int
522nc_pam_conv_clb(int n_messages, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr)
523{
524 int i, j, t, r = PAM_SUCCESS, n_answers, n_requests = n_messages;
525 const char **prompts = NULL;
526 char *echo = NULL;
527 const char *name = "Keyboard-Interactive Authentication";
528 const char *instruction = "Please enter your authentication token";
529 ssh_message reply = NULL;
530 struct nc_pam_thread_arg *clb_data = appdata_ptr;
531 ssh_session libssh_session;
roman41a11e42022-06-22 09:27:08 +0200532
533 libssh_session = clb_data->session->ti.libssh.session;
roman41a11e42022-06-22 09:27:08 +0200534
535 /* PAM_MAX_NUM_MSG == 32 by default */
536 if ((n_messages <= 0) || (n_messages >= PAM_MAX_NUM_MSG)) {
romanc6518422023-11-30 16:39:00 +0100537 ERR(clb_data->session, "Bad number of PAM messages (#%d).", n_messages);
roman41a11e42022-06-22 09:27:08 +0200538 r = PAM_CONV_ERR;
539 goto cleanup;
540 }
541
542 /* only accepting these 4 types of messages */
543 for (i = 0; i < n_messages; i++) {
544 t = msg[i]->msg_style;
545 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 +0100546 ERR(clb_data->session, "PAM conversation callback received an unexpected type of message.");
roman41a11e42022-06-22 09:27:08 +0200547 r = PAM_CONV_ERR;
548 goto cleanup;
549 }
550 }
551
552 /* display messages with errors and/or some information and count the amount of actual authentication challenges */
553 for (i = 0; i < n_messages; i++) {
554 if (msg[i]->msg_style == PAM_TEXT_INFO) {
romanc6518422023-11-30 16:39:00 +0100555 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 +0200556 n_requests--;
557 }
558 if (msg[i]->msg_style == PAM_ERROR_MSG) {
romanc6518422023-11-30 16:39:00 +0100559 ERR(clb_data->session, "PAM conversation callback received an error message (%s).", msg[i]->msg);
roman41a11e42022-06-22 09:27:08 +0200560 r = PAM_CONV_ERR;
561 goto cleanup;
562 }
563 }
564
565 /* there are no requests left for the user, only messages with some information for the client were sent */
566 if (n_requests <= 0) {
567 r = PAM_SUCCESS;
568 goto cleanup;
569 }
570
571 /* it is the PAM module's responsibility to release both, this array and the responses themselves */
572 *resp = calloc(n_requests, sizeof **resp);
573 prompts = calloc(n_requests, sizeof *prompts);
574 echo = calloc(n_requests, sizeof *echo);
roman3a95bb22023-10-26 11:07:17 +0200575 NC_CHECK_ERRMEM_GOTO(!(*resp) || !prompts || !echo, r = PAM_BUF_ERR, cleanup);
roman41a11e42022-06-22 09:27:08 +0200576
577 /* set the prompts for the user */
578 j = 0;
579 for (i = 0; i < n_messages; i++) {
580 if ((msg[i]->msg_style == PAM_PROMPT_ECHO_ON) || (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF)) {
581 prompts[j++] = msg[i]->msg;
582 }
583 }
584
585 /* iterate over all the messages and adjust the echo array accordingly */
586 j = 0;
587 for (i = 0; i < n_messages; i++) {
588 if (msg[i]->msg_style == PAM_PROMPT_ECHO_ON) {
589 echo[j++] = 1;
590 }
591 if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF) {
592 /* no need to set to 0 because of calloc */
593 j++;
594 }
595 }
596
597 /* print all the keyboard-interactive challenges to the user */
598 r = ssh_message_auth_interactive_request(clb_data->msg, name, instruction, n_requests, prompts, echo);
599 if (r != SSH_OK) {
romanc6518422023-11-30 16:39:00 +0100600 ERR(clb_data->session, "Failed to send an authentication request.");
roman41a11e42022-06-22 09:27:08 +0200601 r = PAM_CONV_ERR;
602 goto cleanup;
603 }
604
romane5675b12024-03-05 14:26:23 +0100605 n_answers = nc_server_ssh_kbdint_get_nanswers(clb_data->session, libssh_session);
romanc6518422023-11-30 16:39:00 +0100606 if (n_answers < 0) {
607 /* timeout or dc */
roman41a11e42022-06-22 09:27:08 +0200608 r = PAM_CONV_ERR;
609 goto cleanup;
romanc6518422023-11-30 16:39:00 +0100610 } else if (n_answers != n_requests) {
611 /* check if the number of answers and requests matches */
612 ERR(clb_data->session, "Expected %d response(s), got %d.", n_requests, n_answers);
roman41a11e42022-06-22 09:27:08 +0200613 r = PAM_CONV_ERR;
614 goto cleanup;
615 }
616
617 /* give the replies to a PAM module */
618 for (i = 0; i < n_answers; i++) {
619 (*resp)[i].resp = strdup(ssh_userauth_kbdint_getanswer(libssh_session, i));
620 /* it should be the caller's responsibility to free this, however if mem alloc fails,
621 * it is safer to free the responses here and set them to NULL */
622 if ((*resp)[i].resp == NULL) {
623 for (j = 0; j < i; j++) {
624 free((*resp)[j].resp);
625 (*resp)[j].resp = NULL;
626 }
627 ERRMEM;
628 r = PAM_BUF_ERR;
629 goto cleanup;
630 }
631 }
632
633cleanup:
634 ssh_message_free(reply);
635 free(prompts);
636 free(echo);
637 return r;
638}
639
640/**
641 * @brief Handles authentication via Linux PAM.
642 *
643 * @param[in] session NETCONF session.
644 * @param[in] ssh_msg SSH message with a keyboard-interactive authentication request.
645 * @return PAM_SUCCESS on success;
646 * @return PAM error otherwise.
647 */
648static int
romane5675b12024-03-05 14:26:23 +0100649nc_pam_auth(struct nc_session *session, struct nc_auth_client *client, ssh_message ssh_msg)
roman41a11e42022-06-22 09:27:08 +0200650{
651 pam_handle_t *pam_h = NULL;
652 int ret;
653 struct nc_pam_thread_arg clb_data;
654 struct pam_conv conv;
655
656 /* structure holding callback's data */
657 clb_data.msg = ssh_msg;
658 clb_data.session = session;
659
660 /* PAM conversation structure holding the callback and it's data */
661 conv.conv = nc_pam_conv_clb;
662 conv.appdata_ptr = &clb_data;
663
roman808f3f62023-11-23 16:01:04 +0100664 if (!server_opts.pam_config_name) {
romanc6518422023-11-30 16:39:00 +0100665 ERR(session, "PAM configuration filename not set.");
romanf578cd52023-10-19 09:47:40 +0200666 ret = 1;
667 goto cleanup;
668 }
669
roman41a11e42022-06-22 09:27:08 +0200670 /* initialize PAM and see if the given configuration file exists */
roman808f3f62023-11-23 16:01:04 +0100671 ret = pam_start(server_opts.pam_config_name, client->username, &conv, &pam_h);
roman41a11e42022-06-22 09:27:08 +0200672 if (ret != PAM_SUCCESS) {
romanc6518422023-11-30 16:39:00 +0100673 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200674 goto cleanup;
675 }
676
677 /* authentication based on the modules listed in the configuration file */
678 ret = pam_authenticate(pam_h, 0);
679 if (ret != PAM_SUCCESS) {
680 if (ret == PAM_ABORT) {
romanc6518422023-11-30 16:39:00 +0100681 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200682 goto cleanup;
683 } else {
romanc6518422023-11-30 16:39:00 +0100684 VRB(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200685 goto cleanup;
686 }
687 }
688
689 /* correct token entered, check other requirements(the time of the day, expired token, ...) */
690 ret = pam_acct_mgmt(pam_h, 0);
691 if ((ret != PAM_SUCCESS) && (ret != PAM_NEW_AUTHTOK_REQD)) {
romanc6518422023-11-30 16:39:00 +0100692 VRB(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200693 goto cleanup;
694 }
695
696 /* if a token has expired a new one will be generated */
697 if (ret == PAM_NEW_AUTHTOK_REQD) {
romanc6518422023-11-30 16:39:00 +0100698 VRB(session, "PAM warning occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200699 ret = pam_chauthtok(pam_h, PAM_CHANGE_EXPIRED_AUTHTOK);
700 if (ret == PAM_SUCCESS) {
romanc6518422023-11-30 16:39:00 +0100701 VRB(session, "The authentication token of user \"%s\" updated successfully.", client->username);
roman41a11e42022-06-22 09:27:08 +0200702 } else {
romanc6518422023-11-30 16:39:00 +0100703 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200704 goto cleanup;
705 }
706 }
707
708cleanup:
709 /* destroy the PAM context */
roman6dfdc0d2023-11-09 13:25:27 +0100710 if (pam_h && (pam_end(pam_h, ret) != PAM_SUCCESS)) {
romancab602e2023-11-24 11:30:32 +0100711 ERR(NULL, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200712 }
713 return ret;
714}
715
romanc6518422023-11-30 16:39:00 +0100716#elif defined (HAVE_SHADOW)
717
718static struct passwd *
719nc_server_ssh_getpwnam(const char *username, struct passwd *pwd_buf, char **buf, size_t *buf_size)
720{
721 struct passwd *pwd = NULL;
722 char *mem;
723 int r = 0;
724
725 do {
726 r = getpwnam_r(username, pwd_buf, *buf, *buf_size, &pwd);
727 if (pwd) {
728 /* entry found */
729 break;
730 }
731
732 if (r == ERANGE) {
733 /* small buffer, enlarge */
734 *buf_size <<= 2;
735 mem = realloc(*buf, *buf_size);
736 if (!mem) {
737 ERRMEM;
738 return NULL;
739 }
740 *buf = mem;
741 }
742 } while (r == ERANGE);
743
744 return pwd;
745}
746
747static struct spwd *
748nc_server_ssh_getspnam(const char *username, struct spwd *spwd_buf, char **buf, size_t *buf_size)
749{
750 struct spwd *spwd = NULL;
751 char *mem;
752 int r = 0;
753
754 do {
755# ifndef __QNXNTO__
756 r = getspnam_r(username, spwd_buf, *buf, *buf_size, &spwd);
757# else
758 spwd = getspnam_r(username, spwd_buf, *buf, *buf_size);
759# endif
760 if (spwd) {
761 /* entry found */
762 break;
763 }
764
765 if (r == ERANGE) {
766 /* small buffer, enlarge */
767 *buf_size <<= 2;
768 mem = realloc(*buf, *buf_size);
769 if (!mem) {
770 ERRMEM;
771 return NULL;
772 }
773 *buf = mem;
774 }
775 } while (r == ERANGE);
776
777 return spwd;
778}
779
780static char *
781nc_server_ssh_get_pwd_hash(const char *username)
782{
783 struct passwd *pwd, pwd_buf;
784 struct spwd *spwd, spwd_buf;
785 char *pass_hash = NULL, *buf = NULL;
786 size_t buf_size = 256;
787
788 buf = malloc(buf_size);
789 NC_CHECK_ERRMEM_GOTO(!buf, , error);
790
791 pwd = nc_server_ssh_getpwnam(username, &pwd_buf, &buf, &buf_size);
792 if (!pwd) {
793 VRB(NULL, "User \"%s\" not found locally.", username);
794 goto error;
795 }
796
797 if (!strcmp(pwd->pw_passwd, "x")) {
798 spwd = nc_server_ssh_getspnam(username, &spwd_buf, &buf, &buf_size);
799 if (!spwd) {
800 VRB(NULL, "Failed to retrieve the shadow entry for \"%s\".", username);
801 goto error;
802 } else if ((spwd->sp_expire > -1) && (spwd->sp_expire <= (time(NULL) / (60 * 60 * 24)))) {
803 WRN(NULL, "User \"%s\" account has expired.", username);
804 goto error;
805 }
806
807 pass_hash = spwd->sp_pwdp;
808 } else {
809 pass_hash = pwd->pw_passwd;
810 }
811
812 if (!pass_hash) {
813 ERR(NULL, "No password could be retrieved for \"%s\".", username);
814 goto error;
815 }
816
817 /* check the hash structure for special meaning */
818 if (!strcmp(pass_hash, "*") || !strcmp(pass_hash, "!")) {
819 VRB(NULL, "User \"%s\" is not allowed to authenticate using a password.", username);
820 goto error;
821 }
822 if (!strcmp(pass_hash, "*NP*")) {
823 VRB(NULL, "Retrieving password for \"%s\" from a NIS+ server not supported.", username);
824 goto error;
825 }
826
827 pass_hash = strdup(pass_hash);
828 free(buf);
829 return pass_hash;
830
831error:
832 free(buf);
833 return NULL;
834}
835
836/**
837 * @brief Authenticate using locally stored credentials.
838 *
839 * @param[in] session Session to authenticate on.
840 * @param[in] client Client to authenticate.
romanc6518422023-11-30 16:39:00 +0100841 * @param[in] msg SSH message that originally requested kbdint authentication.
842 *
843 * @return 0 on success, non-zero otherwise.
844 */
845static int
romane5675b12024-03-05 14:26:23 +0100846nc_server_ssh_system_auth(struct nc_session *session, struct nc_auth_client *client, ssh_message msg)
romanc6518422023-11-30 16:39:00 +0100847{
848 int ret = 0, n_answers;
849 const char *name = "Keyboard-Interactive Authentication";
850 const char *instruction = "Please enter your authentication token";
851 char *prompt = NULL, *local_pw = NULL, *received_pw = NULL;
852 char echo[] = {0};
853
854 /* try to get the client's locally stored pw hash */
855 local_pw = nc_server_ssh_get_pwd_hash(client->username);
856 if (!local_pw) {
857 ERR(session, "Unable to get %s's credentials.", client->username);
858 ret = 1;
859 goto cleanup;
860 }
861
862 ret = asprintf(&prompt, "%s's password:", client->username);
863 NC_CHECK_ERRMEM_GOTO(ret == -1, prompt = NULL; ret = 1, cleanup);
864
865 /* send the password prompt to the client */
866 ret = ssh_message_auth_interactive_request(msg, name, instruction, 1, (const char **) &prompt, echo);
867 if (ret) {
868 ERR(session, "Failed to send an authentication request to client \"%s\".", client->username);
869 goto cleanup;
870 }
871
872 /* get the reply */
romane5675b12024-03-05 14:26:23 +0100873 n_answers = nc_server_ssh_kbdint_get_nanswers(session, session->ti.libssh.session);
romanc6518422023-11-30 16:39:00 +0100874 if (n_answers < 0) {
875 /* timeout or dc */
876 ret = 1;
877 goto cleanup;
878 } else if (n_answers != 1) {
879 /* only expecting a single answer */
880 ERR(session, "Unexpected amount of answers in system auth. Expected 1, got \"%d\".", n_answers);
881 ret = 1;
882 goto cleanup;
883 }
884 received_pw = strdup(ssh_userauth_kbdint_getanswer(session->ti.libssh.session, 0));
885 NC_CHECK_ERRMEM_GOTO(!received_pw, ret = 1, cleanup);
886
887 /* cmp the pw hashes */
888 ret = auth_password_compare_pwd(local_pw, received_pw);
889
890cleanup:
891 free(local_pw);
892 free(received_pw);
893 free(prompt);
894 return ret;
895}
896
897#endif
Michal Vasko0d81c572022-09-26 10:39:31 +0200898
romanf578cd52023-10-19 09:47:40 +0200899static int
romane5675b12024-03-05 14:26:23 +0100900nc_sshcb_auth_kbdint(struct nc_session *session, struct nc_auth_client *client, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +0100901{
bhart3bc2f582018-06-05 12:40:32 -0500902 int auth_ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +0100903
roman4f9e4422024-03-21 10:58:41 +0100904 if (!client->kb_int_enabled) {
905 VRB(session, "User \"%s\" does not have Keyboard-interactive method configured, but a request was received.", client->username);
906 } else if (server_opts.interactive_auth_clb) {
romanf578cd52023-10-19 09:47:40 +0200907 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 +0200908 } else {
909#ifdef HAVE_LIBPAM
romanc6518422023-11-30 16:39:00 +0100910 /* authenticate using PAM */
romane5675b12024-03-05 14:26:23 +0100911 if (!nc_pam_auth(session, client, msg)) {
romanc6518422023-11-30 16:39:00 +0100912 auth_ret = 0;
913 }
914#elif defined (HAVE_SHADOW)
915 /* authenticate using locally configured users */
romane5675b12024-03-05 14:26:23 +0100916 if (!nc_server_ssh_system_auth(session, client, msg)) {
Michal Vasko0d81c572022-09-26 10:39:31 +0200917 auth_ret = 0;
918 }
919#else
romanc6518422023-11-30 16:39:00 +0100920 ERR(NULL, "Keyboard-interactive method not supported.");
Michal Vasko0d81c572022-09-26 10:39:31 +0200921#endif
bhart1bb7cdb2018-07-02 15:03:30 -0500922 }
923
924 /* Authenticate message based on outcome */
romanf578cd52023-10-19 09:47:40 +0200925 if (auth_ret) {
bhart1bb7cdb2018-07-02 15:03:30 -0500926 ++session->opts.server.ssh_auth_attempts;
romanc6518422023-11-30 16:39:00 +0100927 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", client->username,
Michal Vasko05532772021-06-03 12:12:38 +0200928 session->opts.server.ssh_auth_attempts);
bhart1bb7cdb2018-07-02 15:03:30 -0500929 ssh_message_reply_default(msg);
Michal Vasko086311b2016-01-08 09:53:11 +0100930 }
romanf578cd52023-10-19 09:47:40 +0200931
932 return auth_ret;
933}
934
roman808f3f62023-11-23 16:01:04 +0100935API void
936nc_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),
937 void *user_data, void (*free_user_data)(void *user_data))
938{
romanc6518422023-11-30 16:39:00 +0100939 /* CONFIG LOCK */
940 pthread_rwlock_wrlock(&server_opts.config_lock);
941
roman808f3f62023-11-23 16:01:04 +0100942 server_opts.interactive_auth_clb = interactive_auth_clb;
943 server_opts.interactive_auth_data = user_data;
944 server_opts.interactive_auth_data_free = free_user_data;
romanc6518422023-11-30 16:39:00 +0100945
946 /* CONFIG UNLOCK */
947 pthread_rwlock_unlock(&server_opts.config_lock);
roman808f3f62023-11-23 16:01:04 +0100948}
949
950#ifdef HAVE_LIBPAM
951
952API int
953nc_server_ssh_set_pam_conf_filename(const char *filename)
954{
romanc6518422023-11-30 16:39:00 +0100955 int ret = 0;
956
roman808f3f62023-11-23 16:01:04 +0100957 NC_CHECK_ARG_RET(NULL, filename, 1);
958
romanc6518422023-11-30 16:39:00 +0100959 /* CONFIG LOCK */
960 pthread_rwlock_wrlock(&server_opts.config_lock);
961
roman808f3f62023-11-23 16:01:04 +0100962 free(server_opts.pam_config_name);
963 server_opts.pam_config_name = strdup(filename);
romanc6518422023-11-30 16:39:00 +0100964 if (!server_opts.pam_config_name) {
965 ERRMEM;
966 ret = 1;
967 }
968
969 /* CONFIG UNLOCK */
970 pthread_rwlock_unlock(&server_opts.config_lock);
971 return ret;
roman808f3f62023-11-23 16:01:04 +0100972}
973
974#else
975
976API int
977nc_server_ssh_set_pam_conf_filename(const char *filename)
978{
romanf69fbcf2023-12-14 09:24:34 +0100979 /* LibPAM not supported */
roman808f3f62023-11-23 16:01:04 +0100980 (void) filename;
roman808f3f62023-11-23 16:01:04 +0100981 return 1;
982}
983
984#endif /* HAVE_LIBPAM */
985
romana9ec3362023-12-21 10:59:57 +0100986API int
987nc_server_ssh_set_authkey_path_format(const char *path)
988{
989 int ret = 0;
990
991 NC_CHECK_ARG_RET(NULL, path, 1);
992
993 /* CONFIG LOCK */
994 pthread_rwlock_wrlock(&server_opts.config_lock);
995
996 free(server_opts.authkey_path_fmt);
997 server_opts.authkey_path_fmt = strdup(path);
998 if (!server_opts.authkey_path_fmt) {
999 ERRMEM;
1000 ret = 1;
1001 }
1002
1003 /* CONFIG UNLOCK */
1004 pthread_rwlock_unlock(&server_opts.config_lock);
1005 return ret;
1006}
1007
romanf578cd52023-10-19 09:47:40 +02001008/*
1009 * Get the public key type from binary data stored in buffer.
1010 * The data is in the form of: 4 bytes = data length, then data of data length
1011 * and the data is in network byte order. The key has to be in the SSH2 format.
1012 */
1013static const char *
1014nc_server_ssh_get_pubkey_type(const char *buffer, uint32_t *len)
1015{
1016 uint32_t type_len;
1017
1018 /* copy the 4 bytes */
1019 memcpy(&type_len, buffer, sizeof type_len);
1020 /* type_len now stores the length of the key type */
1021 type_len = ntohl(type_len);
1022 *len = type_len;
1023
1024 /* move 4 bytes in the buffer, this is where the type should be */
1025 buffer += sizeof type_len;
1026 return buffer;
1027}
1028
1029/**
1030 * @brief Create ssh key from base64 pubkey data.
1031 *
1032 * @param[in] base64 base64 encoded public key.
1033 * @param[out] key created ssh key.
1034 * @return 0 on success, 1 otherwise.
1035 */
1036static int
1037nc_server_ssh_create_ssh_pubkey(const char *base64, ssh_key *key)
1038{
1039 int ret = 0;
1040 char *bin = NULL;
1041 const char *pub_type = NULL;
1042 uint32_t pub_type_len = 0;
1043
roman6dfdc0d2023-11-09 13:25:27 +01001044 NC_CHECK_ARG_RET(NULL, base64, key, 1);
romanf578cd52023-10-19 09:47:40 +02001045
1046 *key = NULL;
1047
1048 /* convert base64 to binary */
1049 if (nc_base64_to_bin(base64, &bin) == -1) {
1050 ERR(NULL, "Unable to decode base64.");
1051 ret = 1;
1052 goto cleanup;
1053 }
1054
1055 /* get the key type and try to import it if possible */
1056 pub_type = nc_server_ssh_get_pubkey_type(bin, &pub_type_len);
1057 if (!pub_type) {
1058 ret = 1;
1059 goto cleanup;
1060 } else if (!strncmp(pub_type, "ssh-dss", pub_type_len)) {
1061 ERR(NULL, "DSA keys are not supported.");
1062 ret = 1;
1063 goto cleanup;
1064 } else if (!strncmp(pub_type, "ssh-rsa", pub_type_len)) {
1065 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_RSA, key);
1066 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp256", pub_type_len)) {
1067 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P256, key);
1068 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp384", pub_type_len)) {
1069 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P384, key);
1070 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp521", pub_type_len)) {
1071 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P521, key);
1072 } else if (!strncmp(pub_type, "ssh-ed25519", pub_type_len)) {
1073 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ED25519, key);
1074 } else {
1075 ERR(NULL, "Public key type not recognised.");
1076 ret = 1;
1077 goto cleanup;
1078 }
1079
1080cleanup:
1081 if (ret != SSH_OK) {
1082 ERR(NULL, "Error importing public key.");
1083 }
1084 free(bin);
1085 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +01001086}
1087
Michal Vaskof3c41e32022-09-09 11:22:21 +02001088/**
1089 * @brief Compare SSH key with configured authorized keys and return the username of the matching one, if any.
1090 *
1091 * @param[in] key Presented SSH key to compare.
1092 * @return Authorized key username, NULL if no match was found.
1093 */
romanf578cd52023-10-19 09:47:40 +02001094static int
1095auth_pubkey_compare_key(ssh_key key, struct nc_auth_client *auth_client)
Michal Vasko086311b2016-01-08 09:53:11 +01001096{
Michal Vaskoe2bfcd62024-03-28 07:58:49 +01001097 uint16_t i, pubkey_count = 0;
Michal Vasko3e9d1682017-02-24 09:50:15 +01001098 int ret = 0;
romanf578cd52023-10-19 09:47:40 +02001099 ssh_key new_key = NULL;
romana9ec3362023-12-21 10:59:57 +01001100 struct nc_public_key *pubkeys = NULL;
Michal Vasko086311b2016-01-08 09:53:11 +01001101
romanf578cd52023-10-19 09:47:40 +02001102 /* get the correct public key storage */
1103 if (auth_client->store == NC_STORE_LOCAL) {
1104 pubkeys = auth_client->pubkeys;
1105 pubkey_count = auth_client->pubkey_count;
romana9ec3362023-12-21 10:59:57 +01001106 } else if (auth_client->store == NC_STORE_TRUSTSTORE) {
romanf578cd52023-10-19 09:47:40 +02001107 ret = nc_server_ssh_ts_ref_get_keys(auth_client->ts_ref, &pubkeys, &pubkey_count);
1108 if (ret) {
1109 ERR(NULL, "Error getting \"%s\"'s public keys from the truststore.", auth_client->username);
romana9ec3362023-12-21 10:59:57 +01001110 goto cleanup;
Michal Vasko17dfda92016-12-01 14:06:16 +01001111 }
romana9ec3362023-12-21 10:59:57 +01001112 } else if (auth_client->store == NC_STORE_SYSTEM) {
1113 ret = nc_server_ssh_get_system_keys(auth_client->username, &pubkeys, &pubkey_count);
1114 if (ret) {
1115 ERR(NULL, "Failed to retrieve public keys of user \"%s\" from the system.", auth_client->username);
1116 goto cleanup;
1117 }
1118 } else {
1119 ERRINT;
1120 return 1;
romanf578cd52023-10-19 09:47:40 +02001121 }
Michal Vasko17dfda92016-12-01 14:06:16 +01001122
romanf578cd52023-10-19 09:47:40 +02001123 /* try to compare all of the client's keys with the key received in the SSH message */
1124 for (i = 0; i < pubkey_count; i++) {
1125 /* create the SSH key from the data */
1126 if (nc_server_ssh_create_ssh_pubkey(pubkeys[i].data, &new_key)) {
1127 ssh_key_free(new_key);
Michal Vasko086311b2016-01-08 09:53:11 +01001128 continue;
1129 }
1130
romanf578cd52023-10-19 09:47:40 +02001131 /* compare the keys */
1132 ret = ssh_key_cmp(key, new_key, SSH_KEY_CMP_PUBLIC);
1133 if (!ret) {
Michal Vasko086311b2016-01-08 09:53:11 +01001134 break;
romanf578cd52023-10-19 09:47:40 +02001135 } else {
1136 WRN(NULL, "User's \"%s\" public key doesn't match, trying another.", auth_client->username);
1137 ssh_key_free(new_key);
Michal Vasko086311b2016-01-08 09:53:11 +01001138 }
Michal Vasko086311b2016-01-08 09:53:11 +01001139 }
romanf578cd52023-10-19 09:47:40 +02001140 if (i == pubkey_count) {
1141 ret = 1;
romana9ec3362023-12-21 10:59:57 +01001142 goto cleanup;
Michal Vasko086311b2016-01-08 09:53:11 +01001143 }
1144
romana9ec3362023-12-21 10:59:57 +01001145cleanup:
romanf578cd52023-10-19 09:47:40 +02001146 if (!ret) {
1147 /* only free a key if everything was ok, it would have already been freed otherwise */
1148 ssh_key_free(new_key);
1149 }
Michal Vaskoa05c7b12017-01-30 14:33:08 +01001150
romana9ec3362023-12-21 10:59:57 +01001151 if ((auth_client->store == NC_STORE_SYSTEM) && pubkeys) {
1152 for (i = 0; i < pubkey_count; i++) {
1153 free(pubkeys[i].name);
1154 free(pubkeys[i].data);
1155 }
1156 free(pubkeys);
1157 }
romanf578cd52023-10-19 09:47:40 +02001158 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +01001159}
1160
1161static void
romanf578cd52023-10-19 09:47:40 +02001162nc_sshcb_auth_none(struct nc_session *session, struct nc_auth_client *auth_client, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +01001163{
roman808f3f62023-11-23 16:01:04 +01001164 if (auth_client->none_enabled && !auth_client->password && !auth_client->pubkey_count && !auth_client->kb_int_enabled) {
romanf578cd52023-10-19 09:47:40 +02001165 /* only authenticate the client if he supports none and no other method */
1166 session->flags |= NC_SESSION_SSH_AUTHENTICATED;
1167 VRB(session, "User \"%s\" authenticated.", session->username);
1168 ssh_message_auth_reply_success(msg, 0);
1169 }
1170
1171 ssh_message_reply_default(msg);
1172}
1173
1174static int
1175nc_sshcb_auth_pubkey(struct nc_session *session, struct nc_auth_client *auth_client, ssh_message msg)
1176{
1177 int signature_state, ret = 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001178
roman9130fc12023-11-03 13:56:23 +01001179 if (auth_pubkey_compare_key(ssh_message_auth_pubkey(msg), auth_client)) {
1180 VRB(session, "User \"%s\" tried to use an unknown (unauthorized) public key.", session->username);
1181 ret = 1;
1182 goto fail;
Michal Vaskobd13a932016-09-14 09:00:35 +02001183 }
Michal Vaskobd13a932016-09-14 09:00:35 +02001184
Michal Vasko086311b2016-01-08 09:53:11 +01001185 signature_state = ssh_message_auth_publickey_state(msg);
romanf578cd52023-10-19 09:47:40 +02001186 if (signature_state == SSH_PUBLICKEY_STATE_NONE) {
Michal Vaskobd13a932016-09-14 09:00:35 +02001187 /* accepting only the use of a public key */
1188 ssh_message_auth_reply_pk_ok_simple(msg);
romanf578cd52023-10-19 09:47:40 +02001189 ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001190 }
1191
romanf578cd52023-10-19 09:47:40 +02001192 return ret;
Michal Vaskobd13a932016-09-14 09:00:35 +02001193
1194fail:
Michal Vasko2e6defd2016-10-07 15:48:15 +02001195 ++session->opts.server.ssh_auth_attempts;
Michal Vasko05532772021-06-03 12:12:38 +02001196 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", session->username,
1197 session->opts.server.ssh_auth_attempts);
Michal Vasko086311b2016-01-08 09:53:11 +01001198 ssh_message_reply_default(msg);
romanf578cd52023-10-19 09:47:40 +02001199
1200 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +01001201}
1202
1203static int
Michal Vasko96164bf2016-01-21 15:41:58 +01001204nc_sshcb_channel_open(struct nc_session *session, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +01001205{
Michal Vasko96164bf2016-01-21 15:41:58 +01001206 ssh_channel chan;
1207
1208 /* first channel request */
1209 if (!session->ti.libssh.channel) {
1210 if (session->status != NC_STATUS_STARTING) {
Michal Vasko9e036d52016-01-08 10:49:26 +01001211 ERRINT;
Michal Vasko086311b2016-01-08 09:53:11 +01001212 return -1;
1213 }
Michal Vasko96164bf2016-01-21 15:41:58 +01001214 chan = ssh_message_channel_request_open_reply_accept(msg);
1215 if (!chan) {
Michal Vasko05532772021-06-03 12:12:38 +02001216 ERR(session, "Failed to create a new SSH channel.");
Michal Vasko96164bf2016-01-21 15:41:58 +01001217 return -1;
1218 }
1219 session->ti.libssh.channel = chan;
Michal Vasko086311b2016-01-08 09:53:11 +01001220
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001221 /* additional channel request */
Michal Vasko96164bf2016-01-21 15:41:58 +01001222 } else {
1223 chan = ssh_message_channel_request_open_reply_accept(msg);
1224 if (!chan) {
Michal Vasko05532772021-06-03 12:12:38 +02001225 ERR(session, "Session %u: failed to create a new SSH channel.", session->id);
Michal Vasko96164bf2016-01-21 15:41:58 +01001226 return -1;
1227 }
1228 /* channel was created and libssh stored it internally in the ssh_session structure, good enough */
Michal Vasko086311b2016-01-08 09:53:11 +01001229 }
1230
Michal Vasko086311b2016-01-08 09:53:11 +01001231 return 0;
1232}
1233
1234static int
1235nc_sshcb_channel_subsystem(struct nc_session *session, ssh_channel channel, const char *subsystem)
1236{
Michal Vasko96164bf2016-01-21 15:41:58 +01001237 struct nc_session *new_session;
Michal Vasko086311b2016-01-08 09:53:11 +01001238
Michal Vasko96164bf2016-01-21 15:41:58 +01001239 if (strcmp(subsystem, "netconf")) {
Michal Vasko05532772021-06-03 12:12:38 +02001240 WRN(session, "Received an unknown subsystem \"%s\" request.", subsystem);
Michal Vasko086311b2016-01-08 09:53:11 +01001241 return -1;
1242 }
1243
Michal Vasko96164bf2016-01-21 15:41:58 +01001244 if (session->ti.libssh.channel == channel) {
1245 /* first channel requested */
1246 if (session->ti.libssh.next || (session->status != NC_STATUS_STARTING)) {
1247 ERRINT;
1248 return -1;
Michal Vasko086311b2016-01-08 09:53:11 +01001249 }
Michal Vasko96164bf2016-01-21 15:41:58 +01001250 if (session->flags & NC_SESSION_SSH_SUBSYS_NETCONF) {
Michal Vasko05532772021-06-03 12:12:38 +02001251 ERR(session, "Subsystem \"netconf\" requested for the second time.");
Michal Vasko96164bf2016-01-21 15:41:58 +01001252 return -1;
1253 }
1254
1255 session->flags |= NC_SESSION_SSH_SUBSYS_NETCONF;
Michal Vasko086311b2016-01-08 09:53:11 +01001256 } else {
Michal Vasko96164bf2016-01-21 15:41:58 +01001257 /* additional channel subsystem request, new session is ready as far as SSH is concerned */
Michal Vasko131120a2018-05-29 15:44:02 +02001258 new_session = nc_new_session(NC_SERVER, 1);
roman3a95bb22023-10-26 11:07:17 +02001259 NC_CHECK_ERRMEM_RET(!new_session, -1);
Michal Vasko96164bf2016-01-21 15:41:58 +01001260
1261 /* insert the new session */
1262 if (!session->ti.libssh.next) {
1263 new_session->ti.libssh.next = session;
1264 } else {
1265 new_session->ti.libssh.next = session->ti.libssh.next;
1266 }
1267 session->ti.libssh.next = new_session;
1268
1269 new_session->status = NC_STATUS_STARTING;
Michal Vasko96164bf2016-01-21 15:41:58 +01001270 new_session->ti_type = NC_TI_LIBSSH;
Michal Vasko131120a2018-05-29 15:44:02 +02001271 new_session->io_lock = session->io_lock;
Michal Vasko96164bf2016-01-21 15:41:58 +01001272 new_session->ti.libssh.channel = channel;
1273 new_session->ti.libssh.session = session->ti.libssh.session;
Michal Vasko93224072021-11-09 12:14:28 +01001274 new_session->username = strdup(session->username);
1275 new_session->host = strdup(session->host);
Michal Vasko96164bf2016-01-21 15:41:58 +01001276 new_session->port = session->port;
Michal Vasko93224072021-11-09 12:14:28 +01001277 new_session->ctx = (struct ly_ctx *)session->ctx;
Michal Vasko83d15322018-09-27 09:44:02 +02001278 new_session->flags = NC_SESSION_SSH_AUTHENTICATED | NC_SESSION_SSH_SUBSYS_NETCONF | NC_SESSION_SHAREDCTX;
Michal Vasko086311b2016-01-08 09:53:11 +01001279 }
1280
1281 return 0;
1282}
1283
Michal Vasko96164bf2016-01-21 15:41:58 +01001284int
romanf578cd52023-10-19 09:47:40 +02001285nc_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 +01001286{
1287 const char *str_type, *str_subtype = NULL, *username;
romanf578cd52023-10-19 09:47:40 +02001288 int subtype, type, libssh_auth_methods = 0, ret = 0;
1289 uint16_t i;
1290 struct nc_auth_client *auth_client = NULL;
roman78df0fa2023-11-02 10:33:57 +01001291 struct nc_endpt *referenced_endpt;
Michal Vasko086311b2016-01-08 09:53:11 +01001292
1293 type = ssh_message_type(msg);
1294 subtype = ssh_message_subtype(msg);
1295
1296 switch (type) {
1297 case SSH_REQUEST_AUTH:
1298 str_type = "request-auth";
1299 switch (subtype) {
1300 case SSH_AUTH_METHOD_NONE:
1301 str_subtype = "none";
1302 break;
1303 case SSH_AUTH_METHOD_PASSWORD:
1304 str_subtype = "password";
1305 break;
1306 case SSH_AUTH_METHOD_PUBLICKEY:
1307 str_subtype = "publickey";
1308 break;
1309 case SSH_AUTH_METHOD_HOSTBASED:
1310 str_subtype = "hostbased";
1311 break;
1312 case SSH_AUTH_METHOD_INTERACTIVE:
1313 str_subtype = "interactive";
1314 break;
1315 case SSH_AUTH_METHOD_GSSAPI_MIC:
1316 str_subtype = "gssapi-mic";
1317 break;
1318 }
1319 break;
1320
1321 case SSH_REQUEST_CHANNEL_OPEN:
1322 str_type = "request-channel-open";
1323 switch (subtype) {
1324 case SSH_CHANNEL_SESSION:
1325 str_subtype = "session";
1326 break;
1327 case SSH_CHANNEL_DIRECT_TCPIP:
1328 str_subtype = "direct-tcpip";
1329 break;
1330 case SSH_CHANNEL_FORWARDED_TCPIP:
1331 str_subtype = "forwarded-tcpip";
1332 break;
1333 case (int)SSH_CHANNEL_X11:
1334 str_subtype = "channel-x11";
1335 break;
1336 case SSH_CHANNEL_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001337 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001338 default:
1339 str_subtype = "unknown";
1340 break;
1341 }
1342 break;
1343
1344 case SSH_REQUEST_CHANNEL:
1345 str_type = "request-channel";
1346 switch (subtype) {
1347 case SSH_CHANNEL_REQUEST_PTY:
1348 str_subtype = "pty";
1349 break;
1350 case SSH_CHANNEL_REQUEST_EXEC:
1351 str_subtype = "exec";
1352 break;
1353 case SSH_CHANNEL_REQUEST_SHELL:
1354 str_subtype = "shell";
1355 break;
1356 case SSH_CHANNEL_REQUEST_ENV:
1357 str_subtype = "env";
1358 break;
1359 case SSH_CHANNEL_REQUEST_SUBSYSTEM:
1360 str_subtype = "subsystem";
1361 break;
1362 case SSH_CHANNEL_REQUEST_WINDOW_CHANGE:
1363 str_subtype = "window-change";
1364 break;
1365 case SSH_CHANNEL_REQUEST_X11:
1366 str_subtype = "x11";
1367 break;
1368 case SSH_CHANNEL_REQUEST_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001369 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001370 default:
1371 str_subtype = "unknown";
1372 break;
1373 }
1374 break;
1375
1376 case SSH_REQUEST_SERVICE:
1377 str_type = "request-service";
1378 str_subtype = ssh_message_service_service(msg);
1379 break;
1380
1381 case SSH_REQUEST_GLOBAL:
1382 str_type = "request-global";
1383 switch (subtype) {
1384 case SSH_GLOBAL_REQUEST_TCPIP_FORWARD:
1385 str_subtype = "tcpip-forward";
1386 break;
1387 case SSH_GLOBAL_REQUEST_CANCEL_TCPIP_FORWARD:
1388 str_subtype = "cancel-tcpip-forward";
1389 break;
1390 case SSH_GLOBAL_REQUEST_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001391 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001392 default:
1393 str_subtype = "unknown";
1394 break;
1395 }
1396 break;
1397
1398 default:
1399 str_type = "unknown";
1400 str_subtype = "unknown";
1401 break;
1402 }
1403
Michal Vasko05532772021-06-03 12:12:38 +02001404 VRB(session, "Received an SSH message \"%s\" of subtype \"%s\".", str_type, str_subtype);
Michal Vasko5e0edd82020-07-29 15:26:13 +02001405 if (!session || (session->status == NC_STATUS_CLOSING) || (session->status == NC_STATUS_INVALID)) {
Michal Vaskoce319162016-02-03 15:33:08 +01001406 /* "valid" situation if, for example, receiving some auth or channel request timeouted,
1407 * but we got it now, during session free */
Michal Vasko05532772021-06-03 12:12:38 +02001408 VRB(session, "SSH message arrived on a %s session, the request will be denied.",
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001409 (session && session->status == NC_STATUS_CLOSING ? "closing" : "invalid"));
Michal Vaskoce319162016-02-03 15:33:08 +01001410 ssh_message_reply_default(msg);
1411 return 0;
1412 }
Michal Vasko086311b2016-01-08 09:53:11 +01001413
1414 /*
1415 * process known messages
1416 */
1417 if (type == SSH_REQUEST_AUTH) {
1418 if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
Michal Vasko05532772021-06-03 12:12:38 +02001419 ERR(session, "User \"%s\" authenticated, but requested another authentication.", session->username);
Michal Vasko086311b2016-01-08 09:53:11 +01001420 ssh_message_reply_default(msg);
1421 return 0;
romanf578cd52023-10-19 09:47:40 +02001422 } else if (!state || !opts) {
1423 /* these two parameters should always be set during an authentication,
1424 * however do a check just in case something goes really wrong, since they
1425 * are not needed for other types of messages
1426 */
1427 ERRINT;
1428 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001429 }
1430
Michal Vasko086311b2016-01-08 09:53:11 +01001431 /* save the username, do not let the client change it */
1432 username = ssh_message_auth_user(msg);
romanf578cd52023-10-19 09:47:40 +02001433 assert(username);
1434
1435 for (i = 0; i < opts->client_count; i++) {
1436 if (!strcmp(opts->auth_clients[i].username, username)) {
1437 auth_client = &opts->auth_clients[i];
1438 break;
1439 }
1440 }
1441
1442 if (!auth_client) {
roman78df0fa2023-11-02 10:33:57 +01001443 if (opts->referenced_endpt_name) {
1444 /* client not known by the endpt, but it references another one so try it */
1445 if (nc_server_get_referenced_endpt(opts->referenced_endpt_name, &referenced_endpt)) {
1446 ERRINT;
1447 return 1;
1448 }
1449
1450 return nc_session_ssh_msg(session, referenced_endpt->opts.ssh, msg, state);
Michal Vasko086311b2016-01-08 09:53:11 +01001451 }
1452
roman545879e2024-01-19 14:43:46 +01001453 /* user not known, set his authentication methods to public key only so that
1454 * there is no interaction and it will simply be denied */
romanf578cd52023-10-19 09:47:40 +02001455 ERR(NULL, "User \"%s\" not known by the server.", username);
roman545879e2024-01-19 14:43:46 +01001456 ssh_set_auth_methods(session->ti.libssh.session, SSH_AUTH_METHOD_PUBLICKEY);
romanf578cd52023-10-19 09:47:40 +02001457 ssh_message_reply_default(msg);
1458 return 0;
1459 }
1460
1461 if (!session->username) {
Michal Vasko93224072021-11-09 12:14:28 +01001462 session->username = strdup(username);
romanf578cd52023-10-19 09:47:40 +02001463
1464 /* configure and count accepted auth methods */
1465 if (auth_client->store == NC_STORE_LOCAL) {
1466 if (auth_client->pubkey_count) {
1467 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1468 }
romana9ec3362023-12-21 10:59:57 +01001469 } else if (auth_client->store == NC_STORE_TRUSTSTORE) {
1470 if (auth_client->ts_ref) {
1471 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1472 }
1473 } else if (auth_client->store == NC_STORE_SYSTEM) {
romanf578cd52023-10-19 09:47:40 +02001474 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1475 }
1476 if (auth_client->password) {
1477 state->auth_method_count++;
1478 libssh_auth_methods |= SSH_AUTH_METHOD_PASSWORD;
1479 }
roman808f3f62023-11-23 16:01:04 +01001480 if (auth_client->kb_int_enabled) {
romanf578cd52023-10-19 09:47:40 +02001481 state->auth_method_count++;
1482 libssh_auth_methods |= SSH_AUTH_METHOD_INTERACTIVE;
1483 }
roman808f3f62023-11-23 16:01:04 +01001484 if (auth_client->none_enabled) {
romanf578cd52023-10-19 09:47:40 +02001485 libssh_auth_methods |= SSH_AUTH_METHOD_NONE;
1486 }
1487
1488 if (libssh_auth_methods & SSH_AUTH_METHOD_PUBLICKEY) {
1489 state->auth_method_count++;
1490 }
1491
1492 ssh_set_auth_methods(session->ti.libssh.session, libssh_auth_methods);
1493 } else {
Michal Vasko086311b2016-01-08 09:53:11 +01001494 if (strcmp(username, session->username)) {
romanf578cd52023-10-19 09:47:40 +02001495 /* changing username not allowed */
Michal Vasko05532772021-06-03 12:12:38 +02001496 ERR(session, "User \"%s\" changed its username to \"%s\".", session->username, username);
Michal Vasko086311b2016-01-08 09:53:11 +01001497 session->status = NC_STATUS_INVALID;
Michal Vasko428087d2016-01-14 16:04:28 +01001498 session->term_reason = NC_SESSION_TERM_OTHER;
Michal Vasko086311b2016-01-08 09:53:11 +01001499 return 1;
1500 }
1501 }
1502
romanf578cd52023-10-19 09:47:40 +02001503 /* try authenticating, the user must authenticate via all of his configured auth methods */
Michal Vasko086311b2016-01-08 09:53:11 +01001504 if (subtype == SSH_AUTH_METHOD_NONE) {
romanf578cd52023-10-19 09:47:40 +02001505 nc_sshcb_auth_none(session, auth_client, msg);
1506 ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001507 } else if (subtype == SSH_AUTH_METHOD_PASSWORD) {
romanf578cd52023-10-19 09:47:40 +02001508 ret = nc_sshcb_auth_password(session, auth_client, msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001509 } else if (subtype == SSH_AUTH_METHOD_PUBLICKEY) {
romanf578cd52023-10-19 09:47:40 +02001510 ret = nc_sshcb_auth_pubkey(session, auth_client, msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001511 } else if (subtype == SSH_AUTH_METHOD_INTERACTIVE) {
romane5675b12024-03-05 14:26:23 +01001512 ret = nc_sshcb_auth_kbdint(session, auth_client, msg);
roman4f9e4422024-03-21 10:58:41 +01001513 } else {
1514 VRB(session, "Authentication method \"%s\" not supported.", str_subtype);
1515 ssh_message_reply_default(msg);
1516 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001517 }
romanf578cd52023-10-19 09:47:40 +02001518
1519 if (!ret) {
1520 state->auth_success_count++;
1521 }
1522
1523 if (!ret && (state->auth_success_count < state->auth_method_count)) {
1524 /* success, but he needs to do another method */
1525 VRB(session, "User \"%s\" partially authenticated, but still needs to authenticate via the rest of his configured methods.", username);
1526 ssh_message_auth_reply_success(msg, 1);
1527 } else if (!ret && (state->auth_success_count == state->auth_method_count)) {
1528 /* authenticated */
1529 ssh_message_auth_reply_success(msg, 0);
1530 session->flags |= NC_SESSION_SSH_AUTHENTICATED;
1531 VRB(session, "User \"%s\" authenticated.", username);
1532 }
1533
1534 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001535 } else if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
Michal Vasko0df67562016-01-21 15:50:11 +01001536 if ((type == SSH_REQUEST_CHANNEL_OPEN) && ((enum ssh_channel_type_e)subtype == SSH_CHANNEL_SESSION)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001537 if (nc_sshcb_channel_open(session, msg)) {
Michal Vasko086311b2016-01-08 09:53:11 +01001538 ssh_message_reply_default(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001539 }
Michal Vasko086311b2016-01-08 09:53:11 +01001540 return 0;
Michal Vasko96164bf2016-01-21 15:41:58 +01001541
Michal Vasko0df67562016-01-21 15:50:11 +01001542 } else if ((type == SSH_REQUEST_CHANNEL) && ((enum ssh_channel_requests_e)subtype == SSH_CHANNEL_REQUEST_SUBSYSTEM)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001543 if (nc_sshcb_channel_subsystem(session, ssh_message_channel_request_channel(msg),
1544 ssh_message_channel_request_subsystem(msg))) {
Michal Vasko086311b2016-01-08 09:53:11 +01001545 ssh_message_reply_default(msg);
Michal Vasko96164bf2016-01-21 15:41:58 +01001546 } else {
1547 ssh_message_channel_request_reply_success(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001548 }
1549 return 0;
1550 }
1551 }
1552
1553 /* we did not process it */
1554 return 1;
1555}
1556
Michal Vasko1a38c862016-01-15 15:50:07 +01001557/* ret 1 on success, 0 on timeout, -1 on error */
Michal Vasko086311b2016-01-08 09:53:11 +01001558static int
romanf578cd52023-10-19 09:47:40 +02001559nc_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 +01001560{
roman6ece9c52022-06-22 09:29:17 +02001561 struct timespec ts_timeout;
romanf578cd52023-10-19 09:47:40 +02001562 ssh_message msg;
Michal Vasko086311b2016-01-08 09:53:11 +01001563
romanf578cd52023-10-19 09:47:40 +02001564 if (timeout) {
1565 nc_timeouttime_get(&ts_timeout, timeout * 1000);
Michal Vasko36c7be82017-02-22 13:37:59 +01001566 }
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001567 while (1) {
1568 if (!nc_session_is_connected(session)) {
romanf578cd52023-10-19 09:47:40 +02001569 ERR(session, "Communication SSH socket unexpectedly closed.");
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001570 return -1;
1571 }
1572
romanf578cd52023-10-19 09:47:40 +02001573 msg = ssh_message_get(session->ti.libssh.session);
1574 if (msg) {
1575 if (nc_session_ssh_msg(session, opts, msg, NULL)) {
1576 ssh_message_reply_default(msg);
1577 }
1578 ssh_message_free(msg);
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001579 }
1580
romanf578cd52023-10-19 09:47:40 +02001581 if (session->ti.libssh.channel && session->flags & NC_SESSION_SSH_SUBSYS_NETCONF) {
Michal Vasko1a38c862016-01-15 15:50:07 +01001582 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001583 }
1584
Michal Vasko086311b2016-01-08 09:53:11 +01001585 usleep(NC_TIMEOUT_STEP);
roman0b7e6982024-04-29 11:11:52 +02001586 if (timeout && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
roman6ece9c52022-06-22 09:29:17 +02001587 /* timeout */
1588 ERR(session, "Failed to start \"netconf\" SSH subsystem for too long, disconnecting.");
1589 break;
Michal Vasko36c7be82017-02-22 13:37:59 +01001590 }
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001591 }
Michal Vasko086311b2016-01-08 09:53:11 +01001592
Michal Vasko1a38c862016-01-15 15:50:07 +01001593 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001594}
1595
Michal Vaskof3c41e32022-09-09 11:22:21 +02001596/**
1597 * @brief Set hostkeys to be used for an SSH bind.
1598 *
1599 * @param[in] sbind SSH bind to use.
1600 * @param[in] hostkeys Array of hostkeys.
1601 * @param[in] hostkey_count Count of @p hostkeys.
1602 * @return 0 on success.
1603 * @return -1 on error.
1604 */
Michal Vasko4c1fb492017-01-30 14:31:07 +01001605static int
romanf578cd52023-10-19 09:47:40 +02001606nc_ssh_bind_add_hostkeys(ssh_bind sbind, struct nc_server_ssh_opts *opts, uint16_t hostkey_count)
Michal Vasko4c1fb492017-01-30 14:31:07 +01001607{
romanf578cd52023-10-19 09:47:40 +02001608 uint16_t i;
roman6dfdc0d2023-11-09 13:25:27 +01001609 char *privkey_path;
Michal Vaskoddce1212019-05-24 09:58:49 +02001610 int ret;
romanf578cd52023-10-19 09:47:40 +02001611 struct nc_asymmetric_key *key = NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +01001612
1613 for (i = 0; i < hostkey_count; ++i) {
roman6dfdc0d2023-11-09 13:25:27 +01001614 privkey_path = NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +01001615
romanf578cd52023-10-19 09:47:40 +02001616 /* get the asymmetric key */
1617 if (opts->hostkeys[i].store == NC_STORE_LOCAL) {
1618 /* stored locally */
1619 key = &opts->hostkeys[i].key;
1620 } else {
1621 /* keystore reference, need to get it */
1622 if (nc_server_ssh_ks_ref_get_key(opts->hostkeys[i].ks_ref, &key)) {
Michal Vasko4c1fb492017-01-30 14:31:07 +01001623 return -1;
1624 }
1625 }
1626
romanf578cd52023-10-19 09:47:40 +02001627 privkey_path = base64der_privkey_to_tmp_file(key->privkey_data, nc_privkey_format_to_str(key->privkey_type));
1628 if (!privkey_path) {
1629 ERR(NULL, "Temporarily storing a host key into a file failed (%s).", strerror(errno));
1630 return -1;
1631 }
1632
Michal Vasko4c1fb492017-01-30 14:31:07 +01001633 ret = ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY, privkey_path);
1634
1635 /* cleanup */
roman6dfdc0d2023-11-09 13:25:27 +01001636 if (unlink(privkey_path)) {
Michal Vasko05532772021-06-03 12:12:38 +02001637 WRN(NULL, "Removing a temporary host key file \"%s\" failed (%s).", privkey_path, strerror(errno));
Michal Vasko4c1fb492017-01-30 14:31:07 +01001638 }
Michal Vasko4c1fb492017-01-30 14:31:07 +01001639
1640 if (ret != SSH_OK) {
romanf578cd52023-10-19 09:47:40 +02001641 ERR(NULL, "Failed to set hostkey \"%s\" (%s).", opts->hostkeys[i].name, privkey_path);
Michal Vasko80075de2017-07-10 11:38:52 +02001642 }
1643 free(privkey_path);
1644
1645 if (ret != SSH_OK) {
Michal Vasko4c1fb492017-01-30 14:31:07 +01001646 return -1;
1647 }
1648 }
1649
1650 return 0;
1651}
1652
Michal Vasko09d700f2022-09-08 10:21:40 +02001653static int
romanf578cd52023-10-19 09:47:40 +02001654nc_accept_ssh_session_auth(struct nc_session *session, struct nc_server_ssh_opts *opts)
Michal Vasko3031aae2016-01-27 16:07:18 +01001655{
roman6ece9c52022-06-22 09:29:17 +02001656 struct timespec ts_timeout;
roman41a11e42022-06-22 09:27:08 +02001657 ssh_message msg;
romanf578cd52023-10-19 09:47:40 +02001658 struct nc_auth_state state = {0};
Michal Vasko086311b2016-01-08 09:53:11 +01001659
Michal Vasko086311b2016-01-08 09:53:11 +01001660 /* authenticate */
Michal Vasko36c7be82017-02-22 13:37:59 +01001661 if (opts->auth_timeout) {
Michal Vaskod8a74192023-02-06 15:51:50 +01001662 nc_timeouttime_get(&ts_timeout, opts->auth_timeout * 1000);
Michal Vasko36c7be82017-02-22 13:37:59 +01001663 }
1664 while (1) {
Michal Vasko2a7d4732016-01-15 09:24:46 +01001665 if (!nc_session_is_connected(session)) {
Michal Vasko05532772021-06-03 12:12:38 +02001666 ERR(session, "Communication SSH socket unexpectedly closed.");
Michal Vasko2a7d4732016-01-15 09:24:46 +01001667 return -1;
1668 }
1669
roman41a11e42022-06-22 09:27:08 +02001670 msg = ssh_message_get(session->ti.libssh.session);
1671 if (msg) {
romanf578cd52023-10-19 09:47:40 +02001672 if (nc_session_ssh_msg(session, opts, msg, &state)) {
roman41a11e42022-06-22 09:27:08 +02001673 ssh_message_reply_default(msg);
1674 }
1675 ssh_message_free(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001676 }
1677
Michal Vasko36c7be82017-02-22 13:37:59 +01001678 if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
1679 break;
1680 }
1681
Michal Vasko145ae672017-02-07 10:57:27 +01001682 if (session->opts.server.ssh_auth_attempts >= opts->auth_attempts) {
Michal Vasko05532772021-06-03 12:12:38 +02001683 ERR(session, "Too many failed authentication attempts of user \"%s\".", session->username);
Michal Vasko145ae672017-02-07 10:57:27 +01001684 return -1;
1685 }
1686
Michal Vasko086311b2016-01-08 09:53:11 +01001687 usleep(NC_TIMEOUT_STEP);
romanea0edaa2023-10-26 12:16:25 +02001688 if (opts->auth_timeout && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
roman6ece9c52022-06-22 09:29:17 +02001689 /* timeout */
1690 break;
Michal Vasko36c7be82017-02-22 13:37:59 +01001691 }
1692 }
Michal Vasko086311b2016-01-08 09:53:11 +01001693
1694 if (!(session->flags & NC_SESSION_SSH_AUTHENTICATED)) {
1695 /* timeout */
Michal Vaskoc13da702017-02-07 10:57:57 +01001696 if (session->username) {
Michal Vasko05532772021-06-03 12:12:38 +02001697 ERR(session, "User \"%s\" failed to authenticate for too long, disconnecting.", session->username);
Michal Vaskoc13da702017-02-07 10:57:57 +01001698 } else {
Michal Vasko05532772021-06-03 12:12:38 +02001699 ERR(session, "User failed to authenticate for too long, disconnecting.");
Michal Vaskoc13da702017-02-07 10:57:57 +01001700 }
Michal Vasko1a38c862016-01-15 15:50:07 +01001701 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001702 }
1703
Michal Vasko09d700f2022-09-08 10:21:40 +02001704 return 1;
1705}
1706
1707int
romanf578cd52023-10-19 09:47:40 +02001708nc_accept_ssh_session(struct nc_session *session, struct nc_server_ssh_opts *opts, int sock, int timeout)
Michal Vasko09d700f2022-09-08 10:21:40 +02001709{
1710 ssh_bind sbind = NULL;
Michal Vasko09d700f2022-09-08 10:21:40 +02001711 int rc = 1, r;
1712 struct timespec ts_timeout;
roman4cc0cd52023-04-14 09:12:29 +02001713 const char *err_msg;
Michal Vasko09d700f2022-09-08 10:21:40 +02001714
Michal Vasko09d700f2022-09-08 10:21:40 +02001715 /* other transport-specific data */
1716 session->ti_type = NC_TI_LIBSSH;
1717 session->ti.libssh.session = ssh_new();
1718 if (!session->ti.libssh.session) {
1719 ERR(NULL, "Failed to initialize a new SSH session.");
1720 rc = -1;
1721 goto cleanup;
1722 }
1723
1724 sbind = ssh_bind_new();
1725 if (!sbind) {
1726 ERR(session, "Failed to create an SSH bind.");
1727 rc = -1;
1728 goto cleanup;
1729 }
1730
1731 /* configure host keys */
romanf578cd52023-10-19 09:47:40 +02001732 if (nc_ssh_bind_add_hostkeys(sbind, opts, opts->hostkey_count)) {
1733 rc = -1;
1734 goto cleanup;
1735 }
1736
1737 /* configure supported algorithms */
1738 if (opts->hostkey_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY_ALGORITHMS, opts->hostkey_algs)) {
1739 rc = -1;
1740 goto cleanup;
1741 }
1742 if (opts->encryption_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_CIPHERS_S_C, opts->encryption_algs)) {
1743 rc = -1;
1744 goto cleanup;
1745 }
1746 if (opts->kex_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_KEY_EXCHANGE, opts->kex_algs)) {
1747 rc = -1;
1748 goto cleanup;
1749 }
1750 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 +02001751 rc = -1;
1752 goto cleanup;
1753 }
1754
1755 /* accept new connection on the bind */
1756 if (ssh_bind_accept_fd(sbind, session->ti.libssh.session, sock) == SSH_ERROR) {
1757 ERR(session, "SSH failed to accept a new connection (%s).", ssh_get_error(sbind));
1758 rc = -1;
1759 goto cleanup;
1760 }
1761 sock = -1;
1762
romanf578cd52023-10-19 09:47:40 +02001763 /* set to non-blocking */
Michal Vasko09d700f2022-09-08 10:21:40 +02001764 ssh_set_blocking(session->ti.libssh.session, 0);
1765
1766 if (timeout > -1) {
Michal Vaskod8a74192023-02-06 15:51:50 +01001767 nc_timeouttime_get(&ts_timeout, timeout);
Michal Vasko09d700f2022-09-08 10:21:40 +02001768 }
1769 while ((r = ssh_handle_key_exchange(session->ti.libssh.session)) == SSH_AGAIN) {
1770 /* this tends to take longer */
1771 usleep(NC_TIMEOUT_STEP * 20);
Michal Vaskod8a74192023-02-06 15:51:50 +01001772 if ((timeout > -1) && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001773 break;
1774 }
1775 }
1776 if (r == SSH_AGAIN) {
1777 ERR(session, "SSH key exchange timeout.");
1778 rc = 0;
1779 goto cleanup;
1780 } else if (r != SSH_OK) {
roman4cc0cd52023-04-14 09:12:29 +02001781 err_msg = ssh_get_error(session->ti.libssh.session);
1782 if (err_msg[0] == '\0') {
1783 err_msg = "hostkey algorithm generated from the hostkey most likely not found in the set of configured hostkey algorithms";
1784 }
1785 ERR(session, "SSH key exchange error (%s).", err_msg);
Michal Vasko09d700f2022-09-08 10:21:40 +02001786 rc = -1;
1787 goto cleanup;
1788 }
1789
romane5675b12024-03-05 14:26:23 +01001790 /* authenticate, store auth_timeout in session so we can retrieve it in kb interactive API */
1791 session->data = &opts->auth_timeout;
1792 rc = nc_accept_ssh_session_auth(session, opts);
1793 session->data = NULL;
1794 if (rc != 1) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001795 goto cleanup;
1796 }
1797
Michal Vasko09d700f2022-09-08 10:21:40 +02001798 /* open channel and request 'netconf' subsystem */
romanf578cd52023-10-19 09:47:40 +02001799 if ((rc = nc_accept_ssh_session_open_netconf_channel(session, opts, timeout)) != 1) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001800 goto cleanup;
Michal Vasko086311b2016-01-08 09:53:11 +01001801 }
1802
Michal Vasko09d700f2022-09-08 10:21:40 +02001803cleanup:
1804 if (sock > -1) {
1805 close(sock);
1806 }
1807 ssh_bind_free(sbind);
1808 return rc;
Michal Vasko086311b2016-01-08 09:53:11 +01001809}
1810
Michal Vasko71090fc2016-05-24 16:37:28 +02001811API NC_MSG_TYPE
1812nc_session_accept_ssh_channel(struct nc_session *orig_session, struct nc_session **session)
1813{
1814 NC_MSG_TYPE msgtype;
1815 struct nc_session *new_session = NULL;
Michal Vasko9f6275e2017-10-05 13:50:05 +02001816 struct timespec ts_cur;
Michal Vasko71090fc2016-05-24 16:37:28 +02001817
roman40672412023-05-04 11:10:22 +02001818 NC_CHECK_ARG_RET(orig_session, orig_session, session, NC_MSG_ERROR);
Michal Vasko71090fc2016-05-24 16:37:28 +02001819
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001820 if ((orig_session->status == NC_STATUS_RUNNING) && (orig_session->ti_type == NC_TI_LIBSSH) &&
1821 orig_session->ti.libssh.next) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001822 for (new_session = orig_session->ti.libssh.next;
1823 new_session != orig_session;
1824 new_session = new_session->ti.libssh.next) {
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001825 if ((new_session->status == NC_STATUS_STARTING) && new_session->ti.libssh.channel &&
1826 (new_session->flags & NC_SESSION_SSH_SUBSYS_NETCONF)) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001827 /* we found our session */
1828 break;
1829 }
1830 }
1831 if (new_session == orig_session) {
1832 new_session = NULL;
1833 }
1834 }
1835
1836 if (!new_session) {
Michal Vasko05532772021-06-03 12:12:38 +02001837 ERR(orig_session, "Session does not have a NETCONF SSH channel ready.");
Michal Vasko71090fc2016-05-24 16:37:28 +02001838 return NC_MSG_ERROR;
1839 }
1840
1841 /* assign new SID atomically */
Michal Vasko5bd4a3f2021-06-17 16:40:10 +02001842 new_session->id = ATOMIC_INC_RELAXED(server_opts.new_session_id);
Michal Vasko71090fc2016-05-24 16:37:28 +02001843
1844 /* NETCONF handshake */
Michal Vasko131120a2018-05-29 15:44:02 +02001845 msgtype = nc_handshake_io(new_session);
Michal Vasko71090fc2016-05-24 16:37:28 +02001846 if (msgtype != NC_MSG_HELLO) {
1847 return msgtype;
1848 }
1849
Michal Vaskod8a74192023-02-06 15:51:50 +01001850 nc_realtime_get(&ts_cur);
roman44efa322023-11-03 13:57:25 +01001851 new_session->opts.server.session_start = ts_cur;
Michal Vaskod8a74192023-02-06 15:51:50 +01001852 nc_timeouttime_get(&ts_cur, 0);
Michal Vasko9f6275e2017-10-05 13:50:05 +02001853 new_session->opts.server.last_rpc = ts_cur.tv_sec;
Michal Vasko71090fc2016-05-24 16:37:28 +02001854 new_session->status = NC_STATUS_RUNNING;
1855 *session = new_session;
1856
1857 return msgtype;
1858}
1859
1860API NC_MSG_TYPE
Michal Vasko96164bf2016-01-21 15:41:58 +01001861nc_ps_accept_ssh_channel(struct nc_pollsession *ps, struct nc_session **session)
Michal Vasko086311b2016-01-08 09:53:11 +01001862{
Michal Vaskobdcf2362016-07-26 11:35:43 +02001863 uint8_t q_id;
Michal Vasko71090fc2016-05-24 16:37:28 +02001864 NC_MSG_TYPE msgtype;
Michal Vaskoe4300a82017-05-24 10:35:42 +02001865 struct nc_session *new_session = NULL, *cur_session;
Michal Vasko9f6275e2017-10-05 13:50:05 +02001866 struct timespec ts_cur;
Michal Vaskoc61c4492016-01-25 11:13:34 +01001867 uint16_t i;
Michal Vasko086311b2016-01-08 09:53:11 +01001868
roman40672412023-05-04 11:10:22 +02001869 NC_CHECK_ARG_RET(NULL, ps, session, NC_MSG_ERROR);
Michal Vasko086311b2016-01-08 09:53:11 +01001870
Michal Vasko48a63ed2016-03-01 09:48:21 +01001871 /* LOCK */
Michal Vasko227f8ff2016-07-26 14:08:59 +02001872 if (nc_ps_lock(ps, &q_id, __func__)) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001873 return NC_MSG_ERROR;
Michal Vaskof04a52a2016-04-07 10:52:10 +02001874 }
Michal Vasko48a63ed2016-03-01 09:48:21 +01001875
Michal Vasko96164bf2016-01-21 15:41:58 +01001876 for (i = 0; i < ps->session_count; ++i) {
fanchanghu3d4e7212017-08-09 09:42:30 +08001877 cur_session = ps->sessions[i]->session;
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001878 if ((cur_session->status == NC_STATUS_RUNNING) && (cur_session->ti_type == NC_TI_LIBSSH) &&
1879 cur_session->ti.libssh.next) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001880 /* an SSH session with more channels */
Michal Vaskoe4300a82017-05-24 10:35:42 +02001881 for (new_session = cur_session->ti.libssh.next;
1882 new_session != cur_session;
Michal Vasko96164bf2016-01-21 15:41:58 +01001883 new_session = new_session->ti.libssh.next) {
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001884 if ((new_session->status == NC_STATUS_STARTING) && new_session->ti.libssh.channel &&
1885 (new_session->flags & NC_SESSION_SSH_SUBSYS_NETCONF)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001886 /* we found our session */
1887 break;
1888 }
1889 }
Michal Vaskoe4300a82017-05-24 10:35:42 +02001890 if (new_session != cur_session) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001891 break;
1892 }
Michal Vaskofb89d772016-01-08 12:25:35 +01001893
Michal Vasko96164bf2016-01-21 15:41:58 +01001894 new_session = NULL;
1895 }
1896 }
Michal Vaskofb89d772016-01-08 12:25:35 +01001897
Michal Vasko48a63ed2016-03-01 09:48:21 +01001898 /* UNLOCK */
Michal Vasko227f8ff2016-07-26 14:08:59 +02001899 nc_ps_unlock(ps, q_id, __func__);
Michal Vasko48a63ed2016-03-01 09:48:21 +01001900
Michal Vasko96164bf2016-01-21 15:41:58 +01001901 if (!new_session) {
Michal Vasko05532772021-06-03 12:12:38 +02001902 ERR(NULL, "No session with a NETCONF SSH channel ready was found.");
Michal Vasko71090fc2016-05-24 16:37:28 +02001903 return NC_MSG_ERROR;
Michal Vasko96164bf2016-01-21 15:41:58 +01001904 }
1905
1906 /* assign new SID atomically */
Michal Vasko5bd4a3f2021-06-17 16:40:10 +02001907 new_session->id = ATOMIC_INC_RELAXED(server_opts.new_session_id);
Michal Vaskofb89d772016-01-08 12:25:35 +01001908
Michal Vasko086311b2016-01-08 09:53:11 +01001909 /* NETCONF handshake */
Michal Vasko131120a2018-05-29 15:44:02 +02001910 msgtype = nc_handshake_io(new_session);
Michal Vasko71090fc2016-05-24 16:37:28 +02001911 if (msgtype != NC_MSG_HELLO) {
1912 return msgtype;
Michal Vasko086311b2016-01-08 09:53:11 +01001913 }
Michal Vasko48a63ed2016-03-01 09:48:21 +01001914
Michal Vaskod8a74192023-02-06 15:51:50 +01001915 nc_realtime_get(&ts_cur);
roman44efa322023-11-03 13:57:25 +01001916 new_session->opts.server.session_start = ts_cur;
Michal Vaskod8a74192023-02-06 15:51:50 +01001917 nc_timeouttime_get(&ts_cur, 0);
Michal Vasko9f6275e2017-10-05 13:50:05 +02001918 new_session->opts.server.last_rpc = ts_cur.tv_sec;
Michal Vasko086311b2016-01-08 09:53:11 +01001919 new_session->status = NC_STATUS_RUNNING;
Michal Vasko96164bf2016-01-21 15:41:58 +01001920 *session = new_session;
Michal Vasko086311b2016-01-08 09:53:11 +01001921
Michal Vasko71090fc2016-05-24 16:37:28 +02001922 return msgtype;
Michal Vasko086311b2016-01-08 09:53:11 +01001923}