-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathsession_server_ssh.c
More file actions
2326 lines (2037 loc) · 73 KB
/
session_server_ssh.c
File metadata and controls
2326 lines (2037 loc) · 73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file session_server_ssh.c
* @author Michal Vasko <mvasko@cesnet.cz>
* @brief libnetconf2 SSH server session manipulation functions
*
* @copyright
* Copyright (c) 2017 - 2021 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#define _GNU_SOURCE
#include "config.h" /* Expose HAVE_LIBPAM and HAVE_SHADOW */
#ifdef HAVE_LIBPAM
# include <security/pam_appl.h>
#endif
#ifdef HAVE_SHADOW
# include <shadow.h>
#endif
#include <arpa/inet.h>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <libssh/libssh.h>
#include <libssh/server.h>
#include <libyang/libyang.h>
#include <pwd.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include "compat.h"
#include "log_p.h"
#include "nc_version.h"
#include "session.h"
#include "session_p.h"
#include "session_wrapper.h"
/**
* @brief Stores the private key data as a temporary file.
*
* @param[in] in Private key data.
* @param[in] privkey_format String representation of the private key format.
* @return Path to the created temporary file or NULL on fail.
*/
static char *
nc_server_ssh_privkey_data_to_tmp_file(const char *in, const char *privkey_format)
{
char path[12] = "/tmp/XXXXXX";
int fd, written;
unsigned len;
mode_t umode;
FILE *file;
NC_CHECK_ARG_RET(NULL, in, NULL);
umode = umask(0177);
fd = mkstemp(path);
umask(umode);
if (fd == -1) {
return NULL;
}
file = fdopen(fd, "w");
if (!file) {
close(fd);
return NULL;
}
/* write header */
written = fwrite("-----BEGIN", 1, 10, file);
if (privkey_format) {
written += fwrite(privkey_format, 1, strlen(privkey_format), file);
written += fwrite("PRIVATE KEY-----\n", 1, 17, file);
} else {
written += fwrite(" PRIVATE KEY-----\n", 1, 18, file);
}
/* write data */
written += fwrite(in, 1, strlen(in), file);
/* write footer */
written += fwrite("\n-----END", 1, 9, file);
if (privkey_format) {
written += fwrite(privkey_format, 1, strlen(privkey_format), file);
written += fwrite("PRIVATE KEY-----", 1, 16, file);
} else {
written += fwrite(" PRIVATE KEY-----", 1, 17, file);
}
fclose(file);
/* checksum */
if (privkey_format) {
len = 10 + strlen(privkey_format) + 17 + strlen(in) + 9 + strlen(privkey_format) + 16;
} else {
len = 10 + 18 + strlen(in) + 9 + 17;
}
if ((unsigned)written != len) {
unlink(path);
return NULL;
}
return strdup(path);
}
/**
* @brief Get asymmetric key from the keystore.
*
* @param[in] referenced_name Name of the asymmetric key in the keystore.
* @param[out] askey Referenced asymmetric key.
* @return 0 on success, 1 on error.
*/
static int
nc_server_ssh_ks_ref_get_key(const char *referenced_name, struct nc_asymmetric_key **askey)
{
LY_ARRAY_COUNT_TYPE i;
struct nc_keystore *ks = &server_opts.config.keystore;
*askey = NULL;
/* lookup name */
LY_ARRAY_FOR(ks->entries, i) {
if (!strcmp(referenced_name, ks->entries[i].asym_key.name)) {
break;
}
}
if (i == LY_ARRAY_COUNT(ks->entries)) {
ERR(NULL, "Keystore entry \"%s\" not found.", referenced_name);
return 1;
}
*askey = &ks->entries[i].asym_key;
/* check if the referenced public key is SubjectPublicKeyInfo */
if ((*askey)->pubkey.data && nc_is_pk_subject_public_key_info((*askey)->pubkey.data)) {
ERR(NULL, "The public key of the referenced hostkey \"%s\" is in the SubjectPublicKeyInfo format, "
"which is not allowed in the SSH!", referenced_name);
return 1;
}
return 0;
}
/**
* @brief Get public keys from the truststore.
*
* @param[in] referenced_name Name of the public key bag in the truststore.
* @param[out] pubkeys Referenced public keys.
* @param[out] pubkey_count Referenced public key count.
* @return 0 on success, 1 on error.
*/
static int
nc_server_ssh_ts_ref_get_keys(const char *referenced_name, struct nc_public_key **pubkeys, uint32_t *pubkey_count)
{
LY_ARRAY_COUNT_TYPE i;
struct nc_public_key *pubkey;
struct nc_truststore *ts = &server_opts.config.truststore;
*pubkeys = NULL;
*pubkey_count = 0;
/* lookup name */
LY_ARRAY_FOR(ts->pubkey_bags, i) {
if (!strcmp(referenced_name, ts->pubkey_bags[i].name)) {
break;
}
}
if (i == LY_ARRAY_COUNT(ts->pubkey_bags)) {
ERR(NULL, "Truststore entry \"%s\" not found.", referenced_name);
return 1;
}
/* check if any of the referenced public keys is SubjectPublicKeyInfo */
LY_ARRAY_FOR(ts->pubkey_bags[i].pubkeys, struct nc_public_key, pubkey) {
if (nc_is_pk_subject_public_key_info(pubkey->data)) {
ERR(NULL, "A public key of the referenced public key bag \"%s\" is in the SubjectPublicKeyInfo format, "
"which is not allowed in SSH!", referenced_name);
return 1;
}
}
*pubkeys = ts->pubkey_bags[i].pubkeys;
*pubkey_count = LY_ARRAY_COUNT(ts->pubkey_bags[i].pubkeys);
return 0;
}
/**
* @brief Convert UID to string.
*
* @param[in] uid UID to convert.
* @return UID converted to string or NULL on fail.
*/
static char *
nc_server_ssh_uid_to_str(uid_t uid)
{
int buf_len;
char *uid_str;
/* get the number of digits and alloc */
buf_len = snprintf(NULL, 0, "%u", uid);
uid_str = malloc(buf_len + 1);
NC_CHECK_ERRMEM_RET(!uid_str, NULL);
/* convert to string */
sprintf(uid_str, "%u", uid);
uid_str[buf_len] = '\0';
return uid_str;
}
/**
* @brief Append a character or a string to a string.
*
* @param[in] src_c Source character.
* @param[in] src_str Source string.
* @param[in,out] size Size of the destination string.
* @param[out] idx Index of the next character to write.
* @param[out] dst Destination string.
* @return 0 on success, 1 on error.
*/
static int
nc_server_ssh_str_append(const char src_c, const char *src_str, int *size, int *idx, char **dst)
{
int src_size, allocate = 0, ret;
/* get size of char/string we want to append */
if (src_str) {
src_size = strlen(src_str);
} else {
src_size = 1;
}
/* check if we have enough space, if not realloc */
while ((src_size + *idx) >= *size) {
(*size) += 16;
allocate = 1;
}
if (allocate) {
*dst = nc_realloc(*dst, *size);
NC_CHECK_ERRMEM_RET(!*dst, 1);
}
/* append the char/string */
if (src_str) {
ret = sprintf(*dst + *idx, "%s", src_str);
} else {
ret = sprintf(*dst + *idx, "%c", src_c);
}
if (ret < 0) {
return 1;
}
*idx += ret;
return 0;
}
/**
* @brief Get the path to the system public keys from format set by an API.
*
* @param[in] username Username.
* @param[out] out_path Path to the system public keys.
* @return 0 on success, 1 on error.
*/
static int
nc_server_ssh_get_system_keys_path(const char *username, char **out_path)
{
int ret = 0, i, have_percent = 0, size = 0, idx = 0;
const char *path_fmt = server_opts.authkey_path_fmt;
char *path = NULL, *buf = NULL, *uid = NULL;
struct passwd *pw, pw_buf;
size_t buf_len = 0;
if (!path_fmt) {
ERR(NULL, "System public keys path format not set.");
return 1;
}
/* check if the path format contains any tokens */
if (strstr(path_fmt, "%h") || strstr(path_fmt, "%U") || strstr(path_fmt, "%u") || strstr(path_fmt, "%%")) {
/* get pw */
pw = nc_getpw(0, username, &pw_buf, &buf, &buf_len);
if (!pw) {
ERR(NULL, "Unable to get passwd entry for user \"%s\".", username);
ret = 1;
goto cleanup;
}
/* convert UID to a string */
uid = nc_server_ssh_uid_to_str(pw->pw_uid);
if (!uid) {
ret = 1;
goto cleanup;
}
} else {
/* no tokens, just copy the path and return */
*out_path = strdup(path_fmt);
NC_CHECK_ERRMEM_RET(!*out_path, 1);
goto cleanup;
}
/* go over characters from format, copy them to path and interpret tokens correctly */
for (i = 0; path_fmt[i]; i++) {
if (have_percent) {
/* special token, need to convert it */
if (path_fmt[i] == '%') {
ret = nc_server_ssh_str_append('%', NULL, &size, &idx, &path);
} else if (path_fmt[i] == 'h') {
/* user home */
ret = nc_server_ssh_str_append(0, pw->pw_dir, &size, &idx, &path);
} else if (path_fmt[i] == 'u') {
/* username */
ret = nc_server_ssh_str_append(0, username, &size, &idx, &path);
} else if (path_fmt[i] == 'U') {
/* UID */
ret = nc_server_ssh_str_append(0, uid, &size, &idx, &path);
} else {
ERR(NULL, "Failed to parse system public keys path format \"%s\".", server_opts.authkey_path_fmt);
ret = 1;
}
have_percent = 0;
} else {
if (path_fmt[i] == '%') {
have_percent = 1;
} else {
/* ordinary character with no meaning */
ret = nc_server_ssh_str_append(path_fmt[i], NULL, &size, &idx, &path);
}
}
if (ret) {
goto cleanup;
}
}
*out_path = path;
path = NULL;
cleanup:
free(uid);
free(buf);
free(path);
return ret;
}
/**
* @brief Read public keys from the authorized keys file.
*
* @param[in] path Path to the authorized keys file.
* @param[out] pubkeys Public keys.
* @param[out] pubkey_count Public key count.
* @return 0 on success, 1 on error.
*/
static int
nc_server_ssh_read_authorized_keys_file(const char *path, struct nc_public_key **pubkeys, uint32_t *pubkey_count)
{
int ret = 0, rc, line_num = 0;
FILE *f = NULL;
char *line = NULL, *ptr, *ptr2;
size_t n;
enum ssh_keytypes_e ktype;
NC_CHECK_ARG_RET(NULL, path, pubkeys, 1);
*pubkeys = NULL;
*pubkey_count = 0;
f = fopen(path, "r");
if (!f) {
ERR(NULL, "Unable to open \"%s\" (%s).", path, strerror(errno));
ret = 1;
goto cleanup;
}
while (getline(&line, &n, f) > -1) {
++line_num;
if ((line[0] == '#') || (line[0] == '\n')) {
/* comment or empty line */
continue;
}
/* separate key type */
ptr = line;
for (ptr2 = ptr; ptr2[0] && !isspace(ptr2[0]); ptr2++) {}
if (!ptr2[0]) {
ERR(NULL, "Invalid format of authorized keys file \"%s\" on line %d.", path, line_num);
ret = 1;
goto cleanup;
}
ptr2[0] = '\0';
/* detect key type */
ktype = ssh_key_type_from_name(ptr);
if ((ktype != SSH_KEYTYPE_RSA) && (ktype != SSH_KEYTYPE_ECDSA_P256) && (ktype != SSH_KEYTYPE_ECDSA_P384) &&
(ktype != SSH_KEYTYPE_ECDSA_P521) && (ktype != SSH_KEYTYPE_ED25519)) {
WRN(NULL, "Unsupported key type \"%s\" in authorized keys file \"%s\" on line %d.", ptr, path, line_num);
continue;
}
/* get key data */
ptr = ptr2 + 1;
for (ptr2 = ptr; ptr2[0] && !isspace(ptr2[0]); ptr2++) {}
ptr2[0] = '\0';
/* add the key */
*pubkeys = nc_realloc(*pubkeys, (*pubkey_count + 1) * sizeof **pubkeys);
NC_CHECK_ERRMEM_GOTO(!(*pubkeys), ret = 1, cleanup);
rc = asprintf(&(*pubkeys)[*pubkey_count].name, "authorized_key_%" PRIu16, *pubkey_count);
NC_CHECK_ERRMEM_GOTO(rc == -1, (*pubkeys)[*pubkey_count].name = NULL; ret = 1, cleanup);
(*pubkeys)[*pubkey_count].type = NC_PUBKEY_FORMAT_SSH;
(*pubkeys)[*pubkey_count].data = strdup(ptr);
NC_CHECK_ERRMEM_GOTO(!(*pubkeys)[*pubkey_count].data, ret = 1, cleanup);
(*pubkey_count)++;
}
/* ok */
ret = 0;
cleanup:
if (f) {
fclose(f);
}
free(line);
return ret;
}
/**
* @brief Get user's public keys from the system.
*
* @param[in] username Username.
* @param[out] pubkeys User's public keys.
* @param[out] pubkey_count Public key count.
* @return 0 on success, non-zero on error.
*/
static int
nc_server_ssh_get_system_keys(const char *username, struct nc_public_key **pubkeys, uint32_t *pubkey_count)
{
int ret = 0;
char *path = NULL;
/* convert the path format to get the actual path */
ret = nc_server_ssh_get_system_keys_path(username, &path);
if (ret) {
ERR(NULL, "Getting system keys path failed.");
goto cleanup;
}
/* get the keys */
ret = nc_server_ssh_read_authorized_keys_file(path, pubkeys, pubkey_count);
if (ret) {
ERR(NULL, "Reading system keys failed.");
goto cleanup;
}
cleanup:
free(path);
return ret;
}
#ifdef HAVE_SHADOW
/**
* @brief Get the user's /etc/passwd entry.
*
* @param[in] username Username.
* @param[out] pwd_buf Buffer for the passwd structure.
* @param[out] buf Buffer for the pwd's strings.
* @param[out] buf_size Size of the buffer.
* @return User's passwd entry or NULL on error.
*/
static struct passwd *
nc_server_ssh_getpwnam(const char *username, struct passwd *pwd_buf, char **buf, size_t *buf_size)
{
struct passwd *pwd = NULL;
char *mem;
int r = 0;
do {
r = getpwnam_r(username, pwd_buf, *buf, *buf_size, &pwd);
if (pwd) {
/* entry found */
break;
}
if (r == ERANGE) {
/* small buffer, enlarge */
*buf_size <<= 2;
mem = realloc(*buf, *buf_size);
if (!mem) {
ERRMEM;
return NULL;
}
*buf = mem;
}
} while (r == ERANGE);
return pwd;
}
/**
* @brief Get the user's /etc/shadow entry.
*
* @param[in] username Username.
* @param[out] spwd_buf Buffer for the spwd structure.
* @param[out] buf Buffer for the spwd's strings.
* @param[out] buf_size Size of the buffer.
* @return User's shadow entry or NULL on error.
*/
static struct spwd *
nc_server_ssh_getspnam(const char *username, struct spwd *spwd_buf, char **buf, size_t *buf_size)
{
struct spwd *spwd = NULL;
char *mem;
int r = 0;
do {
# ifndef __QNXNTO__
r = getspnam_r(username, spwd_buf, *buf, *buf_size, &spwd);
# else
spwd = getspnam_r(username, spwd_buf, *buf, *buf_size);
r = errno;
# endif
if (spwd) {
/* entry found */
break;
}
if (r == ERANGE) {
/* small buffer, enlarge */
*buf_size <<= 2;
mem = realloc(*buf, *buf_size);
if (!mem) {
ERRMEM;
return NULL;
}
*buf = mem;
}
} while (r == ERANGE);
return spwd;
}
/**
* @brief Get the user's hashed password from the system.
*
* @param[in] username Username.
* @return User's hashed password or NULL on error.
*/
static char *
nc_server_ssh_get_pwd_hash(const char *username)
{
struct passwd *pwd, pwd_buf;
struct spwd *spwd, spwd_buf;
char *pass_hash = NULL, *buf = NULL;
size_t buf_size = 256;
buf = malloc(buf_size);
NC_CHECK_ERRMEM_GOTO(!buf, , error);
pwd = nc_server_ssh_getpwnam(username, &pwd_buf, &buf, &buf_size);
if (!pwd) {
VRB(NULL, "User \"%s\" not found in the system.", username);
goto error;
}
if (!strcmp(pwd->pw_passwd, "x")) {
spwd = nc_server_ssh_getspnam(username, &spwd_buf, &buf, &buf_size);
if (!spwd) {
VRB(NULL, "Failed to retrieve the shadow entry for \"%s\".", username);
goto error;
} else if ((spwd->sp_expire > -1) && (spwd->sp_expire <= (time(NULL) / (60 * 60 * 24)))) {
WRN(NULL, "User \"%s\" account has expired.", username);
goto error;
}
pass_hash = spwd->sp_pwdp;
} else {
pass_hash = pwd->pw_passwd;
}
if (!pass_hash) {
ERR(NULL, "No password could be retrieved for \"%s\".", username);
goto error;
}
/* check the hash structure for special meaning */
if (!strcmp(pass_hash, "*") || !strcmp(pass_hash, "!")) {
VRB(NULL, "User \"%s\" is not allowed to authenticate using a password.", username);
goto error;
}
if (!strcmp(pass_hash, "*NP*")) {
VRB(NULL, "Retrieving password for \"%s\" from a NIS+ server not supported.", username);
goto error;
}
pass_hash = strdup(pass_hash);
free(buf);
return pass_hash;
error:
free(buf);
return NULL;
}
#endif
/**
* @brief Compare stored hashed password with a cleartext received password.
*
* @param[in] stored_pw Hashed stored password.
* @param[in] received_pw Cleartext received password.
* @return 0 on match, non-zero otherwise.
*/
static int
nc_server_ssh_compare_password(const char *stored_pw, const char *received_pw)
{
char *received_pw_hash = NULL;
struct crypt_data *cdata;
int ret;
NC_CHECK_ARG_RET(NULL, stored_pw, received_pw, 1);
if (!stored_pw[0]) {
if (!received_pw[0]) {
WRN(NULL, "User authentication successful with an empty password!");
return 0;
} else {
/* the user did now know he does not need any password,
* (which should not be used) so deny authentication */
return 1;
}
}
if (!strncmp(stored_pw, "$0$", 3)) {
/* cleartext password, simply compare the values */
return strcmp(stored_pw + 3, received_pw);
}
cdata = calloc(1, sizeof *cdata);
NC_CHECK_ERRMEM_RET(!cdata, 1);
received_pw_hash = crypt_r(received_pw, stored_pw, cdata);
if (!received_pw_hash) {
ERR(NULL, "Hashing the password failed (%s).", strerror(errno));
free(cdata);
return 1;
}
ret = strcmp(received_pw_hash, stored_pw);
free(cdata);
return ret;
}
API int
nc_server_ssh_kbdint_get_nanswers(const struct nc_session *session, ssh_session libssh_session)
{
int ret = 0;
struct timespec ts_timeout = {0};
ssh_message reply = NULL;
uint16_t auth_timeout = *((uint16_t *)session->data);
NC_CHECK_ARG_RET(NULL, session, libssh_session, -1);
if (auth_timeout) {
nc_timeouttime_get(&ts_timeout, auth_timeout * 1000);
}
/* wait for answers from the client */
do {
if (!ssh_is_connected(session->ti.libssh.session)) {
ERR(NULL, "SSH communication socket unexpectedly closed while waiting for keyboard-interactive authentication answers.");
ret = -1;
goto cleanup;
}
reply = ssh_message_get(libssh_session);
if (reply) {
break;
}
usleep(NC_TIMEOUT_STEP);
} while (auth_timeout && (nc_timeouttime_cur_diff(&ts_timeout) >= 1));
if (!reply) {
ERR(NULL, "Authentication timeout.");
ret = -1;
goto cleanup;
}
ret = ssh_userauth_kbdint_getnanswers(libssh_session);
cleanup:
ssh_message_free(reply);
return ret;
}
#ifdef HAVE_LIBPAM
/**
* @brief PAM conversation function, which serves as a callback for exchanging messages between the client and a PAM module.
*
* @param[in] n_messages Number of messages.
* @param[in] msg PAM module's messages.
* @param[out] resp User responses.
* @param[in] appdata_ptr Callback's data.
* @return PAM_SUCCESS on success, PAM_BUF_ERR on memory allocation error, PAM_CONV_ERR otherwise.
*/
static int
nc_pam_conv_clb(int n_messages, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr)
{
int i, j, t, r = PAM_SUCCESS, n_answers, n_requests = n_messages;
const char **prompts = NULL;
char *echo = NULL;
const char *name = "Keyboard-Interactive Authentication";
const char *instruction = "Please enter your authentication token";
ssh_message reply = NULL;
struct nc_pam_thread_arg *clb_data = appdata_ptr;
ssh_session libssh_session;
libssh_session = clb_data->session->ti.libssh.session;
/* PAM_MAX_NUM_MSG == 32 by default */
if ((n_messages <= 0) || (n_messages >= PAM_MAX_NUM_MSG)) {
ERR(clb_data->session, "Bad number of PAM messages (#%d).", n_messages);
r = PAM_CONV_ERR;
goto cleanup;
}
/* only accepting these 4 types of messages */
for (i = 0; i < n_messages; i++) {
t = msg[i]->msg_style;
if ((t != PAM_PROMPT_ECHO_OFF) && (t != PAM_PROMPT_ECHO_ON) && (t != PAM_TEXT_INFO) && (t != PAM_ERROR_MSG)) {
ERR(clb_data->session, "PAM conversation callback received an unexpected type of message.");
r = PAM_CONV_ERR;
goto cleanup;
}
}
/* display messages with errors and/or some information and count the amount of actual authentication challenges */
for (i = 0; i < n_messages; i++) {
if (msg[i]->msg_style == PAM_TEXT_INFO) {
VRB(clb_data->session, "PAM conversation callback received a message with some information for the client (%s).", msg[i]->msg);
n_requests--;
}
if (msg[i]->msg_style == PAM_ERROR_MSG) {
ERR(clb_data->session, "PAM conversation callback received an error message (%s).", msg[i]->msg);
r = PAM_CONV_ERR;
goto cleanup;
}
}
/* there are no requests left for the user, only messages with some information for the client were sent */
if (n_requests <= 0) {
r = PAM_SUCCESS;
goto cleanup;
}
/* it is the PAM module's responsibility to release both, this array and the responses themselves */
*resp = calloc(n_requests, sizeof **resp);
prompts = calloc(n_requests, sizeof *prompts);
echo = calloc(n_requests, sizeof *echo);
NC_CHECK_ERRMEM_GOTO(!(*resp) || !prompts || !echo, r = PAM_BUF_ERR, cleanup);
/* set the prompts for the user */
j = 0;
for (i = 0; i < n_messages; i++) {
if ((msg[i]->msg_style == PAM_PROMPT_ECHO_ON) || (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF)) {
prompts[j++] = msg[i]->msg;
}
}
/* iterate over all the messages and adjust the echo array accordingly */
j = 0;
for (i = 0; i < n_messages; i++) {
if (msg[i]->msg_style == PAM_PROMPT_ECHO_ON) {
echo[j++] = 1;
}
if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF) {
/* no need to set to 0 because of calloc */
j++;
}
}
/* print all the keyboard-interactive challenges to the user */
r = ssh_message_auth_interactive_request(clb_data->msg, name, instruction, n_requests, prompts, echo);
if (r != SSH_OK) {
ERR(clb_data->session, "Failed to send an authentication request.");
r = PAM_CONV_ERR;
goto cleanup;
}
n_answers = nc_server_ssh_kbdint_get_nanswers(clb_data->session, libssh_session);
if (n_answers < 0) {
/* timeout or dc */
r = PAM_CONV_ERR;
goto cleanup;
} else if (n_answers != n_requests) {
/* check if the number of answers and requests matches */
ERR(clb_data->session, "Expected %d response(s), got %d.", n_requests, n_answers);
r = PAM_CONV_ERR;
goto cleanup;
}
/* give the replies to a PAM module */
for (i = 0; i < n_answers; i++) {
(*resp)[i].resp = strdup(ssh_userauth_kbdint_getanswer(libssh_session, i));
/* it should be the caller's responsibility to free this, however if mem alloc fails,
* it is safer to free the responses here and set them to NULL */
if ((*resp)[i].resp == NULL) {
for (j = 0; j < i; j++) {
free((*resp)[j].resp);
(*resp)[j].resp = NULL;
}
ERRMEM;
r = PAM_BUF_ERR;
goto cleanup;
}
}
cleanup:
ssh_message_free(reply);
free(prompts);
free(echo);
return r;
}
/**
* @brief Handles authentication via Linux PAM.
*
* @param[in] session NETCONF session.
* @param[in] username Username of the client to auhtenticate.
* @param[in] ssh_msg SSH message with a keyboard-interactive authentication request.
* @return PAM_SUCCESS on success;
* @return PAM error otherwise.
*/
static int
nc_server_ssh_auth_kbdint_pam(struct nc_session *session, const char *username, ssh_message ssh_msg)
{
pam_handle_t *pam_h = NULL;
int ret;
struct nc_pam_thread_arg clb_data;
struct pam_conv conv;
/* structure holding callback's data */
clb_data.msg = ssh_msg;
clb_data.session = session;
/* PAM conversation structure holding the callback and it's data */
conv.conv = nc_pam_conv_clb;
conv.appdata_ptr = &clb_data;
if (!server_opts.pam_config_name) {
ERR(session, "PAM configuration filename not set.");
ret = 1;
goto cleanup;
}
/* initialize PAM and see if the given configuration file exists */
ret = pam_start(server_opts.pam_config_name, username, &conv, &pam_h);
if (ret != PAM_SUCCESS) {
ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
goto cleanup;
}
/* authentication based on the modules listed in the configuration file */
ret = pam_authenticate(pam_h, 0);
if (ret != PAM_SUCCESS) {
if (ret == PAM_ABORT) {
ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
goto cleanup;
} else {
VRB(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
goto cleanup;
}
}
/* correct token entered, check other requirements(the time of the day, expired token, ...) */
ret = pam_acct_mgmt(pam_h, 0);
if ((ret != PAM_SUCCESS) && (ret != PAM_NEW_AUTHTOK_REQD)) {
VRB(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
goto cleanup;
}
/* if a token has expired a new one will be generated */
if (ret == PAM_NEW_AUTHTOK_REQD) {
VRB(session, "PAM warning occurred (%s).", pam_strerror(pam_h, ret));
ret = pam_chauthtok(pam_h, PAM_CHANGE_EXPIRED_AUTHTOK);
if (ret == PAM_SUCCESS) {
VRB(session, "The authentication token of user \"%s\" updated successfully.", username);
} else {
ERR(session, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
goto cleanup;
}
}
cleanup:
/* destroy the PAM context */
if (pam_h && (pam_end(pam_h, ret) != PAM_SUCCESS)) {
ERR(NULL, "PAM error occurred (%s).", pam_strerror(pam_h, ret));
}
return ret;
}
#elif defined (HAVE_SHADOW)
/**
* @brief Authenticate using credentials stored in the system.
*
* @param[in] session Session to authenticate on.
* @param[in] username Username of the client to authenticate.
* @param[in] msg SSH message that originally requested kbdint authentication.
*
* @return 0 on success, non-zero otherwise.
*/
static int
nc_server_ssh_auth_kbdint_passwd(struct nc_session *session, const char *username, ssh_message msg)
{
int ret = 0, n_answers;
const char *name = "Keyboard-Interactive Authentication";
const char *instruction = "Please enter your authentication token";
char *prompt = NULL, *pw = NULL, *received_pw = NULL;
char echo[] = {0};
/* try to get the client's pw hash from the system */
pw = nc_server_ssh_get_pwd_hash(username);
if (!pw) {
ret = 1;
goto cleanup;
}
ret = asprintf(&prompt, "%s's password:", username);
NC_CHECK_ERRMEM_GOTO(ret == -1, prompt = NULL; ret = 1, cleanup);
/* send the password prompt to the client */
ret = ssh_message_auth_interactive_request(msg, name, instruction, 1, (const char **) &prompt, echo);
if (ret) {
ERR(session, "Failed to send an authentication request to client \"%s\".", username);
goto cleanup;
}
/* get the reply */
n_answers = nc_server_ssh_kbdint_get_nanswers(session, session->ti.libssh.session);
if (n_answers < 0) {
/* timeout or dc */
ret = 1;
goto cleanup;
} else if (n_answers != 1) {
/* only expecting a single answer */
ERR(session, "Unexpected amount of answers in system auth. Expected 1, got \"%d\".", n_answers);
ret = 1;
goto cleanup;
}
received_pw = strdup(ssh_userauth_kbdint_getanswer(session->ti.libssh.session, 0));
NC_CHECK_ERRMEM_GOTO(!received_pw, ret = 1, cleanup);
/* cmp the passwords */
ret = nc_server_ssh_compare_password(pw, received_pw);
cleanup:
free(pw);
free(received_pw);
free(prompt);
return ret;
}
#endif
/**
* @brief Keyboard-interactive authentication method using the system's authentication methods.
*
* @param[in] session NETCONF session.
* @param[in] msg SSH message with a keyboard-interactive authentication request.
* @return 0 on success, non-zero otherwise.
*/
static int
nc_server_ssh_auth_kbdint_system(struct nc_session *session, ssh_message msg)
{
int rc;
#ifdef HAVE_LIBPAM
/* authenticate using PAM */
rc = nc_server_ssh_auth_kbdint_pam(session, session->username, msg);
#elif defined (HAVE_SHADOW)
/* authenticate using /etc/passwd and /etc/shadow */
rc = nc_server_ssh_auth_kbdint_passwd(session, session->username, msg);
#else
(void)session;
(void)msg;