blob: 0018848a3bf88d7be36946a73cb5f64836636808 [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>
Michal Vaskob83a3fa2021-05-26 09:53:42 +020029#include <errno.h>
romanf578cd52023-10-19 09:47:40 +020030#include <libssh/libssh.h>
31#include <libssh/server.h>
32#include <libyang/libyang.h>
33#include <openssl/bio.h>
34#include <openssl/err.h>
35#include <openssl/evp.h>
Michal Vaskob83a3fa2021-05-26 09:53:42 +020036#include <pwd.h>
romanf578cd52023-10-19 09:47:40 +020037#include <stdint.h>
Michal Vasko086311b2016-01-08 09:53:11 +010038#include <stdlib.h>
39#include <string.h>
Michal Vasko27252692017-03-21 15:34:13 +010040#include <sys/stat.h>
Michal Vaskob83a3fa2021-05-26 09:53:42 +020041#include <sys/types.h>
Michal Vasko9f6275e2017-10-05 13:50:05 +020042#include <time.h>
Claus Klein22091912020-01-20 13:45:47 +010043#include <unistd.h>
Michal Vasko086311b2016-01-08 09:53:11 +010044
Michal Vasko7a20d2e2021-05-19 16:40:23 +020045#include "compat.h"
romanf578cd52023-10-19 09:47:40 +020046#include "log_p.h"
47#include "session.h"
48#include "session_p.h"
Michal Vasko086311b2016-01-08 09:53:11 +010049
50extern struct nc_server_opts server_opts;
Michal Vaskob05053d2016-01-22 16:12:06 +010051
Michal Vasko4c1fb492017-01-30 14:31:07 +010052static char *
romanf578cd52023-10-19 09:47:40 +020053base64der_privkey_to_tmp_file(const char *in, const char *privkey_format)
Michal Vasko086311b2016-01-08 09:53:11 +010054{
Michal Vasko4c1fb492017-01-30 14:31:07 +010055 char path[12] = "/tmp/XXXXXX";
56 int fd, written;
romanf578cd52023-10-19 09:47:40 +020057 unsigned len;
Michal Vasko27252692017-03-21 15:34:13 +010058 mode_t umode;
Michal Vasko4c1fb492017-01-30 14:31:07 +010059 FILE *file;
60
romanf578cd52023-10-19 09:47:40 +020061 NC_CHECK_ARG_RET(NULL, in, NULL);
Michal Vasko086311b2016-01-08 09:53:11 +010062
mekleob31878b2019-09-09 14:10:47 +020063 umode = umask(0177);
Michal Vasko4c1fb492017-01-30 14:31:07 +010064 fd = mkstemp(path);
Michal Vasko27252692017-03-21 15:34:13 +010065 umask(umode);
Michal Vasko4c1fb492017-01-30 14:31:07 +010066 if (fd == -1) {
67 return NULL;
68 }
69
Michal Vasko3964a832018-09-18 14:37:39 +020070 file = fdopen(fd, "w");
Michal Vasko4c1fb492017-01-30 14:31:07 +010071 if (!file) {
72 close(fd);
73 return NULL;
74 }
75
romanf578cd52023-10-19 09:47:40 +020076 /* write header */
77 written = fwrite("-----BEGIN ", 1, 11, file);
78 if (privkey_format) {
79 written += fwrite(privkey_format, 1, strlen(privkey_format), file);
Michal Vasko68177b72020-04-27 15:46:53 +020080 written += fwrite(" PRIVATE KEY-----\n", 1, 18, file);
Michal Vasko68177b72020-04-27 15:46:53 +020081 } else {
romanf578cd52023-10-19 09:47:40 +020082 written += fwrite("PRIVATE KEY-----\n", 1, 17, file);
83 }
Michal Vasko68177b72020-04-27 15:46:53 +020084
romanf578cd52023-10-19 09:47:40 +020085 /* write data */
86 written += fwrite(in, 1, strlen(in), file);
87
88 /* write footer */
89 written += fwrite("\n-----END ", 1, 10, file);
90 if (privkey_format) {
91 written += fwrite(privkey_format, 1, strlen(privkey_format), file);
92 written += fwrite(" PRIVATE KEY-----", 1, 17, file);
93 } else {
94 written += fwrite("PRIVATE KEY-----", 1, 16, file);
95 }
96
97 fclose(file);
98
99 /* checksum */
100 if (privkey_format) {
101 len = 11 + strlen(privkey_format) + 18 + strlen(in) + 10 + strlen(privkey_format) + 17;
102 } else {
103 len = 11 + 17 + strlen(in) + 10 + 16;
104 }
105
106 if ((unsigned)written != len) {
107 unlink(path);
108 return NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +0100109 }
110
111 return strdup(path);
112}
113
114static int
romanf578cd52023-10-19 09:47:40 +0200115nc_server_ssh_ks_ref_get_key(const char *referenced_name, struct nc_asymmetric_key **askey)
Michal Vasko4c1fb492017-01-30 14:31:07 +0100116{
romanf578cd52023-10-19 09:47:40 +0200117 uint16_t i;
118 struct nc_keystore *ks = &server_opts.keystore;
Michal Vaskofbfe8b62017-02-14 10:22:30 +0100119
romanf578cd52023-10-19 09:47:40 +0200120 *askey = NULL;
Michal Vaskod45e25a2016-01-08 15:48:44 +0100121
romanf578cd52023-10-19 09:47:40 +0200122 /* lookup name */
123 for (i = 0; i < ks->asym_key_count; i++) {
124 if (!strcmp(referenced_name, ks->asym_keys[i].name)) {
125 break;
Michal Vaskofbfe8b62017-02-14 10:22:30 +0100126 }
127 }
128
romanf578cd52023-10-19 09:47:40 +0200129 if (i == ks->asym_key_count) {
130 ERR(NULL, "Keystore entry \"%s\" not found.", referenced_name);
131 return 1;
Michal Vaskoe2713da2016-08-22 16:06:40 +0200132 }
Michal Vasko7d255882017-02-09 13:35:08 +0100133
romanf578cd52023-10-19 09:47:40 +0200134 *askey = &ks->asym_keys[i];
135
136 /* check if the referenced public key is SubjectPublicKeyInfo */
137 if ((*askey)->pubkey_data && nc_is_pk_subject_public_key_info((*askey)->pubkey_data)) {
138 ERR(NULL, "The public key of the referenced hostkey \"%s\" is in the SubjectPublicKeyInfo format, "
139 "which is not allowed in the SSH!", referenced_name);
140 return 1;
Michal Vasko7d255882017-02-09 13:35:08 +0100141 }
Michal Vaskoe2713da2016-08-22 16:06:40 +0200142
Michal Vasko5fcc7142016-02-02 12:21:10 +0100143 return 0;
Michal Vaskob05053d2016-01-22 16:12:06 +0100144}
145
romanf578cd52023-10-19 09:47:40 +0200146static int
147nc_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 +0100148{
romanf578cd52023-10-19 09:47:40 +0200149 uint16_t i, j;
150 struct nc_truststore *ts = &server_opts.truststore;
Michal Vasko3031aae2016-01-27 16:07:18 +0100151
romanf578cd52023-10-19 09:47:40 +0200152 *pubkeys = NULL;
153 *pubkey_count = 0;
154
155 /* lookup name */
156 for (i = 0; i < ts->pub_bag_count; i++) {
157 if (!strcmp(referenced_name, ts->pub_bags[i].name)) {
158 break;
159 }
Michal Vasko3031aae2016-01-27 16:07:18 +0100160 }
Michal Vaskoc46b3df2021-07-26 09:30:05 +0200161
romanf578cd52023-10-19 09:47:40 +0200162 if (i == ts->pub_bag_count) {
163 ERR(NULL, "Truststore entry \"%s\" not found.", referenced_name);
164 return 1;
165 }
Michal Vaskoc46b3df2021-07-26 09:30:05 +0200166
romanf578cd52023-10-19 09:47:40 +0200167 /* check if any of the referenced public keys is SubjectPublicKeyInfo */
168 for (j = 0; j < ts->pub_bags[i].pubkey_count; j++) {
169 if (nc_is_pk_subject_public_key_info(ts->pub_bags[i].pubkeys[j].data)) {
170 ERR(NULL, "A public key of the referenced public key bag \"%s\" is in the SubjectPublicKeyInfo format, "
171 "which is not allowed in the SSH!", referenced_name);
172 return 1;
173 }
174 }
Michal Vasko3031aae2016-01-27 16:07:18 +0100175
romanf578cd52023-10-19 09:47:40 +0200176 *pubkeys = ts->pub_bags[i].pubkeys;
177 *pubkey_count = ts->pub_bags[i].pubkey_count;
178 return 0;
Michal Vaskob05053d2016-01-22 16:12:06 +0100179}
180
Michal Vaskof3c41e32022-09-09 11:22:21 +0200181/**
182 * @brief Compare hashed password with a cleartext password for a match.
183 *
184 * @param[in] pass_hash Hashed password.
185 * @param[in] pass_clear Cleartext password.
186 * @return 0 on match.
187 * @return non-zero if not a match.
188 */
Michal Vasko086311b2016-01-08 09:53:11 +0100189static int
roman814f5112023-10-19 15:51:16 +0200190auth_password_compare_pwd(const char *stored_pw, const char *received_pw)
Michal Vasko086311b2016-01-08 09:53:11 +0100191{
roman814f5112023-10-19 15:51:16 +0200192 char *received_pw_hash = NULL;
roman8b1a6c32023-10-26 13:35:22 +0200193 struct crypt_data cdata = {0};
Michal Vasko086311b2016-01-08 09:53:11 +0100194
roman814f5112023-10-19 15:51:16 +0200195 if (!stored_pw[0]) {
196 if (!received_pw[0]) {
Michal Vasko05532772021-06-03 12:12:38 +0200197 WRN(NULL, "User authentication successful with an empty password!");
Michal Vasko086311b2016-01-08 09:53:11 +0100198 return 0;
199 } else {
200 /* the user did now know he does not need any password,
201 * (which should not be used) so deny authentication */
202 return 1;
203 }
204 }
205
roman814f5112023-10-19 15:51:16 +0200206 if (!strncmp(stored_pw, "$0$", 3)) {
207 /* cleartext password, simply compare the values */
208 return strcmp(stored_pw + 3, received_pw);
209 }
210
roman814f5112023-10-19 15:51:16 +0200211 received_pw_hash = crypt_r(received_pw, stored_pw, &cdata);
roman814f5112023-10-19 15:51:16 +0200212 if (!received_pw_hash) {
roman8b1a6c32023-10-26 13:35:22 +0200213 ERR(NULL, "Hashing the password failed (%s).", strerror(errno));
Andrew Langefeld158d6fd2018-06-11 18:51:44 -0500214 return 1;
215 }
216
roman814f5112023-10-19 15:51:16 +0200217 return strcmp(received_pw_hash, stored_pw);
Michal Vasko086311b2016-01-08 09:53:11 +0100218}
219
romanf578cd52023-10-19 09:47:40 +0200220static int
221nc_sshcb_auth_password(struct nc_session *session, struct nc_auth_client *auth_client, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +0100222{
Michal Vaskoebba7602018-03-23 13:14:08 +0100223 int auth_ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +0100224
roman9130fc12023-11-03 13:56:23 +0100225 auth_ret = auth_password_compare_pwd(auth_client->password, ssh_message_auth_password(msg));
Michal Vasko086311b2016-01-08 09:53:11 +0100226
romanf578cd52023-10-19 09:47:40 +0200227 if (auth_ret) {
Michal Vaskoebba7602018-03-23 13:14:08 +0100228 ++session->opts.server.ssh_auth_attempts;
Michal Vasko05532772021-06-03 12:12:38 +0200229 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", session->username,
230 session->opts.server.ssh_auth_attempts);
Michal Vaskoebba7602018-03-23 13:14:08 +0100231 ssh_message_reply_default(msg);
232 }
romanf578cd52023-10-19 09:47:40 +0200233
234 return auth_ret;
Michal Vasko086311b2016-01-08 09:53:11 +0100235}
236
romanc6518422023-11-30 16:39:00 +0100237/* get answers to kbdint prompts on the given libssh session and return the number of them, -1 on timeout/dc */
238static int
239nc_server_ssh_kbdint_get_nanswers(struct nc_session *session, ssh_session libssh_session, uint16_t auth_timeout)
240{
241 int ret = 0;
242 struct timespec ts_timeout = {0};
roman56c85c02023-12-07 13:09:28 +0100243 ssh_message reply = NULL;
romanc6518422023-11-30 16:39:00 +0100244
245 if (auth_timeout) {
246 nc_timeouttime_get(&ts_timeout, auth_timeout * 1000);
247 }
248
249 /* wait for answers from the client */
250 do {
251 if (!nc_session_is_connected(session)) {
252 ERR(NULL, "SSH communication socket unexpectedly closed.");
253 ret = -1;
254 goto cleanup;
255 }
256
257 reply = ssh_message_get(libssh_session);
258 if (reply) {
259 break;
260 }
261
262 usleep(NC_TIMEOUT_STEP);
263 } while (auth_timeout && (nc_timeouttime_cur_diff(&ts_timeout) >= 1));
264 if (!reply) {
265 ERR(NULL, "Authentication timeout.");
266 ret = -1;
267 goto cleanup;
268 }
269
270 ret = ssh_userauth_kbdint_getnanswers(libssh_session);
271
272cleanup:
273 ssh_message_free(reply);
274 return ret;
275}
276
Michal Vasko0d81c572022-09-26 10:39:31 +0200277#ifdef HAVE_LIBPAM
278
roman41a11e42022-06-22 09:27:08 +0200279/**
280 * @brief PAM conversation function, which serves as a callback for exchanging messages between the client and a PAM module.
281 *
282 * @param[in] n_messages Number of messages.
283 * @param[in] msg PAM module's messages.
284 * @param[out] resp User responses.
285 * @param[in] appdata_ptr Callback's data.
roman808f3f62023-11-23 16:01:04 +0100286 * @return PAM_SUCCESS on success, PAM_BUF_ERR on memory allocation error, PAM_CONV_ERR otherwise.
roman41a11e42022-06-22 09:27:08 +0200287 */
288static int
289nc_pam_conv_clb(int n_messages, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr)
290{
291 int i, j, t, r = PAM_SUCCESS, n_answers, n_requests = n_messages;
292 const char **prompts = NULL;
293 char *echo = NULL;
294 const char *name = "Keyboard-Interactive Authentication";
295 const char *instruction = "Please enter your authentication token";
296 ssh_message reply = NULL;
297 struct nc_pam_thread_arg *clb_data = appdata_ptr;
298 ssh_session libssh_session;
roman808f3f62023-11-23 16:01:04 +0100299 uint16_t auth_timeout;
roman41a11e42022-06-22 09:27:08 +0200300
301 libssh_session = clb_data->session->ti.libssh.session;
roman808f3f62023-11-23 16:01:04 +0100302 auth_timeout = clb_data->auth_timeout;
roman41a11e42022-06-22 09:27:08 +0200303
304 /* PAM_MAX_NUM_MSG == 32 by default */
305 if ((n_messages <= 0) || (n_messages >= PAM_MAX_NUM_MSG)) {
romanc6518422023-11-30 16:39:00 +0100306 ERR(clb_data->session, "Bad number of PAM messages (#%d).", n_messages);
roman41a11e42022-06-22 09:27:08 +0200307 r = PAM_CONV_ERR;
308 goto cleanup;
309 }
310
311 /* only accepting these 4 types of messages */
312 for (i = 0; i < n_messages; i++) {
313 t = msg[i]->msg_style;
314 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 +0100315 ERR(clb_data->session, "PAM conversation callback received an unexpected type of message.");
roman41a11e42022-06-22 09:27:08 +0200316 r = PAM_CONV_ERR;
317 goto cleanup;
318 }
319 }
320
321 /* display messages with errors and/or some information and count the amount of actual authentication challenges */
322 for (i = 0; i < n_messages; i++) {
323 if (msg[i]->msg_style == PAM_TEXT_INFO) {
romanc6518422023-11-30 16:39:00 +0100324 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 +0200325 n_requests--;
326 }
327 if (msg[i]->msg_style == PAM_ERROR_MSG) {
romanc6518422023-11-30 16:39:00 +0100328 ERR(clb_data->session, "PAM conversation callback received an error message (%s).", msg[i]->msg);
roman41a11e42022-06-22 09:27:08 +0200329 r = PAM_CONV_ERR;
330 goto cleanup;
331 }
332 }
333
334 /* there are no requests left for the user, only messages with some information for the client were sent */
335 if (n_requests <= 0) {
336 r = PAM_SUCCESS;
337 goto cleanup;
338 }
339
340 /* it is the PAM module's responsibility to release both, this array and the responses themselves */
341 *resp = calloc(n_requests, sizeof **resp);
342 prompts = calloc(n_requests, sizeof *prompts);
343 echo = calloc(n_requests, sizeof *echo);
roman3a95bb22023-10-26 11:07:17 +0200344 NC_CHECK_ERRMEM_GOTO(!(*resp) || !prompts || !echo, r = PAM_BUF_ERR, cleanup);
roman41a11e42022-06-22 09:27:08 +0200345
346 /* set the prompts for the user */
347 j = 0;
348 for (i = 0; i < n_messages; i++) {
349 if ((msg[i]->msg_style == PAM_PROMPT_ECHO_ON) || (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF)) {
350 prompts[j++] = msg[i]->msg;
351 }
352 }
353
354 /* iterate over all the messages and adjust the echo array accordingly */
355 j = 0;
356 for (i = 0; i < n_messages; i++) {
357 if (msg[i]->msg_style == PAM_PROMPT_ECHO_ON) {
358 echo[j++] = 1;
359 }
360 if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF) {
361 /* no need to set to 0 because of calloc */
362 j++;
363 }
364 }
365
366 /* print all the keyboard-interactive challenges to the user */
367 r = ssh_message_auth_interactive_request(clb_data->msg, name, instruction, n_requests, prompts, echo);
368 if (r != SSH_OK) {
romanc6518422023-11-30 16:39:00 +0100369 ERR(clb_data->session, "Failed to send an authentication request.");
roman41a11e42022-06-22 09:27:08 +0200370 r = PAM_CONV_ERR;
371 goto cleanup;
372 }
373
romanc6518422023-11-30 16:39:00 +0100374 n_answers = nc_server_ssh_kbdint_get_nanswers(clb_data->session, libssh_session, auth_timeout);
375 if (n_answers < 0) {
376 /* timeout or dc */
roman41a11e42022-06-22 09:27:08 +0200377 r = PAM_CONV_ERR;
378 goto cleanup;
romanc6518422023-11-30 16:39:00 +0100379 } else if (n_answers != n_requests) {
380 /* check if the number of answers and requests matches */
381 ERR(clb_data->session, "Expected %d response(s), got %d.", n_requests, n_answers);
roman41a11e42022-06-22 09:27:08 +0200382 r = PAM_CONV_ERR;
383 goto cleanup;
384 }
385
386 /* give the replies to a PAM module */
387 for (i = 0; i < n_answers; i++) {
388 (*resp)[i].resp = strdup(ssh_userauth_kbdint_getanswer(libssh_session, i));
389 /* it should be the caller's responsibility to free this, however if mem alloc fails,
390 * it is safer to free the responses here and set them to NULL */
391 if ((*resp)[i].resp == NULL) {
392 for (j = 0; j < i; j++) {
393 free((*resp)[j].resp);
394 (*resp)[j].resp = NULL;
395 }
396 ERRMEM;
397 r = PAM_BUF_ERR;
398 goto cleanup;
399 }
400 }
401
402cleanup:
403 ssh_message_free(reply);
404 free(prompts);
405 free(echo);
406 return r;
407}
408
409/**
410 * @brief Handles authentication via Linux PAM.
411 *
412 * @param[in] session NETCONF session.
413 * @param[in] ssh_msg SSH message with a keyboard-interactive authentication request.
414 * @return PAM_SUCCESS on success;
415 * @return PAM error otherwise.
416 */
417static int
roman808f3f62023-11-23 16:01:04 +0100418nc_pam_auth(struct nc_session *session, struct nc_auth_client *client, uint16_t auth_timeout, ssh_message ssh_msg)
roman41a11e42022-06-22 09:27:08 +0200419{
420 pam_handle_t *pam_h = NULL;
421 int ret;
422 struct nc_pam_thread_arg clb_data;
423 struct pam_conv conv;
424
425 /* structure holding callback's data */
426 clb_data.msg = ssh_msg;
427 clb_data.session = session;
roman808f3f62023-11-23 16:01:04 +0100428 clb_data.auth_timeout = auth_timeout;
roman41a11e42022-06-22 09:27:08 +0200429
430 /* PAM conversation structure holding the callback and it's data */
431 conv.conv = nc_pam_conv_clb;
432 conv.appdata_ptr = &clb_data;
433
roman808f3f62023-11-23 16:01:04 +0100434 if (!server_opts.pam_config_name) {
romanc6518422023-11-30 16:39:00 +0100435 ERR(session, "PAM configuration filename not set.");
romanf578cd52023-10-19 09:47:40 +0200436 ret = 1;
437 goto cleanup;
438 }
439
roman41a11e42022-06-22 09:27:08 +0200440 /* initialize PAM and see if the given configuration file exists */
roman808f3f62023-11-23 16:01:04 +0100441 ret = pam_start(server_opts.pam_config_name, client->username, &conv, &pam_h);
roman41a11e42022-06-22 09:27:08 +0200442 if (ret != PAM_SUCCESS) {
romanc6518422023-11-30 16:39:00 +0100443 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200444 goto cleanup;
445 }
446
447 /* authentication based on the modules listed in the configuration file */
448 ret = pam_authenticate(pam_h, 0);
449 if (ret != PAM_SUCCESS) {
450 if (ret == PAM_ABORT) {
romanc6518422023-11-30 16:39:00 +0100451 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200452 goto cleanup;
453 } else {
romanc6518422023-11-30 16:39:00 +0100454 VRB(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200455 goto cleanup;
456 }
457 }
458
459 /* correct token entered, check other requirements(the time of the day, expired token, ...) */
460 ret = pam_acct_mgmt(pam_h, 0);
461 if ((ret != PAM_SUCCESS) && (ret != PAM_NEW_AUTHTOK_REQD)) {
romanc6518422023-11-30 16:39:00 +0100462 VRB(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200463 goto cleanup;
464 }
465
466 /* if a token has expired a new one will be generated */
467 if (ret == PAM_NEW_AUTHTOK_REQD) {
romanc6518422023-11-30 16:39:00 +0100468 VRB(session, "PAM warning occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200469 ret = pam_chauthtok(pam_h, PAM_CHANGE_EXPIRED_AUTHTOK);
470 if (ret == PAM_SUCCESS) {
romanc6518422023-11-30 16:39:00 +0100471 VRB(session, "The authentication token of user \"%s\" updated successfully.", client->username);
roman41a11e42022-06-22 09:27:08 +0200472 } else {
romanc6518422023-11-30 16:39:00 +0100473 ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200474 goto cleanup;
475 }
476 }
477
478cleanup:
479 /* destroy the PAM context */
roman6dfdc0d2023-11-09 13:25:27 +0100480 if (pam_h && (pam_end(pam_h, ret) != PAM_SUCCESS)) {
romancab602e2023-11-24 11:30:32 +0100481 ERR(NULL, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
roman41a11e42022-06-22 09:27:08 +0200482 }
483 return ret;
484}
485
romanc6518422023-11-30 16:39:00 +0100486#elif defined (HAVE_SHADOW)
487
488static struct passwd *
489nc_server_ssh_getpwnam(const char *username, struct passwd *pwd_buf, char **buf, size_t *buf_size)
490{
491 struct passwd *pwd = NULL;
492 char *mem;
493 int r = 0;
494
495 do {
496 r = getpwnam_r(username, pwd_buf, *buf, *buf_size, &pwd);
497 if (pwd) {
498 /* entry found */
499 break;
500 }
501
502 if (r == ERANGE) {
503 /* small buffer, enlarge */
504 *buf_size <<= 2;
505 mem = realloc(*buf, *buf_size);
506 if (!mem) {
507 ERRMEM;
508 return NULL;
509 }
510 *buf = mem;
511 }
512 } while (r == ERANGE);
513
514 return pwd;
515}
516
517static struct spwd *
518nc_server_ssh_getspnam(const char *username, struct spwd *spwd_buf, char **buf, size_t *buf_size)
519{
520 struct spwd *spwd = NULL;
521 char *mem;
522 int r = 0;
523
524 do {
525# ifndef __QNXNTO__
526 r = getspnam_r(username, spwd_buf, *buf, *buf_size, &spwd);
527# else
528 spwd = getspnam_r(username, spwd_buf, *buf, *buf_size);
529# endif
530 if (spwd) {
531 /* entry found */
532 break;
533 }
534
535 if (r == ERANGE) {
536 /* small buffer, enlarge */
537 *buf_size <<= 2;
538 mem = realloc(*buf, *buf_size);
539 if (!mem) {
540 ERRMEM;
541 return NULL;
542 }
543 *buf = mem;
544 }
545 } while (r == ERANGE);
546
547 return spwd;
548}
549
550static char *
551nc_server_ssh_get_pwd_hash(const char *username)
552{
553 struct passwd *pwd, pwd_buf;
554 struct spwd *spwd, spwd_buf;
555 char *pass_hash = NULL, *buf = NULL;
556 size_t buf_size = 256;
557
558 buf = malloc(buf_size);
559 NC_CHECK_ERRMEM_GOTO(!buf, , error);
560
561 pwd = nc_server_ssh_getpwnam(username, &pwd_buf, &buf, &buf_size);
562 if (!pwd) {
563 VRB(NULL, "User \"%s\" not found locally.", username);
564 goto error;
565 }
566
567 if (!strcmp(pwd->pw_passwd, "x")) {
568 spwd = nc_server_ssh_getspnam(username, &spwd_buf, &buf, &buf_size);
569 if (!spwd) {
570 VRB(NULL, "Failed to retrieve the shadow entry for \"%s\".", username);
571 goto error;
572 } else if ((spwd->sp_expire > -1) && (spwd->sp_expire <= (time(NULL) / (60 * 60 * 24)))) {
573 WRN(NULL, "User \"%s\" account has expired.", username);
574 goto error;
575 }
576
577 pass_hash = spwd->sp_pwdp;
578 } else {
579 pass_hash = pwd->pw_passwd;
580 }
581
582 if (!pass_hash) {
583 ERR(NULL, "No password could be retrieved for \"%s\".", username);
584 goto error;
585 }
586
587 /* check the hash structure for special meaning */
588 if (!strcmp(pass_hash, "*") || !strcmp(pass_hash, "!")) {
589 VRB(NULL, "User \"%s\" is not allowed to authenticate using a password.", username);
590 goto error;
591 }
592 if (!strcmp(pass_hash, "*NP*")) {
593 VRB(NULL, "Retrieving password for \"%s\" from a NIS+ server not supported.", username);
594 goto error;
595 }
596
597 pass_hash = strdup(pass_hash);
598 free(buf);
599 return pass_hash;
600
601error:
602 free(buf);
603 return NULL;
604}
605
606/**
607 * @brief Authenticate using locally stored credentials.
608 *
609 * @param[in] session Session to authenticate on.
610 * @param[in] client Client to authenticate.
611 * @param[in] auth_timeout Authentication timeout.
612 * @param[in] msg SSH message that originally requested kbdint authentication.
613 *
614 * @return 0 on success, non-zero otherwise.
615 */
616static int
617nc_server_ssh_system_auth(struct nc_session *session, struct nc_auth_client *client, uint16_t auth_timeout, ssh_message msg)
618{
619 int ret = 0, n_answers;
620 const char *name = "Keyboard-Interactive Authentication";
621 const char *instruction = "Please enter your authentication token";
622 char *prompt = NULL, *local_pw = NULL, *received_pw = NULL;
623 char echo[] = {0};
624
625 /* try to get the client's locally stored pw hash */
626 local_pw = nc_server_ssh_get_pwd_hash(client->username);
627 if (!local_pw) {
628 ERR(session, "Unable to get %s's credentials.", client->username);
629 ret = 1;
630 goto cleanup;
631 }
632
633 ret = asprintf(&prompt, "%s's password:", client->username);
634 NC_CHECK_ERRMEM_GOTO(ret == -1, prompt = NULL; ret = 1, cleanup);
635
636 /* send the password prompt to the client */
637 ret = ssh_message_auth_interactive_request(msg, name, instruction, 1, (const char **) &prompt, echo);
638 if (ret) {
639 ERR(session, "Failed to send an authentication request to client \"%s\".", client->username);
640 goto cleanup;
641 }
642
643 /* get the reply */
644 n_answers = nc_server_ssh_kbdint_get_nanswers(session, session->ti.libssh.session, auth_timeout);
645 if (n_answers < 0) {
646 /* timeout or dc */
647 ret = 1;
648 goto cleanup;
649 } else if (n_answers != 1) {
650 /* only expecting a single answer */
651 ERR(session, "Unexpected amount of answers in system auth. Expected 1, got \"%d\".", n_answers);
652 ret = 1;
653 goto cleanup;
654 }
655 received_pw = strdup(ssh_userauth_kbdint_getanswer(session->ti.libssh.session, 0));
656 NC_CHECK_ERRMEM_GOTO(!received_pw, ret = 1, cleanup);
657
658 /* cmp the pw hashes */
659 ret = auth_password_compare_pwd(local_pw, received_pw);
660
661cleanup:
662 free(local_pw);
663 free(received_pw);
664 free(prompt);
665 return ret;
666}
667
668#endif
Michal Vasko0d81c572022-09-26 10:39:31 +0200669
romanf578cd52023-10-19 09:47:40 +0200670static int
roman808f3f62023-11-23 16:01:04 +0100671nc_sshcb_auth_kbdint(struct nc_session *session, struct nc_auth_client *client, uint16_t auth_timeout, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +0100672{
bhart3bc2f582018-06-05 12:40:32 -0500673 int auth_ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +0100674
romanf578cd52023-10-19 09:47:40 +0200675 if (server_opts.interactive_auth_clb) {
676 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 +0200677 } else {
678#ifdef HAVE_LIBPAM
romanc6518422023-11-30 16:39:00 +0100679 /* authenticate using PAM */
680 if (!nc_pam_auth(session, client, auth_timeout, msg)) {
681 auth_ret = 0;
682 }
683#elif defined (HAVE_SHADOW)
684 /* authenticate using locally configured users */
685 if (!nc_server_ssh_system_auth(session, client, auth_timeout, msg)) {
Michal Vasko0d81c572022-09-26 10:39:31 +0200686 auth_ret = 0;
687 }
688#else
romanc6518422023-11-30 16:39:00 +0100689 (void) auth_timeout;
690 ERR(NULL, "Keyboard-interactive method not supported.");
Michal Vasko0d81c572022-09-26 10:39:31 +0200691#endif
bhart1bb7cdb2018-07-02 15:03:30 -0500692 }
693
694 /* Authenticate message based on outcome */
romanf578cd52023-10-19 09:47:40 +0200695 if (auth_ret) {
bhart1bb7cdb2018-07-02 15:03:30 -0500696 ++session->opts.server.ssh_auth_attempts;
romanc6518422023-11-30 16:39:00 +0100697 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", client->username,
Michal Vasko05532772021-06-03 12:12:38 +0200698 session->opts.server.ssh_auth_attempts);
bhart1bb7cdb2018-07-02 15:03:30 -0500699 ssh_message_reply_default(msg);
Michal Vasko086311b2016-01-08 09:53:11 +0100700 }
romanf578cd52023-10-19 09:47:40 +0200701
702 return auth_ret;
703}
704
roman808f3f62023-11-23 16:01:04 +0100705API void
706nc_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),
707 void *user_data, void (*free_user_data)(void *user_data))
708{
romanc6518422023-11-30 16:39:00 +0100709 /* CONFIG LOCK */
710 pthread_rwlock_wrlock(&server_opts.config_lock);
711
roman808f3f62023-11-23 16:01:04 +0100712 server_opts.interactive_auth_clb = interactive_auth_clb;
713 server_opts.interactive_auth_data = user_data;
714 server_opts.interactive_auth_data_free = free_user_data;
romanc6518422023-11-30 16:39:00 +0100715
716 /* CONFIG UNLOCK */
717 pthread_rwlock_unlock(&server_opts.config_lock);
roman808f3f62023-11-23 16:01:04 +0100718}
719
720#ifdef HAVE_LIBPAM
721
722API int
723nc_server_ssh_set_pam_conf_filename(const char *filename)
724{
romanc6518422023-11-30 16:39:00 +0100725 int ret = 0;
726
roman808f3f62023-11-23 16:01:04 +0100727 NC_CHECK_ARG_RET(NULL, filename, 1);
728
romanc6518422023-11-30 16:39:00 +0100729 /* CONFIG LOCK */
730 pthread_rwlock_wrlock(&server_opts.config_lock);
731
roman808f3f62023-11-23 16:01:04 +0100732 free(server_opts.pam_config_name);
733 server_opts.pam_config_name = strdup(filename);
romanc6518422023-11-30 16:39:00 +0100734 if (!server_opts.pam_config_name) {
735 ERRMEM;
736 ret = 1;
737 }
738
739 /* CONFIG UNLOCK */
740 pthread_rwlock_unlock(&server_opts.config_lock);
741 return ret;
roman808f3f62023-11-23 16:01:04 +0100742}
743
744#else
745
746API int
747nc_server_ssh_set_pam_conf_filename(const char *filename)
748{
749 (void) filename;
romanea82c742023-12-11 10:23:43 +0100750 ERR(NULL, "LibPAM not found.");
roman808f3f62023-11-23 16:01:04 +0100751 return 1;
752}
753
754#endif /* HAVE_LIBPAM */
755
romanf578cd52023-10-19 09:47:40 +0200756/*
757 * Get the public key type from binary data stored in buffer.
758 * The data is in the form of: 4 bytes = data length, then data of data length
759 * and the data is in network byte order. The key has to be in the SSH2 format.
760 */
761static const char *
762nc_server_ssh_get_pubkey_type(const char *buffer, uint32_t *len)
763{
764 uint32_t type_len;
765
766 /* copy the 4 bytes */
767 memcpy(&type_len, buffer, sizeof type_len);
768 /* type_len now stores the length of the key type */
769 type_len = ntohl(type_len);
770 *len = type_len;
771
772 /* move 4 bytes in the buffer, this is where the type should be */
773 buffer += sizeof type_len;
774 return buffer;
775}
776
777/**
778 * @brief Create ssh key from base64 pubkey data.
779 *
780 * @param[in] base64 base64 encoded public key.
781 * @param[out] key created ssh key.
782 * @return 0 on success, 1 otherwise.
783 */
784static int
785nc_server_ssh_create_ssh_pubkey(const char *base64, ssh_key *key)
786{
787 int ret = 0;
788 char *bin = NULL;
789 const char *pub_type = NULL;
790 uint32_t pub_type_len = 0;
791
roman6dfdc0d2023-11-09 13:25:27 +0100792 NC_CHECK_ARG_RET(NULL, base64, key, 1);
romanf578cd52023-10-19 09:47:40 +0200793
794 *key = NULL;
795
796 /* convert base64 to binary */
797 if (nc_base64_to_bin(base64, &bin) == -1) {
798 ERR(NULL, "Unable to decode base64.");
799 ret = 1;
800 goto cleanup;
801 }
802
803 /* get the key type and try to import it if possible */
804 pub_type = nc_server_ssh_get_pubkey_type(bin, &pub_type_len);
805 if (!pub_type) {
806 ret = 1;
807 goto cleanup;
808 } else if (!strncmp(pub_type, "ssh-dss", pub_type_len)) {
809 ERR(NULL, "DSA keys are not supported.");
810 ret = 1;
811 goto cleanup;
812 } else if (!strncmp(pub_type, "ssh-rsa", pub_type_len)) {
813 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_RSA, key);
814 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp256", pub_type_len)) {
815 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P256, key);
816 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp384", pub_type_len)) {
817 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P384, key);
818 } else if (!strncmp(pub_type, "ecdsa-sha2-nistp521", pub_type_len)) {
819 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ECDSA_P521, key);
820 } else if (!strncmp(pub_type, "ssh-ed25519", pub_type_len)) {
821 ret = ssh_pki_import_pubkey_base64(base64, SSH_KEYTYPE_ED25519, key);
822 } else {
823 ERR(NULL, "Public key type not recognised.");
824 ret = 1;
825 goto cleanup;
826 }
827
828cleanup:
829 if (ret != SSH_OK) {
830 ERR(NULL, "Error importing public key.");
831 }
832 free(bin);
833 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +0100834}
835
Michal Vaskof3c41e32022-09-09 11:22:21 +0200836/**
837 * @brief Compare SSH key with configured authorized keys and return the username of the matching one, if any.
838 *
839 * @param[in] key Presented SSH key to compare.
840 * @return Authorized key username, NULL if no match was found.
841 */
romanf578cd52023-10-19 09:47:40 +0200842static int
843auth_pubkey_compare_key(ssh_key key, struct nc_auth_client *auth_client)
Michal Vasko086311b2016-01-08 09:53:11 +0100844{
romanf578cd52023-10-19 09:47:40 +0200845 uint16_t i, pubkey_count;
Michal Vasko3e9d1682017-02-24 09:50:15 +0100846 int ret = 0;
romanf578cd52023-10-19 09:47:40 +0200847 ssh_key new_key = NULL;
848 struct nc_public_key *pubkeys;
Michal Vasko086311b2016-01-08 09:53:11 +0100849
romanf578cd52023-10-19 09:47:40 +0200850 /* get the correct public key storage */
851 if (auth_client->store == NC_STORE_LOCAL) {
852 pubkeys = auth_client->pubkeys;
853 pubkey_count = auth_client->pubkey_count;
854 } else {
855 ret = nc_server_ssh_ts_ref_get_keys(auth_client->ts_ref, &pubkeys, &pubkey_count);
856 if (ret) {
857 ERR(NULL, "Error getting \"%s\"'s public keys from the truststore.", auth_client->username);
858 return ret;
Michal Vasko17dfda92016-12-01 14:06:16 +0100859 }
romanf578cd52023-10-19 09:47:40 +0200860 }
Michal Vasko17dfda92016-12-01 14:06:16 +0100861
romanf578cd52023-10-19 09:47:40 +0200862 /* try to compare all of the client's keys with the key received in the SSH message */
863 for (i = 0; i < pubkey_count; i++) {
864 /* create the SSH key from the data */
865 if (nc_server_ssh_create_ssh_pubkey(pubkeys[i].data, &new_key)) {
866 ssh_key_free(new_key);
Michal Vasko086311b2016-01-08 09:53:11 +0100867 continue;
868 }
869
romanf578cd52023-10-19 09:47:40 +0200870 /* compare the keys */
871 ret = ssh_key_cmp(key, new_key, SSH_KEY_CMP_PUBLIC);
872 if (!ret) {
Michal Vasko086311b2016-01-08 09:53:11 +0100873 break;
romanf578cd52023-10-19 09:47:40 +0200874 } else {
875 WRN(NULL, "User's \"%s\" public key doesn't match, trying another.", auth_client->username);
876 ssh_key_free(new_key);
Michal Vasko086311b2016-01-08 09:53:11 +0100877 }
Michal Vasko086311b2016-01-08 09:53:11 +0100878 }
879
romanf578cd52023-10-19 09:47:40 +0200880 if (i == pubkey_count) {
881 ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +0100882 }
883
romanf578cd52023-10-19 09:47:40 +0200884 if (!ret) {
885 /* only free a key if everything was ok, it would have already been freed otherwise */
886 ssh_key_free(new_key);
887 }
Michal Vaskoa05c7b12017-01-30 14:33:08 +0100888
romanf578cd52023-10-19 09:47:40 +0200889 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +0100890}
891
892static void
romanf578cd52023-10-19 09:47:40 +0200893nc_sshcb_auth_none(struct nc_session *session, struct nc_auth_client *auth_client, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +0100894{
roman808f3f62023-11-23 16:01:04 +0100895 if (auth_client->none_enabled && !auth_client->password && !auth_client->pubkey_count && !auth_client->kb_int_enabled) {
romanf578cd52023-10-19 09:47:40 +0200896 /* only authenticate the client if he supports none and no other method */
897 session->flags |= NC_SESSION_SSH_AUTHENTICATED;
898 VRB(session, "User \"%s\" authenticated.", session->username);
899 ssh_message_auth_reply_success(msg, 0);
900 }
901
902 ssh_message_reply_default(msg);
903}
904
905static int
906nc_sshcb_auth_pubkey(struct nc_session *session, struct nc_auth_client *auth_client, ssh_message msg)
907{
908 int signature_state, ret = 0;
Michal Vasko086311b2016-01-08 09:53:11 +0100909
roman9130fc12023-11-03 13:56:23 +0100910 if (auth_pubkey_compare_key(ssh_message_auth_pubkey(msg), auth_client)) {
911 VRB(session, "User \"%s\" tried to use an unknown (unauthorized) public key.", session->username);
912 ret = 1;
913 goto fail;
Michal Vaskobd13a932016-09-14 09:00:35 +0200914 }
Michal Vaskobd13a932016-09-14 09:00:35 +0200915
Michal Vasko086311b2016-01-08 09:53:11 +0100916 signature_state = ssh_message_auth_publickey_state(msg);
romanf578cd52023-10-19 09:47:40 +0200917 if (signature_state == SSH_PUBLICKEY_STATE_NONE) {
Michal Vaskobd13a932016-09-14 09:00:35 +0200918 /* accepting only the use of a public key */
919 ssh_message_auth_reply_pk_ok_simple(msg);
romanf578cd52023-10-19 09:47:40 +0200920 ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +0100921 }
922
romanf578cd52023-10-19 09:47:40 +0200923 return ret;
Michal Vaskobd13a932016-09-14 09:00:35 +0200924
925fail:
Michal Vasko2e6defd2016-10-07 15:48:15 +0200926 ++session->opts.server.ssh_auth_attempts;
Michal Vasko05532772021-06-03 12:12:38 +0200927 VRB(session, "Failed user \"%s\" authentication attempt (#%d).", session->username,
928 session->opts.server.ssh_auth_attempts);
Michal Vasko086311b2016-01-08 09:53:11 +0100929 ssh_message_reply_default(msg);
romanf578cd52023-10-19 09:47:40 +0200930
931 return ret;
Michal Vasko086311b2016-01-08 09:53:11 +0100932}
933
934static int
Michal Vasko96164bf2016-01-21 15:41:58 +0100935nc_sshcb_channel_open(struct nc_session *session, ssh_message msg)
Michal Vasko086311b2016-01-08 09:53:11 +0100936{
Michal Vasko96164bf2016-01-21 15:41:58 +0100937 ssh_channel chan;
938
939 /* first channel request */
940 if (!session->ti.libssh.channel) {
941 if (session->status != NC_STATUS_STARTING) {
Michal Vasko9e036d52016-01-08 10:49:26 +0100942 ERRINT;
Michal Vasko086311b2016-01-08 09:53:11 +0100943 return -1;
944 }
Michal Vasko96164bf2016-01-21 15:41:58 +0100945 chan = ssh_message_channel_request_open_reply_accept(msg);
946 if (!chan) {
Michal Vasko05532772021-06-03 12:12:38 +0200947 ERR(session, "Failed to create a new SSH channel.");
Michal Vasko96164bf2016-01-21 15:41:58 +0100948 return -1;
949 }
950 session->ti.libssh.channel = chan;
Michal Vasko086311b2016-01-08 09:53:11 +0100951
Michal Vaskob83a3fa2021-05-26 09:53:42 +0200952 /* additional channel request */
Michal Vasko96164bf2016-01-21 15:41:58 +0100953 } else {
954 chan = ssh_message_channel_request_open_reply_accept(msg);
955 if (!chan) {
Michal Vasko05532772021-06-03 12:12:38 +0200956 ERR(session, "Session %u: failed to create a new SSH channel.", session->id);
Michal Vasko96164bf2016-01-21 15:41:58 +0100957 return -1;
958 }
959 /* channel was created and libssh stored it internally in the ssh_session structure, good enough */
Michal Vasko086311b2016-01-08 09:53:11 +0100960 }
961
Michal Vasko086311b2016-01-08 09:53:11 +0100962 return 0;
963}
964
965static int
966nc_sshcb_channel_subsystem(struct nc_session *session, ssh_channel channel, const char *subsystem)
967{
Michal Vasko96164bf2016-01-21 15:41:58 +0100968 struct nc_session *new_session;
Michal Vasko086311b2016-01-08 09:53:11 +0100969
Michal Vasko96164bf2016-01-21 15:41:58 +0100970 if (strcmp(subsystem, "netconf")) {
Michal Vasko05532772021-06-03 12:12:38 +0200971 WRN(session, "Received an unknown subsystem \"%s\" request.", subsystem);
Michal Vasko086311b2016-01-08 09:53:11 +0100972 return -1;
973 }
974
Michal Vasko96164bf2016-01-21 15:41:58 +0100975 if (session->ti.libssh.channel == channel) {
976 /* first channel requested */
977 if (session->ti.libssh.next || (session->status != NC_STATUS_STARTING)) {
978 ERRINT;
979 return -1;
Michal Vasko086311b2016-01-08 09:53:11 +0100980 }
Michal Vasko96164bf2016-01-21 15:41:58 +0100981 if (session->flags & NC_SESSION_SSH_SUBSYS_NETCONF) {
Michal Vasko05532772021-06-03 12:12:38 +0200982 ERR(session, "Subsystem \"netconf\" requested for the second time.");
Michal Vasko96164bf2016-01-21 15:41:58 +0100983 return -1;
984 }
985
986 session->flags |= NC_SESSION_SSH_SUBSYS_NETCONF;
Michal Vasko086311b2016-01-08 09:53:11 +0100987 } else {
Michal Vasko96164bf2016-01-21 15:41:58 +0100988 /* additional channel subsystem request, new session is ready as far as SSH is concerned */
Michal Vasko131120a2018-05-29 15:44:02 +0200989 new_session = nc_new_session(NC_SERVER, 1);
roman3a95bb22023-10-26 11:07:17 +0200990 NC_CHECK_ERRMEM_RET(!new_session, -1);
Michal Vasko96164bf2016-01-21 15:41:58 +0100991
992 /* insert the new session */
993 if (!session->ti.libssh.next) {
994 new_session->ti.libssh.next = session;
995 } else {
996 new_session->ti.libssh.next = session->ti.libssh.next;
997 }
998 session->ti.libssh.next = new_session;
999
1000 new_session->status = NC_STATUS_STARTING;
Michal Vasko96164bf2016-01-21 15:41:58 +01001001 new_session->ti_type = NC_TI_LIBSSH;
Michal Vasko131120a2018-05-29 15:44:02 +02001002 new_session->io_lock = session->io_lock;
Michal Vasko96164bf2016-01-21 15:41:58 +01001003 new_session->ti.libssh.channel = channel;
1004 new_session->ti.libssh.session = session->ti.libssh.session;
Michal Vasko93224072021-11-09 12:14:28 +01001005 new_session->username = strdup(session->username);
1006 new_session->host = strdup(session->host);
Michal Vasko96164bf2016-01-21 15:41:58 +01001007 new_session->port = session->port;
Michal Vasko93224072021-11-09 12:14:28 +01001008 new_session->ctx = (struct ly_ctx *)session->ctx;
Michal Vasko83d15322018-09-27 09:44:02 +02001009 new_session->flags = NC_SESSION_SSH_AUTHENTICATED | NC_SESSION_SSH_SUBSYS_NETCONF | NC_SESSION_SHAREDCTX;
Michal Vasko086311b2016-01-08 09:53:11 +01001010 }
1011
1012 return 0;
1013}
1014
Michal Vasko96164bf2016-01-21 15:41:58 +01001015int
romanf578cd52023-10-19 09:47:40 +02001016nc_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 +01001017{
1018 const char *str_type, *str_subtype = NULL, *username;
romanf578cd52023-10-19 09:47:40 +02001019 int subtype, type, libssh_auth_methods = 0, ret = 0;
1020 uint16_t i;
1021 struct nc_auth_client *auth_client = NULL;
roman78df0fa2023-11-02 10:33:57 +01001022 struct nc_endpt *referenced_endpt;
Michal Vasko086311b2016-01-08 09:53:11 +01001023
1024 type = ssh_message_type(msg);
1025 subtype = ssh_message_subtype(msg);
1026
1027 switch (type) {
1028 case SSH_REQUEST_AUTH:
1029 str_type = "request-auth";
1030 switch (subtype) {
1031 case SSH_AUTH_METHOD_NONE:
1032 str_subtype = "none";
1033 break;
1034 case SSH_AUTH_METHOD_PASSWORD:
1035 str_subtype = "password";
1036 break;
1037 case SSH_AUTH_METHOD_PUBLICKEY:
1038 str_subtype = "publickey";
1039 break;
1040 case SSH_AUTH_METHOD_HOSTBASED:
1041 str_subtype = "hostbased";
1042 break;
1043 case SSH_AUTH_METHOD_INTERACTIVE:
1044 str_subtype = "interactive";
1045 break;
1046 case SSH_AUTH_METHOD_GSSAPI_MIC:
1047 str_subtype = "gssapi-mic";
1048 break;
1049 }
1050 break;
1051
1052 case SSH_REQUEST_CHANNEL_OPEN:
1053 str_type = "request-channel-open";
1054 switch (subtype) {
1055 case SSH_CHANNEL_SESSION:
1056 str_subtype = "session";
1057 break;
1058 case SSH_CHANNEL_DIRECT_TCPIP:
1059 str_subtype = "direct-tcpip";
1060 break;
1061 case SSH_CHANNEL_FORWARDED_TCPIP:
1062 str_subtype = "forwarded-tcpip";
1063 break;
1064 case (int)SSH_CHANNEL_X11:
1065 str_subtype = "channel-x11";
1066 break;
1067 case SSH_CHANNEL_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001068 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001069 default:
1070 str_subtype = "unknown";
1071 break;
1072 }
1073 break;
1074
1075 case SSH_REQUEST_CHANNEL:
1076 str_type = "request-channel";
1077 switch (subtype) {
1078 case SSH_CHANNEL_REQUEST_PTY:
1079 str_subtype = "pty";
1080 break;
1081 case SSH_CHANNEL_REQUEST_EXEC:
1082 str_subtype = "exec";
1083 break;
1084 case SSH_CHANNEL_REQUEST_SHELL:
1085 str_subtype = "shell";
1086 break;
1087 case SSH_CHANNEL_REQUEST_ENV:
1088 str_subtype = "env";
1089 break;
1090 case SSH_CHANNEL_REQUEST_SUBSYSTEM:
1091 str_subtype = "subsystem";
1092 break;
1093 case SSH_CHANNEL_REQUEST_WINDOW_CHANGE:
1094 str_subtype = "window-change";
1095 break;
1096 case SSH_CHANNEL_REQUEST_X11:
1097 str_subtype = "x11";
1098 break;
1099 case SSH_CHANNEL_REQUEST_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001100 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001101 default:
1102 str_subtype = "unknown";
1103 break;
1104 }
1105 break;
1106
1107 case SSH_REQUEST_SERVICE:
1108 str_type = "request-service";
1109 str_subtype = ssh_message_service_service(msg);
1110 break;
1111
1112 case SSH_REQUEST_GLOBAL:
1113 str_type = "request-global";
1114 switch (subtype) {
1115 case SSH_GLOBAL_REQUEST_TCPIP_FORWARD:
1116 str_subtype = "tcpip-forward";
1117 break;
1118 case SSH_GLOBAL_REQUEST_CANCEL_TCPIP_FORWARD:
1119 str_subtype = "cancel-tcpip-forward";
1120 break;
1121 case SSH_GLOBAL_REQUEST_UNKNOWN:
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001122 /* fallthrough */
Michal Vasko086311b2016-01-08 09:53:11 +01001123 default:
1124 str_subtype = "unknown";
1125 break;
1126 }
1127 break;
1128
1129 default:
1130 str_type = "unknown";
1131 str_subtype = "unknown";
1132 break;
1133 }
1134
Michal Vasko05532772021-06-03 12:12:38 +02001135 VRB(session, "Received an SSH message \"%s\" of subtype \"%s\".", str_type, str_subtype);
Michal Vasko5e0edd82020-07-29 15:26:13 +02001136 if (!session || (session->status == NC_STATUS_CLOSING) || (session->status == NC_STATUS_INVALID)) {
Michal Vaskoce319162016-02-03 15:33:08 +01001137 /* "valid" situation if, for example, receiving some auth or channel request timeouted,
1138 * but we got it now, during session free */
Michal Vasko05532772021-06-03 12:12:38 +02001139 VRB(session, "SSH message arrived on a %s session, the request will be denied.",
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001140 (session && session->status == NC_STATUS_CLOSING ? "closing" : "invalid"));
Michal Vaskoce319162016-02-03 15:33:08 +01001141 ssh_message_reply_default(msg);
1142 return 0;
1143 }
Michal Vasko086311b2016-01-08 09:53:11 +01001144
1145 /*
1146 * process known messages
1147 */
1148 if (type == SSH_REQUEST_AUTH) {
1149 if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
Michal Vasko05532772021-06-03 12:12:38 +02001150 ERR(session, "User \"%s\" authenticated, but requested another authentication.", session->username);
Michal Vasko086311b2016-01-08 09:53:11 +01001151 ssh_message_reply_default(msg);
1152 return 0;
romanf578cd52023-10-19 09:47:40 +02001153 } else if (!state || !opts) {
1154 /* these two parameters should always be set during an authentication,
1155 * however do a check just in case something goes really wrong, since they
1156 * are not needed for other types of messages
1157 */
1158 ERRINT;
1159 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001160 }
1161
Michal Vasko086311b2016-01-08 09:53:11 +01001162 /* save the username, do not let the client change it */
1163 username = ssh_message_auth_user(msg);
romanf578cd52023-10-19 09:47:40 +02001164 assert(username);
1165
1166 for (i = 0; i < opts->client_count; i++) {
1167 if (!strcmp(opts->auth_clients[i].username, username)) {
1168 auth_client = &opts->auth_clients[i];
1169 break;
1170 }
1171 }
1172
1173 if (!auth_client) {
roman78df0fa2023-11-02 10:33:57 +01001174 if (opts->referenced_endpt_name) {
1175 /* client not known by the endpt, but it references another one so try it */
1176 if (nc_server_get_referenced_endpt(opts->referenced_endpt_name, &referenced_endpt)) {
1177 ERRINT;
1178 return 1;
1179 }
1180
1181 return nc_session_ssh_msg(session, referenced_endpt->opts.ssh, msg, state);
Michal Vasko086311b2016-01-08 09:53:11 +01001182 }
1183
romanf578cd52023-10-19 09:47:40 +02001184 ERR(NULL, "User \"%s\" not known by the server.", username);
1185 ssh_message_reply_default(msg);
1186 return 0;
1187 }
1188
1189 if (!session->username) {
Michal Vasko93224072021-11-09 12:14:28 +01001190 session->username = strdup(username);
romanf578cd52023-10-19 09:47:40 +02001191
1192 /* configure and count accepted auth methods */
1193 if (auth_client->store == NC_STORE_LOCAL) {
1194 if (auth_client->pubkey_count) {
1195 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1196 }
1197 } else if (auth_client->ts_ref) {
1198 libssh_auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
1199 }
1200 if (auth_client->password) {
1201 state->auth_method_count++;
1202 libssh_auth_methods |= SSH_AUTH_METHOD_PASSWORD;
1203 }
roman808f3f62023-11-23 16:01:04 +01001204 if (auth_client->kb_int_enabled) {
romanf578cd52023-10-19 09:47:40 +02001205 state->auth_method_count++;
1206 libssh_auth_methods |= SSH_AUTH_METHOD_INTERACTIVE;
1207 }
roman808f3f62023-11-23 16:01:04 +01001208 if (auth_client->none_enabled) {
romanf578cd52023-10-19 09:47:40 +02001209 libssh_auth_methods |= SSH_AUTH_METHOD_NONE;
1210 }
1211
1212 if (libssh_auth_methods & SSH_AUTH_METHOD_PUBLICKEY) {
1213 state->auth_method_count++;
1214 }
1215
1216 ssh_set_auth_methods(session->ti.libssh.session, libssh_auth_methods);
1217 } else {
Michal Vasko086311b2016-01-08 09:53:11 +01001218 if (strcmp(username, session->username)) {
romanf578cd52023-10-19 09:47:40 +02001219 /* changing username not allowed */
Michal Vasko05532772021-06-03 12:12:38 +02001220 ERR(session, "User \"%s\" changed its username to \"%s\".", session->username, username);
Michal Vasko086311b2016-01-08 09:53:11 +01001221 session->status = NC_STATUS_INVALID;
Michal Vasko428087d2016-01-14 16:04:28 +01001222 session->term_reason = NC_SESSION_TERM_OTHER;
Michal Vasko086311b2016-01-08 09:53:11 +01001223 return 1;
1224 }
1225 }
1226
romanf578cd52023-10-19 09:47:40 +02001227 /* try authenticating, the user must authenticate via all of his configured auth methods */
Michal Vasko086311b2016-01-08 09:53:11 +01001228 if (subtype == SSH_AUTH_METHOD_NONE) {
romanf578cd52023-10-19 09:47:40 +02001229 nc_sshcb_auth_none(session, auth_client, msg);
1230 ret = 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001231 } else if (subtype == SSH_AUTH_METHOD_PASSWORD) {
romanf578cd52023-10-19 09:47:40 +02001232 ret = nc_sshcb_auth_password(session, auth_client, msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001233 } else if (subtype == SSH_AUTH_METHOD_PUBLICKEY) {
romanf578cd52023-10-19 09:47:40 +02001234 ret = nc_sshcb_auth_pubkey(session, auth_client, msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001235 } else if (subtype == SSH_AUTH_METHOD_INTERACTIVE) {
roman808f3f62023-11-23 16:01:04 +01001236 ret = nc_sshcb_auth_kbdint(session, auth_client, opts->auth_timeout, msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001237 }
romanf578cd52023-10-19 09:47:40 +02001238
1239 if (!ret) {
1240 state->auth_success_count++;
1241 }
1242
1243 if (!ret && (state->auth_success_count < state->auth_method_count)) {
1244 /* success, but he needs to do another method */
1245 VRB(session, "User \"%s\" partially authenticated, but still needs to authenticate via the rest of his configured methods.", username);
1246 ssh_message_auth_reply_success(msg, 1);
1247 } else if (!ret && (state->auth_success_count == state->auth_method_count)) {
1248 /* authenticated */
1249 ssh_message_auth_reply_success(msg, 0);
1250 session->flags |= NC_SESSION_SSH_AUTHENTICATED;
1251 VRB(session, "User \"%s\" authenticated.", username);
1252 }
1253
1254 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001255 } else if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
Michal Vasko0df67562016-01-21 15:50:11 +01001256 if ((type == SSH_REQUEST_CHANNEL_OPEN) && ((enum ssh_channel_type_e)subtype == SSH_CHANNEL_SESSION)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001257 if (nc_sshcb_channel_open(session, msg)) {
Michal Vasko086311b2016-01-08 09:53:11 +01001258 ssh_message_reply_default(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001259 }
Michal Vasko086311b2016-01-08 09:53:11 +01001260 return 0;
Michal Vasko96164bf2016-01-21 15:41:58 +01001261
Michal Vasko0df67562016-01-21 15:50:11 +01001262 } else if ((type == SSH_REQUEST_CHANNEL) && ((enum ssh_channel_requests_e)subtype == SSH_CHANNEL_REQUEST_SUBSYSTEM)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001263 if (nc_sshcb_channel_subsystem(session, ssh_message_channel_request_channel(msg),
1264 ssh_message_channel_request_subsystem(msg))) {
Michal Vasko086311b2016-01-08 09:53:11 +01001265 ssh_message_reply_default(msg);
Michal Vasko96164bf2016-01-21 15:41:58 +01001266 } else {
1267 ssh_message_channel_request_reply_success(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001268 }
1269 return 0;
1270 }
1271 }
1272
1273 /* we did not process it */
1274 return 1;
1275}
1276
Michal Vasko1a38c862016-01-15 15:50:07 +01001277/* ret 1 on success, 0 on timeout, -1 on error */
Michal Vasko086311b2016-01-08 09:53:11 +01001278static int
romanf578cd52023-10-19 09:47:40 +02001279nc_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 +01001280{
roman6ece9c52022-06-22 09:29:17 +02001281 struct timespec ts_timeout;
romanf578cd52023-10-19 09:47:40 +02001282 ssh_message msg;
Michal Vasko086311b2016-01-08 09:53:11 +01001283
romanf578cd52023-10-19 09:47:40 +02001284 if (timeout) {
1285 nc_timeouttime_get(&ts_timeout, timeout * 1000);
Michal Vasko36c7be82017-02-22 13:37:59 +01001286 }
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001287 while (1) {
1288 if (!nc_session_is_connected(session)) {
romanf578cd52023-10-19 09:47:40 +02001289 ERR(session, "Communication SSH socket unexpectedly closed.");
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001290 return -1;
1291 }
1292
romanf578cd52023-10-19 09:47:40 +02001293 msg = ssh_message_get(session->ti.libssh.session);
1294 if (msg) {
1295 if (nc_session_ssh_msg(session, opts, msg, NULL)) {
1296 ssh_message_reply_default(msg);
1297 }
1298 ssh_message_free(msg);
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001299 }
1300
romanf578cd52023-10-19 09:47:40 +02001301 if (session->ti.libssh.channel && session->flags & NC_SESSION_SSH_SUBSYS_NETCONF) {
Michal Vasko1a38c862016-01-15 15:50:07 +01001302 return 1;
Michal Vasko086311b2016-01-08 09:53:11 +01001303 }
1304
Michal Vasko086311b2016-01-08 09:53:11 +01001305 usleep(NC_TIMEOUT_STEP);
romanea0edaa2023-10-26 12:16:25 +02001306 if (opts->auth_timeout && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
roman6ece9c52022-06-22 09:29:17 +02001307 /* timeout */
1308 ERR(session, "Failed to start \"netconf\" SSH subsystem for too long, disconnecting.");
1309 break;
Michal Vasko36c7be82017-02-22 13:37:59 +01001310 }
Michal Vasko7f1c78b2016-01-19 09:52:14 +01001311 }
Michal Vasko086311b2016-01-08 09:53:11 +01001312
Michal Vasko1a38c862016-01-15 15:50:07 +01001313 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001314}
1315
Michal Vaskof3c41e32022-09-09 11:22:21 +02001316/**
1317 * @brief Set hostkeys to be used for an SSH bind.
1318 *
1319 * @param[in] sbind SSH bind to use.
1320 * @param[in] hostkeys Array of hostkeys.
1321 * @param[in] hostkey_count Count of @p hostkeys.
1322 * @return 0 on success.
1323 * @return -1 on error.
1324 */
Michal Vasko4c1fb492017-01-30 14:31:07 +01001325static int
romanf578cd52023-10-19 09:47:40 +02001326nc_ssh_bind_add_hostkeys(ssh_bind sbind, struct nc_server_ssh_opts *opts, uint16_t hostkey_count)
Michal Vasko4c1fb492017-01-30 14:31:07 +01001327{
romanf578cd52023-10-19 09:47:40 +02001328 uint16_t i;
roman6dfdc0d2023-11-09 13:25:27 +01001329 char *privkey_path;
Michal Vaskoddce1212019-05-24 09:58:49 +02001330 int ret;
romanf578cd52023-10-19 09:47:40 +02001331 struct nc_asymmetric_key *key = NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +01001332
1333 for (i = 0; i < hostkey_count; ++i) {
roman6dfdc0d2023-11-09 13:25:27 +01001334 privkey_path = NULL;
Michal Vasko4c1fb492017-01-30 14:31:07 +01001335
romanf578cd52023-10-19 09:47:40 +02001336 /* get the asymmetric key */
1337 if (opts->hostkeys[i].store == NC_STORE_LOCAL) {
1338 /* stored locally */
1339 key = &opts->hostkeys[i].key;
1340 } else {
1341 /* keystore reference, need to get it */
1342 if (nc_server_ssh_ks_ref_get_key(opts->hostkeys[i].ks_ref, &key)) {
Michal Vasko4c1fb492017-01-30 14:31:07 +01001343 return -1;
1344 }
1345 }
1346
romanf578cd52023-10-19 09:47:40 +02001347 privkey_path = base64der_privkey_to_tmp_file(key->privkey_data, nc_privkey_format_to_str(key->privkey_type));
1348 if (!privkey_path) {
1349 ERR(NULL, "Temporarily storing a host key into a file failed (%s).", strerror(errno));
1350 return -1;
1351 }
1352
Michal Vasko4c1fb492017-01-30 14:31:07 +01001353 ret = ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY, privkey_path);
1354
1355 /* cleanup */
roman6dfdc0d2023-11-09 13:25:27 +01001356 if (unlink(privkey_path)) {
Michal Vasko05532772021-06-03 12:12:38 +02001357 WRN(NULL, "Removing a temporary host key file \"%s\" failed (%s).", privkey_path, strerror(errno));
Michal Vasko4c1fb492017-01-30 14:31:07 +01001358 }
Michal Vasko4c1fb492017-01-30 14:31:07 +01001359
1360 if (ret != SSH_OK) {
romanf578cd52023-10-19 09:47:40 +02001361 ERR(NULL, "Failed to set hostkey \"%s\" (%s).", opts->hostkeys[i].name, privkey_path);
Michal Vasko80075de2017-07-10 11:38:52 +02001362 }
1363 free(privkey_path);
1364
1365 if (ret != SSH_OK) {
Michal Vasko4c1fb492017-01-30 14:31:07 +01001366 return -1;
1367 }
1368 }
1369
1370 return 0;
1371}
1372
Michal Vasko09d700f2022-09-08 10:21:40 +02001373static int
romanf578cd52023-10-19 09:47:40 +02001374nc_accept_ssh_session_auth(struct nc_session *session, struct nc_server_ssh_opts *opts)
Michal Vasko3031aae2016-01-27 16:07:18 +01001375{
roman6ece9c52022-06-22 09:29:17 +02001376 struct timespec ts_timeout;
roman41a11e42022-06-22 09:27:08 +02001377 ssh_message msg;
romanf578cd52023-10-19 09:47:40 +02001378 struct nc_auth_state state = {0};
Michal Vasko086311b2016-01-08 09:53:11 +01001379
Michal Vasko086311b2016-01-08 09:53:11 +01001380 /* authenticate */
Michal Vasko36c7be82017-02-22 13:37:59 +01001381 if (opts->auth_timeout) {
Michal Vaskod8a74192023-02-06 15:51:50 +01001382 nc_timeouttime_get(&ts_timeout, opts->auth_timeout * 1000);
Michal Vasko36c7be82017-02-22 13:37:59 +01001383 }
1384 while (1) {
Michal Vasko2a7d4732016-01-15 09:24:46 +01001385 if (!nc_session_is_connected(session)) {
Michal Vasko05532772021-06-03 12:12:38 +02001386 ERR(session, "Communication SSH socket unexpectedly closed.");
Michal Vasko2a7d4732016-01-15 09:24:46 +01001387 return -1;
1388 }
1389
roman41a11e42022-06-22 09:27:08 +02001390 msg = ssh_message_get(session->ti.libssh.session);
1391 if (msg) {
romanf578cd52023-10-19 09:47:40 +02001392 if (nc_session_ssh_msg(session, opts, msg, &state)) {
roman41a11e42022-06-22 09:27:08 +02001393 ssh_message_reply_default(msg);
1394 }
1395 ssh_message_free(msg);
Michal Vasko086311b2016-01-08 09:53:11 +01001396 }
1397
Michal Vasko36c7be82017-02-22 13:37:59 +01001398 if (session->flags & NC_SESSION_SSH_AUTHENTICATED) {
1399 break;
1400 }
1401
Michal Vasko145ae672017-02-07 10:57:27 +01001402 if (session->opts.server.ssh_auth_attempts >= opts->auth_attempts) {
Michal Vasko05532772021-06-03 12:12:38 +02001403 ERR(session, "Too many failed authentication attempts of user \"%s\".", session->username);
Michal Vasko145ae672017-02-07 10:57:27 +01001404 return -1;
1405 }
1406
Michal Vasko086311b2016-01-08 09:53:11 +01001407 usleep(NC_TIMEOUT_STEP);
romanea0edaa2023-10-26 12:16:25 +02001408 if (opts->auth_timeout && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
roman6ece9c52022-06-22 09:29:17 +02001409 /* timeout */
1410 break;
Michal Vasko36c7be82017-02-22 13:37:59 +01001411 }
1412 }
Michal Vasko086311b2016-01-08 09:53:11 +01001413
1414 if (!(session->flags & NC_SESSION_SSH_AUTHENTICATED)) {
1415 /* timeout */
Michal Vaskoc13da702017-02-07 10:57:57 +01001416 if (session->username) {
Michal Vasko05532772021-06-03 12:12:38 +02001417 ERR(session, "User \"%s\" failed to authenticate for too long, disconnecting.", session->username);
Michal Vaskoc13da702017-02-07 10:57:57 +01001418 } else {
Michal Vasko05532772021-06-03 12:12:38 +02001419 ERR(session, "User failed to authenticate for too long, disconnecting.");
Michal Vaskoc13da702017-02-07 10:57:57 +01001420 }
Michal Vasko1a38c862016-01-15 15:50:07 +01001421 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +01001422 }
1423
Michal Vasko09d700f2022-09-08 10:21:40 +02001424 return 1;
1425}
1426
1427int
romanf578cd52023-10-19 09:47:40 +02001428nc_accept_ssh_session(struct nc_session *session, struct nc_server_ssh_opts *opts, int sock, int timeout)
Michal Vasko09d700f2022-09-08 10:21:40 +02001429{
1430 ssh_bind sbind = NULL;
Michal Vasko09d700f2022-09-08 10:21:40 +02001431 int rc = 1, r;
1432 struct timespec ts_timeout;
roman4cc0cd52023-04-14 09:12:29 +02001433 const char *err_msg;
Michal Vasko09d700f2022-09-08 10:21:40 +02001434
Michal Vasko09d700f2022-09-08 10:21:40 +02001435 /* other transport-specific data */
1436 session->ti_type = NC_TI_LIBSSH;
1437 session->ti.libssh.session = ssh_new();
1438 if (!session->ti.libssh.session) {
1439 ERR(NULL, "Failed to initialize a new SSH session.");
1440 rc = -1;
1441 goto cleanup;
1442 }
1443
1444 sbind = ssh_bind_new();
1445 if (!sbind) {
1446 ERR(session, "Failed to create an SSH bind.");
1447 rc = -1;
1448 goto cleanup;
1449 }
1450
1451 /* configure host keys */
romanf578cd52023-10-19 09:47:40 +02001452 if (nc_ssh_bind_add_hostkeys(sbind, opts, opts->hostkey_count)) {
1453 rc = -1;
1454 goto cleanup;
1455 }
1456
1457 /* configure supported algorithms */
1458 if (opts->hostkey_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY_ALGORITHMS, opts->hostkey_algs)) {
1459 rc = -1;
1460 goto cleanup;
1461 }
1462 if (opts->encryption_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_CIPHERS_S_C, opts->encryption_algs)) {
1463 rc = -1;
1464 goto cleanup;
1465 }
1466 if (opts->kex_algs && ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_KEY_EXCHANGE, opts->kex_algs)) {
1467 rc = -1;
1468 goto cleanup;
1469 }
1470 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 +02001471 rc = -1;
1472 goto cleanup;
1473 }
1474
1475 /* accept new connection on the bind */
1476 if (ssh_bind_accept_fd(sbind, session->ti.libssh.session, sock) == SSH_ERROR) {
1477 ERR(session, "SSH failed to accept a new connection (%s).", ssh_get_error(sbind));
1478 rc = -1;
1479 goto cleanup;
1480 }
1481 sock = -1;
1482
romanf578cd52023-10-19 09:47:40 +02001483 /* set to non-blocking */
Michal Vasko09d700f2022-09-08 10:21:40 +02001484 ssh_set_blocking(session->ti.libssh.session, 0);
1485
1486 if (timeout > -1) {
Michal Vaskod8a74192023-02-06 15:51:50 +01001487 nc_timeouttime_get(&ts_timeout, timeout);
Michal Vasko09d700f2022-09-08 10:21:40 +02001488 }
1489 while ((r = ssh_handle_key_exchange(session->ti.libssh.session)) == SSH_AGAIN) {
1490 /* this tends to take longer */
1491 usleep(NC_TIMEOUT_STEP * 20);
Michal Vaskod8a74192023-02-06 15:51:50 +01001492 if ((timeout > -1) && (nc_timeouttime_cur_diff(&ts_timeout) < 1)) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001493 break;
1494 }
1495 }
1496 if (r == SSH_AGAIN) {
1497 ERR(session, "SSH key exchange timeout.");
1498 rc = 0;
1499 goto cleanup;
1500 } else if (r != SSH_OK) {
roman4cc0cd52023-04-14 09:12:29 +02001501 err_msg = ssh_get_error(session->ti.libssh.session);
1502 if (err_msg[0] == '\0') {
1503 err_msg = "hostkey algorithm generated from the hostkey most likely not found in the set of configured hostkey algorithms";
1504 }
1505 ERR(session, "SSH key exchange error (%s).", err_msg);
Michal Vasko09d700f2022-09-08 10:21:40 +02001506 rc = -1;
1507 goto cleanup;
1508 }
1509
1510 /* authenticate */
1511 if ((rc = nc_accept_ssh_session_auth(session, opts)) != 1) {
1512 goto cleanup;
1513 }
1514
Michal Vasko09d700f2022-09-08 10:21:40 +02001515 /* open channel and request 'netconf' subsystem */
romanf578cd52023-10-19 09:47:40 +02001516 if ((rc = nc_accept_ssh_session_open_netconf_channel(session, opts, timeout)) != 1) {
Michal Vasko09d700f2022-09-08 10:21:40 +02001517 goto cleanup;
Michal Vasko086311b2016-01-08 09:53:11 +01001518 }
1519
Michal Vasko09d700f2022-09-08 10:21:40 +02001520cleanup:
1521 if (sock > -1) {
1522 close(sock);
1523 }
1524 ssh_bind_free(sbind);
1525 return rc;
Michal Vasko086311b2016-01-08 09:53:11 +01001526}
1527
Michal Vasko71090fc2016-05-24 16:37:28 +02001528API NC_MSG_TYPE
1529nc_session_accept_ssh_channel(struct nc_session *orig_session, struct nc_session **session)
1530{
1531 NC_MSG_TYPE msgtype;
1532 struct nc_session *new_session = NULL;
Michal Vasko9f6275e2017-10-05 13:50:05 +02001533 struct timespec ts_cur;
Michal Vasko71090fc2016-05-24 16:37:28 +02001534
roman40672412023-05-04 11:10:22 +02001535 NC_CHECK_ARG_RET(orig_session, orig_session, session, NC_MSG_ERROR);
Michal Vasko71090fc2016-05-24 16:37:28 +02001536
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001537 if ((orig_session->status == NC_STATUS_RUNNING) && (orig_session->ti_type == NC_TI_LIBSSH) &&
1538 orig_session->ti.libssh.next) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001539 for (new_session = orig_session->ti.libssh.next;
1540 new_session != orig_session;
1541 new_session = new_session->ti.libssh.next) {
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001542 if ((new_session->status == NC_STATUS_STARTING) && new_session->ti.libssh.channel &&
1543 (new_session->flags & NC_SESSION_SSH_SUBSYS_NETCONF)) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001544 /* we found our session */
1545 break;
1546 }
1547 }
1548 if (new_session == orig_session) {
1549 new_session = NULL;
1550 }
1551 }
1552
1553 if (!new_session) {
Michal Vasko05532772021-06-03 12:12:38 +02001554 ERR(orig_session, "Session does not have a NETCONF SSH channel ready.");
Michal Vasko71090fc2016-05-24 16:37:28 +02001555 return NC_MSG_ERROR;
1556 }
1557
1558 /* assign new SID atomically */
Michal Vasko5bd4a3f2021-06-17 16:40:10 +02001559 new_session->id = ATOMIC_INC_RELAXED(server_opts.new_session_id);
Michal Vasko71090fc2016-05-24 16:37:28 +02001560
1561 /* NETCONF handshake */
Michal Vasko131120a2018-05-29 15:44:02 +02001562 msgtype = nc_handshake_io(new_session);
Michal Vasko71090fc2016-05-24 16:37:28 +02001563 if (msgtype != NC_MSG_HELLO) {
1564 return msgtype;
1565 }
1566
Michal Vaskod8a74192023-02-06 15:51:50 +01001567 nc_realtime_get(&ts_cur);
roman44efa322023-11-03 13:57:25 +01001568 new_session->opts.server.session_start = ts_cur;
Michal Vaskod8a74192023-02-06 15:51:50 +01001569 nc_timeouttime_get(&ts_cur, 0);
Michal Vasko9f6275e2017-10-05 13:50:05 +02001570 new_session->opts.server.last_rpc = ts_cur.tv_sec;
Michal Vasko71090fc2016-05-24 16:37:28 +02001571 new_session->status = NC_STATUS_RUNNING;
1572 *session = new_session;
1573
1574 return msgtype;
1575}
1576
1577API NC_MSG_TYPE
Michal Vasko96164bf2016-01-21 15:41:58 +01001578nc_ps_accept_ssh_channel(struct nc_pollsession *ps, struct nc_session **session)
Michal Vasko086311b2016-01-08 09:53:11 +01001579{
Michal Vaskobdcf2362016-07-26 11:35:43 +02001580 uint8_t q_id;
Michal Vasko71090fc2016-05-24 16:37:28 +02001581 NC_MSG_TYPE msgtype;
Michal Vaskoe4300a82017-05-24 10:35:42 +02001582 struct nc_session *new_session = NULL, *cur_session;
Michal Vasko9f6275e2017-10-05 13:50:05 +02001583 struct timespec ts_cur;
Michal Vaskoc61c4492016-01-25 11:13:34 +01001584 uint16_t i;
Michal Vasko086311b2016-01-08 09:53:11 +01001585
roman40672412023-05-04 11:10:22 +02001586 NC_CHECK_ARG_RET(NULL, ps, session, NC_MSG_ERROR);
Michal Vasko086311b2016-01-08 09:53:11 +01001587
Michal Vasko48a63ed2016-03-01 09:48:21 +01001588 /* LOCK */
Michal Vasko227f8ff2016-07-26 14:08:59 +02001589 if (nc_ps_lock(ps, &q_id, __func__)) {
Michal Vasko71090fc2016-05-24 16:37:28 +02001590 return NC_MSG_ERROR;
Michal Vaskof04a52a2016-04-07 10:52:10 +02001591 }
Michal Vasko48a63ed2016-03-01 09:48:21 +01001592
Michal Vasko96164bf2016-01-21 15:41:58 +01001593 for (i = 0; i < ps->session_count; ++i) {
fanchanghu3d4e7212017-08-09 09:42:30 +08001594 cur_session = ps->sessions[i]->session;
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001595 if ((cur_session->status == NC_STATUS_RUNNING) && (cur_session->ti_type == NC_TI_LIBSSH) &&
1596 cur_session->ti.libssh.next) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001597 /* an SSH session with more channels */
Michal Vaskoe4300a82017-05-24 10:35:42 +02001598 for (new_session = cur_session->ti.libssh.next;
1599 new_session != cur_session;
Michal Vasko96164bf2016-01-21 15:41:58 +01001600 new_session = new_session->ti.libssh.next) {
Michal Vaskob83a3fa2021-05-26 09:53:42 +02001601 if ((new_session->status == NC_STATUS_STARTING) && new_session->ti.libssh.channel &&
1602 (new_session->flags & NC_SESSION_SSH_SUBSYS_NETCONF)) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001603 /* we found our session */
1604 break;
1605 }
1606 }
Michal Vaskoe4300a82017-05-24 10:35:42 +02001607 if (new_session != cur_session) {
Michal Vasko96164bf2016-01-21 15:41:58 +01001608 break;
1609 }
Michal Vaskofb89d772016-01-08 12:25:35 +01001610
Michal Vasko96164bf2016-01-21 15:41:58 +01001611 new_session = NULL;
1612 }
1613 }
Michal Vaskofb89d772016-01-08 12:25:35 +01001614
Michal Vasko48a63ed2016-03-01 09:48:21 +01001615 /* UNLOCK */
Michal Vasko227f8ff2016-07-26 14:08:59 +02001616 nc_ps_unlock(ps, q_id, __func__);
Michal Vasko48a63ed2016-03-01 09:48:21 +01001617
Michal Vasko96164bf2016-01-21 15:41:58 +01001618 if (!new_session) {
Michal Vasko05532772021-06-03 12:12:38 +02001619 ERR(NULL, "No session with a NETCONF SSH channel ready was found.");
Michal Vasko71090fc2016-05-24 16:37:28 +02001620 return NC_MSG_ERROR;
Michal Vasko96164bf2016-01-21 15:41:58 +01001621 }
1622
1623 /* assign new SID atomically */
Michal Vasko5bd4a3f2021-06-17 16:40:10 +02001624 new_session->id = ATOMIC_INC_RELAXED(server_opts.new_session_id);
Michal Vaskofb89d772016-01-08 12:25:35 +01001625
Michal Vasko086311b2016-01-08 09:53:11 +01001626 /* NETCONF handshake */
Michal Vasko131120a2018-05-29 15:44:02 +02001627 msgtype = nc_handshake_io(new_session);
Michal Vasko71090fc2016-05-24 16:37:28 +02001628 if (msgtype != NC_MSG_HELLO) {
1629 return msgtype;
Michal Vasko086311b2016-01-08 09:53:11 +01001630 }
Michal Vasko48a63ed2016-03-01 09:48:21 +01001631
Michal Vaskod8a74192023-02-06 15:51:50 +01001632 nc_realtime_get(&ts_cur);
roman44efa322023-11-03 13:57:25 +01001633 new_session->opts.server.session_start = ts_cur;
Michal Vaskod8a74192023-02-06 15:51:50 +01001634 nc_timeouttime_get(&ts_cur, 0);
Michal Vasko9f6275e2017-10-05 13:50:05 +02001635 new_session->opts.server.last_rpc = ts_cur.tv_sec;
Michal Vasko086311b2016-01-08 09:53:11 +01001636 new_session->status = NC_STATUS_RUNNING;
Michal Vasko96164bf2016-01-21 15:41:58 +01001637 *session = new_session;
Michal Vasko086311b2016-01-08 09:53:11 +01001638
Michal Vasko71090fc2016-05-24 16:37:28 +02001639 return msgtype;
Michal Vasko086311b2016-01-08 09:53:11 +01001640}