blob: f7fc74dc890f4531a1c519c7f736b29e60c1fc36 [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 *
romance435112024-04-23 15:12:09 +02001012nc_server_ssh_get_pubkey_type(const unsigned char *buffer, uint32_t *len)
romanf578cd52023-10-19 09:47:40 +02001013{
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;
romance435112024-04-23 15:12:09 +02001024 return (const char *)buffer;
romanf578cd52023-10-19 09:47:40 +02001025}
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;
romance435112024-04-23 15:12:09 +02001038 unsigned char *bin = NULL;
romanf578cd52023-10-19 09:47:40 +02001039 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 ret = 1;
1049 goto cleanup;
1050 }
1051
1052 /* get the key type and try to import it if possible */
1053 pub_type = nc_server_ssh_get_pubkey_type(bin, &pub_type_len);
1054 if (!pub_type) {
1055 ret = 1;
1056 goto cleanup;
1057 } else if (!strncmp(pub_type, "ssh-dss", pub_type_len)) {
1058 ERR(NULL, "DSA keys are not supported.");
1059 ret = 1;
1060 goto cleanup;
1061 } else if (!strncmp(pub_type, "ssh-rsa", pub_type_len)) {
1062 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_RSA, key);
1063 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp256", pub_type_len)) {
1064 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P256, key);
1065 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp384", pub_type_len)) {
1066 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P384, key);
1067 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp521", pub_type_len)) {
1068 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P521, key);
1069 } else if (!strncmp(pub_type, "ssh-ed25519", pub_type_len)) {
1070 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ED25519, key);
1071 } else {
1072 ERR(NULL, "Public key type not recognised.");
1073 ret = 1;
1074 goto cleanup;
1075 }
1076
1077cleanup:
1078 if (ret != SSH_OK) {
1079 ERR(NULL, "Error importing public key.");
1080 }
1081 free(bin);
1082 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +01001083}
1084
Michal Vaskof3c41e32022-09-09 11:22:21 +02001085/**
1086 * @brief Compare SSH key with configured authorized keys and return the username of the matching one, if any.
1087 *
1088 * @param[in] key Presented SSH key to compare.
1089 * @return Authorized key username, NULL if no match was found.
1090 */
romanf578cd52023-10-19 09:47:40 +02001091static int
1092auth_pubkey_compare_key(ssh_key key, struct nc_auth_client *auth_client)
Michal Vasko086311b2016-01-08 09:53:11 +01001093{
Michal Vaskoe2bfcd62024-03-28 07:58:49 +01001094 uint16_t i, pubkey_count = 0;
Michal Vasko3e9d1682017-02-24 09:50:15 +01001095 int ret = 0;
romanf578cd52023-10-19 09:47:40 +02001096 ssh_key new_key = NULL;
romana9ec3362023-12-21 10:59:57 +01001097 struct nc_public_key *pubkeys = NULL;
Michal Vasko086311b2016-01-08 09:53:11 +01001098
romanf578cd52023-10-19 09:47:40 +02001099 /* get the correct public key storage */
1100 if (auth_client->store == NC_STORE_LOCAL) {
1101 pubkeys = auth_client->pubkeys;
1102 pubkey_count = auth_client->pubkey_count;
romana9ec3362023-12-21 10:59:57 +01001103 } else if (auth_client->store == NC_STORE_TRUSTSTORE) {
romanf578cd52023-10-19 09:47:40 +02001104 ret = nc_server_ssh_ts_ref_get_keys(auth_client->ts_ref, &pubkeys, &pubkey_count);
1105 if (ret) {
1106 ERR(NULL, "Error getting \"%s\"'s public keys from the truststore.", auth_client->username);
romana9ec3362023-12-21 10:59:57 +01001107 goto cleanup;
Michal Vasko17dfda92016-12-01 14:06:16 +01001108 }
romana9ec3362023-12-21 10:59:57 +01001109 } else if (auth_client->store == NC_STORE_SYSTEM) {
1110 ret = nc_server_ssh_get_system_keys(auth_client->username, &pubkeys, &pubkey_count);
1111 if (ret) {
1112 ERR(NULL, "Failed to retrieve public keys of user \"%s\" from the system.", auth_client->username);
1113 goto cleanup;
1114 }
1115 } else {
1116 ERRINT;
1117 return 1;
romanf578cd52023-10-19 09:47:40 +02001118 }
Michal Vasko17dfda92016-12-01 14:06:16 +01001119
romanf578cd52023-10-19 09:47:40 +02001120 /* try to compare all of the client's keys with the key received in the SSH message */
1121 for (i = 0; i < pubkey_count; i++) {
1122 /* create the SSH key from the data */
1123 if (nc_server_ssh_create_ssh_pubkey(pubkeys[i].data, &new_key)) {
1124 ssh_key_free(new_key);
Michal Vasko086311b2016-01-08 09:53:11 +01001125 continue;
1126 }
1127
romanf578cd52023-10-19 09:47:40 +02001128 /* compare the keys */
1129 ret = ssh_key_cmp(key, new_key, SSH_KEY_CMP_PUBLIC);
1130 if (!ret) {
Michal Vasko086311b2016-01-08 09:53:11 +01001131 break;
romanf578cd52023-10-19 09:47:40 +02001132 } else {
1133 WRN(NULL, "User's \"%s\" public key doesn't match, trying another.", auth_client->username);
1134 ssh_key_free(new_key);
Michal Vasko086311b2016-01-08 09:53:11 +01001135 }
Michal Vasko086311b2016-01-08 09:53:11 +01001136 }
romanf578cd52023-10-19 09:47:40 +02001137 if (i == pubkey_count) {
1138 ret = 1;
romana9ec3362023-12-21 10:59:57 +01001139 goto cleanup;
Michal Vasko086311b2016-01-08 09:53:11 +01001140 }
1141
romana9ec3362023-12-21 10:59:57 +01001142cleanup:
romanf578cd52023-10-19 09:47:40 +02001143 if (!ret) {
1144 /* only free a key if everything was ok, it would have already been freed otherwise */
1145 ssh_key_free(new_key);
1146 }
Michal Vaskoa05c7b12017-01-30 14:33:08 +01001147
romana9ec3362023-12-21 10:59:57 +01001148 if ((auth_client->store == NC_STORE_SYSTEM) && pubkeys) {
1149 for (i = 0; i < pubkey_count; i++) {
1150 free(pubkeys[i].name);
1151 free(pubkeys[i].data);
1152 }
1153 free(pubkeys);
1154 }
romanf578cd52023-10-19 09:47:40 +02001155 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +01001156}
1157
1158static void
romanf578cd52023-10-19 09:47:40 +02001159nc_sshcb_auth_none(struct nc_session *session, struct nc_auth_client *auth_client, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +01001160{
roman808f3f62023-11-23 16:01:04 +01001161 if (auth_client->none_enabled && !auth_client->password && !auth_client->pubkey_count && !auth_client->kb_int_enabled) {
romanf578cd52023-10-19 09:47:40 +02001162 /* only authenticate the client if he supports none and no other method */
1163 session->flags |= NC_SESSION_SSH_AUTHENTICATED;
1164 VRB(session, "User \"%s\" authenticated.", session->username);
1165 ssh_message_auth_reply_success(msg, 0);
1166 }
1167
1168 ssh_message_reply_default(msg);
1169}
1170
1171static int
1172nc_sshcb_auth_pubkey(struct nc_session *session, struct nc_auth_client *auth_client, ssh_message msg)
1173{
1174 int signature_state, ret = 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001175
roman9130fc12023-11-03 13:56:23 +01001176 if (auth_pubkey_compare_key(ssh_message_auth_pubkey(msg), auth_client)) {
1177 VRB(session, "User \"%s\" tried to use an unknown (unauthorized) public key.", session->username);
1178 ret = 1;
1179 goto fail;
Michal Vaskobd13a932016-09-14 09:00:35 +02001180 }
Michal Vaskobd13a932016-09-14 09:00:35 +02001181
Michal Vasko086311b2016-01-08 09:53:11 +01001182 signature_state = ssh_message_auth_publickey_state(msg);
romanf578cd52023-10-19 09:47:40 +02001183 if (signature_state == SSH_PUBLICKEY_STATE_NONE) {
Michal Vaskobd13a932016-09-14 09:00:35 +02001184 /* accepting only the use of a public key */
1185 ssh_message_auth_reply_pk_ok_simple(msg);
romanf578cd52023-10-19 09:47:40 +02001186 ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001187 }
1188
romanf578cd52023-10-19 09:47:40 +02001189 return ret;
Michal Vaskobd13a932016-09-14 09:00:35 +02001190
1191fail:
Michal Vasko2e6defd2016-10-07 15:48:15 +02001192 ++session->opts.server.ssh_auth_attempts;
Michal Vasko05532772021-06-03 12:12:38 +02001193 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", session->username,
1194 session->opts.server.ssh_auth_attempts);
Michal Vasko086311b2016-01-08 09:53:11 +01001195 ssh_message_reply_default(msg);
romanf578cd52023-10-19 09:47:40 +02001196
1197 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +01001198}
1199
1200static int
Michal Vasko96164bf2016-01-21 15:41:58 +01001201nc_sshcb_channel_open(struct nc_session *session, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +01001202{
Michal Vasko96164bf2016-01-21 15:41:58 +01001203 ssh_channel chan;
1204
1205 /* first channel request */
1206 if (!session->ti.libssh.channel) {
1207 if (session->status != NC_STATUS_STARTING) {
Michal Vasko9e036d52016-01-08 10:49:26 +01001208 ERRINT;
Michal Vasko086311b2016-01-08 09:53:11 +01001209 return -1;
1210 }
Michal Vasko96164bf2016-01-21 15:41:58 +01001211 chan = ssh_message_channel_request_open_reply_accept(msg);
1212 if (!chan) {
Michal Vasko05532772021-06-03 12:12:38 +02001213 ERR(session, "Failed to create a new SSH channel.");
Michal Vasko96164bf2016-01-21 15:41:58 +01001214 return -1;
1215 }
1216 session->ti.libssh.channel = chan;
Michal Vasko086311b2016-01-08 09:53:11 +01001217
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001218 /* additional channel request */
Michal Vasko96164bf2016-01-21 15:41:58 +01001219 } else {
1220 chan = ssh_message_channel_request_open_reply_accept(msg);
1221 if (!chan) {
Michal Vasko05532772021-06-03 12:12:38 +02001222 ERR(session, "Session %u: failed to create a new SSH channel.", session->id);
Michal Vasko96164bf2016-01-21 15:41:58 +01001223 return -1;
1224 }
1225 /* channel was created and libssh stored it internally in the ssh_session structure, good enough */
Michal Vasko086311b2016-01-08 09:53:11 +01001226 }
1227
Michal Vasko086311b2016-01-08 09:53:11 +01001228 return 0;
1229}
1230
1231static int
1232nc_sshcb_channel_subsystem(struct nc_session *session, ssh_channel channel, const char *subsystem)
1233{
Michal Vasko96164bf2016-01-21 15:41:58 +01001234 struct nc_session *new_session;
Michal Vasko086311b2016-01-08 09:53:11 +01001235
Michal Vasko96164bf2016-01-21 15:41:58 +01001236 if (strcmp(subsystem, "netconf")) {
Michal Vasko05532772021-06-03 12:12:38 +02001237 WRN(session, "Received an unknown subsystem \"%s\" request.", subsystem);
Michal Vasko086311b2016-01-08 09:53:11 +01001238 return -1;
1239 }
1240
Michal Vasko96164bf2016-01-21 15:41:58 +01001241 if (session->ti.libssh.channel == channel) {
1242 /* first channel requested */
1243 if (session->ti.libssh.next || (session->status != NC_STATUS_STARTING)) {
1244 ERRINT;
1245 return -1;
Michal Vasko086311b2016-01-08 09:53:11 +01001246 }
Michal Vasko96164bf2016-01-21 15:41:58 +01001247 if (session->flags & NC_SESSION_SSH_SUBSYS_NETCONF) {
Michal Vasko05532772021-06-03 12:12:38 +02001248 ERR(session, "Subsystem \"netconf\" requested for the second time.");
Michal Vasko96164bf2016-01-21 15:41:58 +01001249 return -1;
1250 }
1251
1252 session->flags |= NC_SESSION_SSH_SUBSYS_NETCONF;
Michal Vasko086311b2016-01-08 09:53:11 +01001253 } else {
Michal Vasko96164bf2016-01-21 15:41:58 +01001254 /* additional channel subsystem request, new session is ready as far as SSH is concerned */
Michal Vasko131120a2018-05-29 15:44:02 +02001255 new_session = nc_new_session(NC_SERVER, 1);
roman3a95bb22023-10-26 11:07:17 +02001256 NC_CHECK_ERRMEM_RET(!new_session, -1);
Michal Vasko96164bf2016-01-21 15:41:58 +01001257
1258 /* insert the new session */
1259 if (!session->ti.libssh.next) {
1260 new_session->ti.libssh.next = session;
1261 } else {
1262 new_session->ti.libssh.next = session->ti.libssh.next;
1263 }
1264 session->ti.libssh.next = new_session;
1265
1266 new_session->status = NC_STATUS_STARTING;
roman506354a2024-04-11 09:37:22 +02001267 new_session->ti_type = NC_TI_SSH;
Michal Vasko131120a2018-05-29 15:44:02 +02001268 new_session->io_lock = session->io_lock;
Michal Vasko96164bf2016-01-21 15:41:58 +01001269 new_session->ti.libssh.channel = channel;
1270 new_session->ti.libssh.session = session->ti.libssh.session;
Michal Vasko93224072021-11-09 12:14:28 +01001271 new_session->username = strdup(session->username);
1272 new_session->host = strdup(session->host);
Michal Vasko96164bf2016-01-21 15:41:58 +01001273 new_session->port = session->port;
Michal Vasko93224072021-11-09 12:14:28 +01001274 new_session->ctx = (struct ly_ctx *)session->ctx;
Michal Vasko83d15322018-09-27 09:44:02 +02001275 new_session->flags = NC_SESSION_SSH_AUTHENTICATED | NC_SESSION_SSH_SUBSYS_NETCONF | NC_SESSION_SHAREDCTX;
Michal Vasko086311b2016-01-08 09:53:11 +01001276 }
1277
1278 return 0;
1279}
1280
Michal Vasko96164bf2016-01-21 15:41:58 +01001281int
romanf578cd52023-10-19 09:47:40 +02001282nc_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 +01001283{
1284 const char *str_type, *str_subtype = NULL, *username;
romanf578cd52023-10-19 09:47:40 +02001285 int subtype, type, libssh_auth_methods = 0, ret = 0;
1286 uint16_t i;
1287 struct nc_auth_client *auth_client = NULL;
roman78df0fa2023-11-02 10:33:57 +01001288 struct nc_endpt *referenced_endpt;
Michal Vasko086311b2016-01-08 09:53:11 +01001289
1290 type = ssh_message_type(msg);
1291 subtype = ssh_message_subtype(msg);
1292
1293 switch (type) {
1294 case SSH_REQUEST_AUTH:
1295 str_type = "request-auth";
1296 switch (subtype) {
1297 case SSH_AUTH_METHOD_NONE:
1298 str_subtype = "none";
1299 break;
1300 case SSH_AUTH_METHOD_PASSWORD:
1301 str_subtype = "password";
1302 break;
1303 case SSH_AUTH_METHOD_PUBLICKEY:
1304 str_subtype = "publickey";
1305 break;
1306 case SSH_AUTH_METHOD_HOSTBASED:
1307 str_subtype = "hostbased";
1308 break;
1309 case SSH_AUTH_METHOD_INTERACTIVE:
1310 str_subtype = "interactive";
1311 break;
1312 case SSH_AUTH_METHOD_GSSAPI_MIC:
1313 str_subtype = "gssapi-mic";
1314 break;
1315 }
1316 break;
1317
1318 case SSH_REQUEST_CHANNEL_OPEN:
1319 str_type = "request-channel-open";
1320 switch (subtype) {
1321 case SSH_CHANNEL_SESSION:
1322 str_subtype = "session";
1323 break;
1324 case SSH_CHANNEL_DIRECT_TCPIP:
1325 str_subtype = "direct-tcpip";
1326 break;
1327 case SSH_CHANNEL_FORWARDED_TCPIP:
1328 str_subtype = "forwarded-tcpip";
1329 break;
1330 case (int)SSH_CHANNEL_X11:
1331 str_subtype = "channel-x11";
1332 break;
1333 case SSH_CHANNEL_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001334 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001335 default:
1336 str_subtype = "unknown";
1337 break;
1338 }
1339 break;
1340
1341 case SSH_REQUEST_CHANNEL:
1342 str_type = "request-channel";
1343 switch (subtype) {
1344 case SSH_CHANNEL_REQUEST_PTY:
1345 str_subtype = "pty";
1346 break;
1347 case SSH_CHANNEL_REQUEST_EXEC:
1348 str_subtype = "exec";
1349 break;
1350 case SSH_CHANNEL_REQUEST_SHELL:
1351 str_subtype = "shell";
1352 break;
1353 case SSH_CHANNEL_REQUEST_ENV:
1354 str_subtype = "env";
1355 break;
1356 case SSH_CHANNEL_REQUEST_SUBSYSTEM:
1357 str_subtype = "subsystem";
1358 break;
1359 case SSH_CHANNEL_REQUEST_WINDOW_CHANGE:
1360 str_subtype = "window-change";
1361 break;
1362 case SSH_CHANNEL_REQUEST_X11:
1363 str_subtype = "x11";
1364 break;
1365 case SSH_CHANNEL_REQUEST_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001366 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001367 default:
1368 str_subtype = "unknown";
1369 break;
1370 }
1371 break;
1372
1373 case SSH_REQUEST_SERVICE:
1374 str_type = "request-service";
1375 str_subtype = ssh_message_service_service(msg);
1376 break;
1377
1378 case SSH_REQUEST_GLOBAL:
1379 str_type = "request-global";
1380 switch (subtype) {
1381 case SSH_GLOBAL_REQUEST_TCPIP_FORWARD:
1382 str_subtype = "tcpip-forward";
1383 break;
1384 case SSH_GLOBAL_REQUEST_CANCEL_TCPIP_FORWARD:
1385 str_subtype = "cancel-tcpip-forward";
1386 break;
1387 case SSH_GLOBAL_REQUEST_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001388 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001389 default:
1390 str_subtype = "unknown";
1391 break;
1392 }
1393 break;
1394
1395 default:
1396 str_type = "unknown";
1397 str_subtype = "unknown";
1398 break;
1399 }
1400
Michal Vasko05532772021-06-03 12:12:38 +02001401 VRB(session, "Received an SSH message \"%s\" of subtype \"%s\".", str_type, str_subtype);
Michal Vasko5e0edd82020-07-29 15:26:13 +02001402 if (!session || (session->status == NC_STATUS_CLOSING) || (session->status == NC_STATUS_INVALID)) {
Michal Vaskoce319162016-02-03 15:33:08 +01001403 /* "valid" situation if, for example, receiving some auth or channel request timeouted,
1404 * but we got it now, during session free */
Michal Vasko05532772021-06-03 12:12:38 +02001405 VRB(session, "SSH message arrived on a %s session, the request will be denied.",
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001406 (session && session->status == NC_STATUS_CLOSING ? "closing" : "invalid"));
Michal Vaskoce319162016-02-03 15:33:08 +01001407 ssh_message_reply_default(msg);
1408 return 0;
1409 }
Michal Vasko086311b2016-01-08 09:53:11 +01001410
1411 /*
1412 * process known messages
1413 */
1414 if (type == SSH_REQUEST_AUTH) {
1415 if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
Michal Vasko05532772021-06-03 12:12:38 +02001416 ERR(session, "User \"%s\" authenticated, but requested another authentication.", session->username);
Michal Vasko086311b2016-01-08 09:53:11 +01001417 ssh_message_reply_default(msg);
1418 return 0;
romanf578cd52023-10-19 09:47:40 +02001419 } else if (!state || !opts) {
1420 /* these two parameters should always be set during an authentication,
1421 * however do a check just in case something goes really wrong, since they
1422 * are not needed for other types of messages
1423 */
1424 ERRINT;
1425 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001426 }
1427
Michal Vasko086311b2016-01-08 09:53:11 +01001428 /* save the username, do not let the client change it */
1429 username = ssh_message_auth_user(msg);
romanf578cd52023-10-19 09:47:40 +02001430 assert(username);
1431
1432 for (i = 0; i < opts->client_count; i++) {
1433 if (!strcmp(opts->auth_clients[i].username, username)) {
1434 auth_client = &opts->auth_clients[i];
1435 break;
1436 }
1437 }
1438
1439 if (!auth_client) {
roman78df0fa2023-11-02 10:33:57 +01001440 if (opts->referenced_endpt_name) {
1441 /* client not known by the endpt, but it references another one so try it */
1442 if (nc_server_get_referenced_endpt(opts->referenced_endpt_name, &referenced_endpt)) {
1443 ERRINT;
1444 return 1;
1445 }
1446
1447 return nc_session_ssh_msg(session, referenced_endpt->opts.ssh, msg, state);
Michal Vasko086311b2016-01-08 09:53:11 +01001448 }
1449
roman545879e2024-01-19 14:43:46 +01001450 /* user not known, set his authentication methods to public key only so that
1451 * there is no interaction and it will simply be denied */
romanf578cd52023-10-19 09:47:40 +02001452 ERR(NULL, "User \"%s\" not known by the server.", username);
roman545879e2024-01-19 14:43:46 +01001453 ssh_set_auth_methods(session->ti.libssh.session, SSH_AUTH_METHOD_PUBLICKEY);
romanf578cd52023-10-19 09:47:40 +02001454 ssh_message_reply_default(msg);
1455 return 0;
1456 }
1457
1458 if (!session->username) {
Michal Vasko93224072021-11-09 12:14:28 +01001459 session->username = strdup(username);
romanf578cd52023-10-19 09:47:40 +02001460
1461 /* configure and count accepted auth methods */
1462 if (auth_client->store == NC_STORE_LOCAL) {
1463 if (auth_client->pubkey_count) {
1464 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1465 }
romana9ec3362023-12-21 10:59:57 +01001466 } else if (auth_client->store == NC_STORE_TRUSTSTORE) {
1467 if (auth_client->ts_ref) {
1468 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1469 }
1470 } else if (auth_client->store == NC_STORE_SYSTEM) {
romanf578cd52023-10-19 09:47:40 +02001471 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1472 }
1473 if (auth_client->password) {
1474 state->auth_method_count++;
1475 libssh_auth_methods |= SSH_AUTH_METHOD_PASSWORD;
1476 }
roman808f3f62023-11-23 16:01:04 +01001477 if (auth_client->kb_int_enabled) {
romanf578cd52023-10-19 09:47:40 +02001478 state->auth_method_count++;
1479 libssh_auth_methods |= SSH_AUTH_METHOD_INTERACTIVE;
1480 }
roman808f3f62023-11-23 16:01:04 +01001481 if (auth_client->none_enabled) {
romanf578cd52023-10-19 09:47:40 +02001482 libssh_auth_methods |= SSH_AUTH_METHOD_NONE;
1483 }
1484
1485 if (libssh_auth_methods & SSH_AUTH_METHOD_PUBLICKEY) {
1486 state->auth_method_count++;
1487 }
1488
1489 ssh_set_auth_methods(session->ti.libssh.session, libssh_auth_methods);
1490 } else {
Michal Vasko086311b2016-01-08 09:53:11 +01001491 if (strcmp(username, session->username)) {
romanf578cd52023-10-19 09:47:40 +02001492 /* changing username not allowed */
Michal Vasko05532772021-06-03 12:12:38 +02001493 ERR(session, "User \"%s\" changed its username to \"%s\".", session->username, username);
Michal Vasko086311b2016-01-08 09:53:11 +01001494 session->status = NC_STATUS_INVALID;
Michal Vasko428087d2016-01-14 16:04:28 +01001495 session->term_reason = NC_SESSION_TERM_OTHER;
Michal Vasko086311b2016-01-08 09:53:11 +01001496 return 1;
1497 }
1498 }
1499
romanf578cd52023-10-19 09:47:40 +02001500 /* try authenticating, the user must authenticate via all of his configured auth methods */
Michal Vasko086311b2016-01-08 09:53:11 +01001501 if (subtype == SSH_AUTH_METHOD_NONE) {
romanf578cd52023-10-19 09:47:40 +02001502 nc_sshcb_auth_none(session, auth_client, msg);
1503 ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001504 } else if (subtype == SSH_AUTH_METHOD_PASSWORD) {
romanf578cd52023-10-19 09:47:40 +02001505 ret = nc_sshcb_auth_password(session, auth_client, msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001506 } else if (subtype == SSH_AUTH_METHOD_PUBLICKEY) {
romanf578cd52023-10-19 09:47:40 +02001507 ret = nc_sshcb_auth_pubkey(session, auth_client, msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001508 } else if (subtype == SSH_AUTH_METHOD_INTERACTIVE) {
romane5675b12024-03-05 14:26:23 +01001509 ret = nc_sshcb_auth_kbdint(session, auth_client, msg);
roman4f9e4422024-03-21 10:58:41 +01001510 } else {
1511 VRB(session, "Authentication method \"%s\" not supported.", str_subtype);
1512 ssh_message_reply_default(msg);
1513 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001514 }
romanf578cd52023-10-19 09:47:40 +02001515
1516 if (!ret) {
1517 state->auth_success_count++;
1518 }
1519
1520 if (!ret && (state->auth_success_count < state->auth_method_count)) {
1521 /* success, but he needs to do another method */
1522 VRB(session, "User \"%s\" partially authenticated, but still needs to authenticate via the rest of his configured methods.", username);
1523 ssh_message_auth_reply_success(msg, 1);
1524 } else if (!ret && (state->auth_success_count == state->auth_method_count)) {
1525 /* authenticated */
1526 ssh_message_auth_reply_success(msg, 0);
1527 session->flags |= NC_SESSION_SSH_AUTHENTICATED;
1528 VRB(session, "User \"%s\" authenticated.", username);
1529 }
1530
1531 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001532 } else if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
Michal Vasko0df67562016-01-21 15:50:11 +01001533 if ((type == SSH_REQUEST_CHANNEL_OPEN) && ((enum ssh_channel_type_e)subtype == SSH_CHANNEL_SESSION)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001534 if (nc_sshcb_channel_open(session, msg)) {
Michal Vasko086311b2016-01-08 09:53:11 +01001535 ssh_message_reply_default(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001536 }
Michal Vasko086311b2016-01-08 09:53:11 +01001537 return 0;
Michal Vasko96164bf2016-01-21 15:41:58 +01001538
Michal Vasko0df67562016-01-21 15:50:11 +01001539 } else if ((type == SSH_REQUEST_CHANNEL) && ((enum ssh_channel_requests_e)subtype == SSH_CHANNEL_REQUEST_SUBSYSTEM)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001540 if (nc_sshcb_channel_subsystem(session, ssh_message_channel_request_channel(msg),
1541 ssh_message_channel_request_subsystem(msg))) {
Michal Vasko086311b2016-01-08 09:53:11 +01001542 ssh_message_reply_default(msg);
Michal Vasko96164bf2016-01-21 15:41:58 +01001543 } else {
1544 ssh_message_channel_request_reply_success(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001545 }
1546 return 0;
1547 }
1548 }
1549
1550 /* we did not process it */
1551 return 1;
1552}
1553
Michal Vasko1a38c862016-01-15 15:50:07 +01001554/* ret 1 on success, 0 on timeout, -1 on error */
Michal Vasko086311b2016-01-08 09:53:11 +01001555static int
romanf578cd52023-10-19 09:47:40 +02001556nc_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 +01001557{
roman6ece9c52022-06-22 09:29:17 +02001558 struct timespec ts_timeout;
romanf578cd52023-10-19 09:47:40 +02001559 ssh_message msg;
Michal Vasko086311b2016-01-08 09:53:11 +01001560
romanf578cd52023-10-19 09:47:40 +02001561 if (timeout) {
1562 nc_timeouttime_get(&ts_timeout, timeout * 1000);
Michal Vasko36c7be82017-02-22 13:37:59 +01001563 }
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001564 while (1) {
1565 if (!nc_session_is_connected(session)) {
romanf578cd52023-10-19 09:47:40 +02001566 ERR(session, "Communication SSH socket unexpectedly closed.");
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001567 return -1;
1568 }
1569
romanf578cd52023-10-19 09:47:40 +02001570 msg = ssh_message_get(session->ti.libssh.session);
1571 if (msg) {
1572 if (nc_session_ssh_msg(session, opts, msg, NULL)) {
1573 ssh_message_reply_default(msg);
1574 }
1575 ssh_message_free(msg);
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001576 }
1577
romanf578cd52023-10-19 09:47:40 +02001578 if (session->ti.libssh.channel && session->flags & NC_SESSION_SSH_SUBSYS_NETCONF) {
Michal Vasko1a38c862016-01-15 15:50:07 +01001579 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001580 }
1581
Michal Vasko086311b2016-01-08 09:53:11 +01001582 usleep(NC_TIMEOUT_STEP);
roman0b7e6982024-04-29 11:11:52 +02001583 if (timeout && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
roman6ece9c52022-06-22 09:29:17 +02001584 /* timeout */
1585 ERR(session, "Failed to start \"netconf\" SSH subsystem for too long, disconnecting.");
1586 break;
Michal Vasko36c7be82017-02-22 13:37:59 +01001587 }
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001588 }
Michal Vasko086311b2016-01-08 09:53:11 +01001589
Michal Vasko1a38c862016-01-15 15:50:07 +01001590 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001591}
1592
Michal Vaskof3c41e32022-09-09 11:22:21 +02001593/**
1594 * @brief Set hostkeys to be used for an SSH bind.
1595 *
1596 * @param[in] sbind SSH bind to use.
1597 * @param[in] hostkeys Array of hostkeys.
1598 * @param[in] hostkey_count Count of @p hostkeys.
1599 * @return 0 on success.
1600 * @return -1 on error.
1601 */
Michal Vasko4c1fb492017-01-30 14:31:07 +01001602static int
romanf578cd52023-10-19 09:47:40 +02001603nc_ssh_bind_add_hostkeys(ssh_bind sbind, struct nc_server_ssh_opts *opts, uint16_t hostkey_count)
Michal Vasko4c1fb492017-01-30 14:31:07 +01001604{
romanf578cd52023-10-19 09:47:40 +02001605 uint16_t i;
roman6dfdc0d2023-11-09 13:25:27 +01001606 char *privkey_path;
Michal Vaskoddce1212019-05-24 09:58:49 +02001607 int ret;
romanf578cd52023-10-19 09:47:40 +02001608 struct nc_asymmetric_key *key = NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +01001609
1610 for (i = 0; i < hostkey_count; ++i) {
roman6dfdc0d2023-11-09 13:25:27 +01001611 privkey_path = NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +01001612
romanf578cd52023-10-19 09:47:40 +02001613 /* get the asymmetric key */
1614 if (opts->hostkeys[i].store == NC_STORE_LOCAL) {
1615 /* stored locally */
1616 key = &opts->hostkeys[i].key;
1617 } else {
1618 /* keystore reference, need to get it */
1619 if (nc_server_ssh_ks_ref_get_key(opts->hostkeys[i].ks_ref, &key)) {
Michal Vasko4c1fb492017-01-30 14:31:07 +01001620 return -1;
1621 }
1622 }
1623
romanf578cd52023-10-19 09:47:40 +02001624 privkey_path = base64der_privkey_to_tmp_file(key->privkey_data, nc_privkey_format_to_str(key->privkey_type));
1625 if (!privkey_path) {
1626 ERR(NULL, "Temporarily storing a host key into a file failed (%s).", strerror(errno));
1627 return -1;
1628 }
1629
Michal Vasko4c1fb492017-01-30 14:31:07 +01001630 ret = ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY, privkey_path);
1631
1632 /* cleanup */
roman6dfdc0d2023-11-09 13:25:27 +01001633 if (unlink(privkey_path)) {
Michal Vasko05532772021-06-03 12:12:38 +02001634 WRN(NULL, "Removing a temporary host key file \"%s\" failed (%s).", privkey_path, strerror(errno));
Michal Vasko4c1fb492017-01-30 14:31:07 +01001635 }
Michal Vasko4c1fb492017-01-30 14:31:07 +01001636
1637 if (ret != SSH_OK) {
romanf578cd52023-10-19 09:47:40 +02001638 ERR(NULL, "Failed to set hostkey \"%s\" (%s).", opts->hostkeys[i].name, privkey_path);
Michal Vasko80075de2017-07-10 11:38:52 +02001639 }
1640 free(privkey_path);
1641
1642 if (ret != SSH_OK) {
Michal Vasko4c1fb492017-01-30 14:31:07 +01001643 return -1;
1644 }
1645 }
1646
1647 return 0;
1648}
1649
Michal Vasko09d700f2022-09-08 10:21:40 +02001650static int
romanf578cd52023-10-19 09:47:40 +02001651nc_accept_ssh_session_auth(struct nc_session *session, struct nc_server_ssh_opts *opts)
Michal Vasko3031aae2016-01-27 16:07:18 +01001652{
roman6ece9c52022-06-22 09:29:17 +02001653 struct timespec ts_timeout;
roman41a11e42022-06-22 09:27:08 +02001654 ssh_message msg;
romanf578cd52023-10-19 09:47:40 +02001655 struct nc_auth_state state = {0};
Michal Vasko086311b2016-01-08 09:53:11 +01001656
Michal Vasko086311b2016-01-08 09:53:11 +01001657 /* authenticate */
Michal Vasko36c7be82017-02-22 13:37:59 +01001658 if (opts->auth_timeout) {
Michal Vaskod8a74192023-02-06 15:51:50 +01001659 nc_timeouttime_get(&ts_timeout, opts->auth_timeout * 1000);
Michal Vasko36c7be82017-02-22 13:37:59 +01001660 }
1661 while (1) {
Michal Vasko2a7d4732016-01-15 09:24:46 +01001662 if (!nc_session_is_connected(session)) {
Michal Vasko05532772021-06-03 12:12:38 +02001663 ERR(session, "Communication SSH socket unexpectedly closed.");
Michal Vasko2a7d4732016-01-15 09:24:46 +01001664 return -1;
1665 }
1666
roman41a11e42022-06-22 09:27:08 +02001667 msg = ssh_message_get(session->ti.libssh.session);
1668 if (msg) {
romanf578cd52023-10-19 09:47:40 +02001669 if (nc_session_ssh_msg(session, opts, msg, &state)) {
roman41a11e42022-06-22 09:27:08 +02001670 ssh_message_reply_default(msg);
1671 }
1672 ssh_message_free(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001673 }
1674
Michal Vasko36c7be82017-02-22 13:37:59 +01001675 if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
1676 break;
1677 }
1678
Michal Vasko145ae672017-02-07 10:57:27 +01001679 if (session->opts.server.ssh_auth_attempts >= opts->auth_attempts) {
Michal Vasko05532772021-06-03 12:12:38 +02001680 ERR(session, "Too many failed authentication attempts of user \"%s\".", session->username);
Michal Vasko145ae672017-02-07 10:57:27 +01001681 return -1;
1682 }
1683
Michal Vasko086311b2016-01-08 09:53:11 +01001684 usleep(NC_TIMEOUT_STEP);
romanea0edaa2023-10-26 12:16:25 +02001685 if (opts->auth_timeout && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
roman6ece9c52022-06-22 09:29:17 +02001686 /* timeout */
1687 break;
Michal Vasko36c7be82017-02-22 13:37:59 +01001688 }
1689 }
Michal Vasko086311b2016-01-08 09:53:11 +01001690
1691 if (!(session->flags & NC_SESSION_SSH_AUTHENTICATED)) {
1692 /* timeout */
Michal Vaskoc13da702017-02-07 10:57:57 +01001693 if (session->username) {
Michal Vasko05532772021-06-03 12:12:38 +02001694 ERR(session, "User \"%s\" failed to authenticate for too long, disconnecting.", session->username);
Michal Vaskoc13da702017-02-07 10:57:57 +01001695 } else {
Michal Vasko05532772021-06-03 12:12:38 +02001696 ERR(session, "User failed to authenticate for too long, disconnecting.");
Michal Vaskoc13da702017-02-07 10:57:57 +01001697 }
Michal Vasko1a38c862016-01-15 15:50:07 +01001698 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001699 }
1700
Michal Vasko09d700f2022-09-08 10:21:40 +02001701 return 1;
1702}
1703
1704int
romanf578cd52023-10-19 09:47:40 +02001705nc_accept_ssh_session(struct nc_session *session, struct nc_server_ssh_opts *opts, int sock, int timeout)
Michal Vasko09d700f2022-09-08 10:21:40 +02001706{
1707 ssh_bind sbind = NULL;
Michal Vasko09d700f2022-09-08 10:21:40 +02001708 int rc = 1, r;
1709 struct timespec ts_timeout;
roman4cc0cd52023-04-14 09:12:29 +02001710 const char *err_msg;
Michal Vasko09d700f2022-09-08 10:21:40 +02001711
Michal Vasko09d700f2022-09-08 10:21:40 +02001712 /* other transport-specific data */
roman506354a2024-04-11 09:37:22 +02001713 session->ti_type = NC_TI_SSH;
Michal Vasko09d700f2022-09-08 10:21:40 +02001714 session->ti.libssh.session = ssh_new();
1715 if (!session->ti.libssh.session) {
1716 ERR(NULL, "Failed to initialize a new SSH session.");
1717 rc = -1;
1718 goto cleanup;
1719 }
1720
1721 sbind = ssh_bind_new();
1722 if (!sbind) {
1723 ERR(session, "Failed to create an SSH bind.");
1724 rc = -1;
1725 goto cleanup;
1726 }
1727
1728 /* configure host keys */
romanf578cd52023-10-19 09:47:40 +02001729 if (nc_ssh_bind_add_hostkeys(sbind, opts, opts->hostkey_count)) {
1730 rc = -1;
1731 goto cleanup;
1732 }
1733
1734 /* configure supported algorithms */
1735 if (opts->hostkey_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY_ALGORITHMS, opts->hostkey_algs)) {
1736 rc = -1;
1737 goto cleanup;
1738 }
1739 if (opts->encryption_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_CIPHERS_S_C, opts->encryption_algs)) {
1740 rc = -1;
1741 goto cleanup;
1742 }
1743 if (opts->kex_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_KEY_EXCHANGE, opts->kex_algs)) {
1744 rc = -1;
1745 goto cleanup;
1746 }
1747 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 +02001748 rc = -1;
1749 goto cleanup;
1750 }
1751
1752 /* accept new connection on the bind */
1753 if (ssh_bind_accept_fd(sbind, session->ti.libssh.session, sock) == SSH_ERROR) {
1754 ERR(session, "SSH failed to accept a new connection (%s).", ssh_get_error(sbind));
1755 rc = -1;
1756 goto cleanup;
1757 }
1758 sock = -1;
1759
romanf578cd52023-10-19 09:47:40 +02001760 /* set to non-blocking */
Michal Vasko09d700f2022-09-08 10:21:40 +02001761 ssh_set_blocking(session->ti.libssh.session, 0);
1762
1763 if (timeout > -1) {
Michal Vaskod8a74192023-02-06 15:51:50 +01001764 nc_timeouttime_get(&ts_timeout, timeout);
Michal Vasko09d700f2022-09-08 10:21:40 +02001765 }
1766 while ((r = ssh_handle_key_exchange(session->ti.libssh.session)) == SSH_AGAIN) {
1767 /* this tends to take longer */
1768 usleep(NC_TIMEOUT_STEP * 20);
Michal Vaskod8a74192023-02-06 15:51:50 +01001769 if ((timeout > -1) && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001770 break;
1771 }
1772 }
1773 if (r == SSH_AGAIN) {
1774 ERR(session, "SSH key exchange timeout.");
1775 rc = 0;
1776 goto cleanup;
1777 } else if (r != SSH_OK) {
roman4cc0cd52023-04-14 09:12:29 +02001778 err_msg = ssh_get_error(session->ti.libssh.session);
1779 if (err_msg[0] == '\0') {
1780 err_msg = "hostkey algorithm generated from the hostkey most likely not found in the set of configured hostkey algorithms";
1781 }
1782 ERR(session, "SSH key exchange error (%s).", err_msg);
Michal Vasko09d700f2022-09-08 10:21:40 +02001783 rc = -1;
1784 goto cleanup;
1785 }
1786
romane5675b12024-03-05 14:26:23 +01001787 /* authenticate, store auth_timeout in session so we can retrieve it in kb interactive API */
1788 session->data = &opts->auth_timeout;
1789 rc = nc_accept_ssh_session_auth(session, opts);
1790 session->data = NULL;
1791 if (rc != 1) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001792 goto cleanup;
1793 }
1794
Michal Vasko09d700f2022-09-08 10:21:40 +02001795 /* open channel and request 'netconf' subsystem */
romanf578cd52023-10-19 09:47:40 +02001796 if ((rc = nc_accept_ssh_session_open_netconf_channel(session, opts, timeout)) != 1) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001797 goto cleanup;
Michal Vasko086311b2016-01-08 09:53:11 +01001798 }
1799
Michal Vasko09d700f2022-09-08 10:21:40 +02001800cleanup:
1801 if (sock > -1) {
1802 close(sock);
1803 }
1804 ssh_bind_free(sbind);
1805 return rc;
Michal Vasko086311b2016-01-08 09:53:11 +01001806}
1807
Michal Vasko71090fc2016-05-24 16:37:28 +02001808API NC_MSG_TYPE
1809nc_session_accept_ssh_channel(struct nc_session *orig_session, struct nc_session **session)
1810{
1811 NC_MSG_TYPE msgtype;
1812 struct nc_session *new_session = NULL;
Michal Vasko9f6275e2017-10-05 13:50:05 +02001813 struct timespec ts_cur;
Michal Vasko71090fc2016-05-24 16:37:28 +02001814
roman40672412023-05-04 11:10:22 +02001815 NC_CHECK_ARG_RET(orig_session, orig_session, session, NC_MSG_ERROR);
Michal Vasko71090fc2016-05-24 16:37:28 +02001816
roman506354a2024-04-11 09:37:22 +02001817 if ((orig_session->status == NC_STATUS_RUNNING) && (orig_session->ti_type == NC_TI_SSH) &&
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001818 orig_session->ti.libssh.next) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001819 for (new_session = orig_session->ti.libssh.next;
1820 new_session != orig_session;
1821 new_session = new_session->ti.libssh.next) {
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001822 if ((new_session->status == NC_STATUS_STARTING) && new_session->ti.libssh.channel &&
1823 (new_session->flags & NC_SESSION_SSH_SUBSYS_NETCONF)) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001824 /* we found our session */
1825 break;
1826 }
1827 }
1828 if (new_session == orig_session) {
1829 new_session = NULL;
1830 }
1831 }
1832
1833 if (!new_session) {
Michal Vasko05532772021-06-03 12:12:38 +02001834 ERR(orig_session, "Session does not have a NETCONF SSH channel ready.");
Michal Vasko71090fc2016-05-24 16:37:28 +02001835 return NC_MSG_ERROR;
1836 }
1837
1838 /* assign new SID atomically */
Michal Vasko5bd4a3f2021-06-17 16:40:10 +02001839 new_session->id = ATOMIC_INC_RELAXED(server_opts.new_session_id);
Michal Vasko71090fc2016-05-24 16:37:28 +02001840
1841 /* NETCONF handshake */
Michal Vasko131120a2018-05-29 15:44:02 +02001842 msgtype = nc_handshake_io(new_session);
Michal Vasko71090fc2016-05-24 16:37:28 +02001843 if (msgtype != NC_MSG_HELLO) {
1844 return msgtype;
1845 }
1846
Michal Vaskod8a74192023-02-06 15:51:50 +01001847 nc_realtime_get(&ts_cur);
roman44efa322023-11-03 13:57:25 +01001848 new_session->opts.server.session_start = ts_cur;
Michal Vaskod8a74192023-02-06 15:51:50 +01001849 nc_timeouttime_get(&ts_cur, 0);
Michal Vasko9f6275e2017-10-05 13:50:05 +02001850 new_session->opts.server.last_rpc = ts_cur.tv_sec;
Michal Vasko71090fc2016-05-24 16:37:28 +02001851 new_session->status = NC_STATUS_RUNNING;
1852 *session = new_session;
1853
1854 return msgtype;
1855}
1856
1857API NC_MSG_TYPE
Michal Vasko96164bf2016-01-21 15:41:58 +01001858nc_ps_accept_ssh_channel(struct nc_pollsession *ps, struct nc_session **session)
Michal Vasko086311b2016-01-08 09:53:11 +01001859{
Michal Vaskobdcf2362016-07-26 11:35:43 +02001860 uint8_t q_id;
Michal Vasko71090fc2016-05-24 16:37:28 +02001861 NC_MSG_TYPE msgtype;
Michal Vaskoe4300a82017-05-24 10:35:42 +02001862 struct nc_session *new_session = NULL, *cur_session;
Michal Vasko9f6275e2017-10-05 13:50:05 +02001863 struct timespec ts_cur;
Michal Vaskoc61c4492016-01-25 11:13:34 +01001864 uint16_t i;
Michal Vasko086311b2016-01-08 09:53:11 +01001865
roman40672412023-05-04 11:10:22 +02001866 NC_CHECK_ARG_RET(NULL, ps, session, NC_MSG_ERROR);
Michal Vasko086311b2016-01-08 09:53:11 +01001867
Michal Vasko48a63ed2016-03-01 09:48:21 +01001868 /* LOCK */
Michal Vasko227f8ff2016-07-26 14:08:59 +02001869 if (nc_ps_lock(ps, &q_id, __func__)) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001870 return NC_MSG_ERROR;
Michal Vaskof04a52a2016-04-07 10:52:10 +02001871 }
Michal Vasko48a63ed2016-03-01 09:48:21 +01001872
Michal Vasko96164bf2016-01-21 15:41:58 +01001873 for (i = 0; i < ps->session_count; ++i) {
fanchanghu3d4e7212017-08-09 09:42:30 +08001874 cur_session = ps->sessions[i]->session;
roman506354a2024-04-11 09:37:22 +02001875 if ((cur_session->status == NC_STATUS_RUNNING) && (cur_session->ti_type == NC_TI_SSH) &&
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001876 cur_session->ti.libssh.next) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001877 /* an SSH session with more channels */
Michal Vaskoe4300a82017-05-24 10:35:42 +02001878 for (new_session = cur_session->ti.libssh.next;
1879 new_session != cur_session;
Michal Vasko96164bf2016-01-21 15:41:58 +01001880 new_session = new_session->ti.libssh.next) {
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001881 if ((new_session->status == NC_STATUS_STARTING) && new_session->ti.libssh.channel &&
1882 (new_session->flags & NC_SESSION_SSH_SUBSYS_NETCONF)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001883 /* we found our session */
1884 break;
1885 }
1886 }
Michal Vaskoe4300a82017-05-24 10:35:42 +02001887 if (new_session != cur_session) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001888 break;
1889 }
Michal Vaskofb89d772016-01-08 12:25:35 +01001890
Michal Vasko96164bf2016-01-21 15:41:58 +01001891 new_session = NULL;
1892 }
1893 }
Michal Vaskofb89d772016-01-08 12:25:35 +01001894
Michal Vasko48a63ed2016-03-01 09:48:21 +01001895 /* UNLOCK */
Michal Vasko227f8ff2016-07-26 14:08:59 +02001896 nc_ps_unlock(ps, q_id, __func__);
Michal Vasko48a63ed2016-03-01 09:48:21 +01001897
Michal Vasko96164bf2016-01-21 15:41:58 +01001898 if (!new_session) {
Michal Vasko05532772021-06-03 12:12:38 +02001899 ERR(NULL, "No session with a NETCONF SSH channel ready was found.");
Michal Vasko71090fc2016-05-24 16:37:28 +02001900 return NC_MSG_ERROR;
Michal Vasko96164bf2016-01-21 15:41:58 +01001901 }
1902
1903 /* assign new SID atomically */
Michal Vasko5bd4a3f2021-06-17 16:40:10 +02001904 new_session->id = ATOMIC_INC_RELAXED(server_opts.new_session_id);
Michal Vaskofb89d772016-01-08 12:25:35 +01001905
Michal Vasko086311b2016-01-08 09:53:11 +01001906 /* NETCONF handshake */
Michal Vasko131120a2018-05-29 15:44:02 +02001907 msgtype = nc_handshake_io(new_session);
Michal Vasko71090fc2016-05-24 16:37:28 +02001908 if (msgtype != NC_MSG_HELLO) {
1909 return msgtype;
Michal Vasko086311b2016-01-08 09:53:11 +01001910 }
Michal Vasko48a63ed2016-03-01 09:48:21 +01001911
Michal Vaskod8a74192023-02-06 15:51:50 +01001912 nc_realtime_get(&ts_cur);
roman44efa322023-11-03 13:57:25 +01001913 new_session->opts.server.session_start = ts_cur;
Michal Vaskod8a74192023-02-06 15:51:50 +01001914 nc_timeouttime_get(&ts_cur, 0);
Michal Vasko9f6275e2017-10-05 13:50:05 +02001915 new_session->opts.server.last_rpc = ts_cur.tv_sec;
Michal Vasko086311b2016-01-08 09:53:11 +01001916 new_session->status = NC_STATUS_RUNNING;
Michal Vasko96164bf2016-01-21 15:41:58 +01001917 *session = new_session;
Michal Vasko086311b2016-01-08 09:53:11 +01001918
Michal Vasko71090fc2016-05-24 16:37:28 +02001919 return msgtype;
Michal Vasko086311b2016-01-08 09:53:11 +01001920}