-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathauth.c
More file actions
2265 lines (1986 loc) · 70.7 KB
/
Copy pathauth.c
File metadata and controls
2265 lines (1986 loc) · 70.7 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
/* auth.c
*
* Copyright (C) 2014-2026 wolfSSL Inc.
*
* This file is part of wolfSSH.
*
* wolfSSH is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* wolfSSH is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with wolfSSH. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#else
#include <wolfssl/options.h>
#endif
#ifdef WOLFSSH_SSHD
#ifdef __linux__
#define _XOPEN_SOURCE
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#endif
#ifndef _WIN32
#include <unistd.h>
#else
/* avoid macro redefinition warnings on STATUS values when include ntstatus.h */
#undef UMDF_USING_NTSTATUS
#define UMDF_USING_NTSTATUS
#undef UNICODE
#define UNICODE
#endif
#include <wolfssh/ssh.h>
#include <wolfssh/internal.h>
#include <wolfssh/log.h>
#include <wolfssl/wolfcrypt/wc_port.h>
#include <wolfssl/wolfcrypt/error-crypt.h>
#include <wolfssl/wolfcrypt/coding.h>
#ifdef WOLFSSL_FPKI
#include <wolfssl/wolfcrypt/asn.h>
#endif
#ifdef NO_INLINE
#include <wolfssh/misc.h>
#else
#define WOLFSSH_MISC_INCLUDED
#include "src/misc.c"
#endif
#include "configuration.h"
#ifndef _WIN32
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#include <grp.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>
#ifndef O_NOFOLLOW
/* Older platforms lack O_NOFOLLOW; the lstat() pre-check and the post-open
* st_dev/st_ino comparison still reject a symlinked leaf there. */
#define O_NOFOLLOW 0
#endif
#ifndef PATH_MAX
#define PATH_MAX 4096
#endif
#endif
#if !defined(_WIN32) && !(defined(__OSX__) || defined(__APPLE__))
#include <shadow.h>
#define HAVE_SHADOW
#endif
#if defined(WOLFSSHD_UNIT_TEST) && !defined(_WIN32)
int (*wsshd_setregid_cb)(WGID_T, WGID_T) = setregid;
int (*wsshd_setreuid_cb)(WUID_T, WUID_T) = setreuid;
#endif
struct WOLFSSHD_AUTH {
CallbackCheckUser checkUserCb;
CallbackCheckPassword checkPasswordCb;
CallbackCheckPublicKey checkPublicKeyCb;
const WOLFSSHD_CONFIG* conf;
#if defined(_WIN32)
HANDLE token; /* a users token */
#endif
int gid;
int uid;
int sGid; /* saved gid */
int sUid; /* saved uid */
int attempts;
void* heap;
};
#ifndef WOLFSSHD_MAX_PASSWORD_ATTEMPTS
#define WOLFSSHD_MAX_PASSWORD_ATTEMPTS 3
#endif
#ifndef MAX_LINE_SZ
#define MAX_LINE_SZ 900
#endif
#ifndef MAX_PATH_SZ
#define MAX_PATH_SZ 80
#endif
#if 0
/* this could potentially be useful in a deeply embedded future port */
/* Map user names to passwords */
/* Use arrays for username and p. The password or public key can
* be hashed and the hash stored here. Then I won't need the type. */
struct USER_NODE {
byte type;
byte username[32];
word32 usernameSz;
byte fingerprint[WC_SHA256_DIGEST_SIZE];
struct USER_NODE* next;
};
/* Takes a users input and adds it to the list of accepted users
* 'value' can be a users password / public key / or certificate
* returns an updated list on success (i.e. 'new' -> 'list' -> ...) or NULL
* on failure
*/
USER_NODE* AddNewUser(USER_NODE* list, byte type, const byte* username,
word32 usernameSz, const byte* value, word32 valueSz)
{
USER_NODE* map;
map = (USER_NODE*)WMALLOC(sizeof(USER_NODE), NULL, 0);
if (map != NULL) {
map->type = type;
if (usernameSz >= sizeof(map->username))
usernameSz = sizeof(map->username) - 1;
WMEMCPY(map->username, username, usernameSz + 1);
map->username[usernameSz] = 0;
map->usernameSz = usernameSz;
if (type != WOLFSSH_USERAUTH_NONE) {
wc_Sha256Hash(value, valueSz, map->fingerprint);
}
map->next = list;
}
return map;
}
#endif
/* TODO: Can use wolfSSH_ReadKey_buffer? */
#ifdef WOLFSSHD_UNIT_TEST
int CheckAuthKeysLine(char* line, word32 lineSz, const byte* key,
word32 keySz)
#else
static int CheckAuthKeysLine(char* line, word32 lineSz, const byte* key,
word32 keySz)
#endif
{
int ret = WSSHD_AUTH_SUCCESS;
char* type = NULL;
char* keyCandBase64 = NULL; /* cand == candidate */
word32 keyCandBase64Sz;
byte* keyCand = NULL;
word32 keyCandSz = 0;
char* last = NULL;
enum {
#ifdef WOLFSSH_CERTS
NUM_ALLOWED_TYPES = 9
#else
NUM_ALLOWED_TYPES = 5
#endif
};
static const char* allowedTypes[NUM_ALLOWED_TYPES] = {
"ssh-rsa",
"ssh-ed25519",
"ecdsa-sha2-nistp256",
"ecdsa-sha2-nistp384",
"ecdsa-sha2-nistp521",
#ifdef WOLFSSH_CERTS
"x509v3-ssh-rsa",
"x509v3-ecdsa-sha2-nistp256",
"x509v3-ecdsa-sha2-nistp384",
"x509v3-ecdsa-sha2-nistp521",
#endif
};
int typeOk = 0;
int i;
if (line == NULL || lineSz == 0 || key == NULL || keySz == 0) {
ret = WS_BAD_ARGUMENT;
}
if (ret == WSSHD_AUTH_SUCCESS) {
if ((type = WSTRTOK(line, " ", &last)) == NULL) {
ret = WS_FATAL_ERROR;
}
else if ((keyCandBase64 = WSTRTOK(NULL, " ", &last)) == NULL) {
ret = WS_FATAL_ERROR;
}
}
if (ret == WSSHD_AUTH_SUCCESS) {
for (i = 0; i < NUM_ALLOWED_TYPES; ++i) {
if (WSTRCMP(type, allowedTypes[i]) == 0) {
typeOk = 1;
break;
}
}
if (!typeOk) {
ret = WS_FATAL_ERROR;
}
}
if (ret == WSSHD_AUTH_SUCCESS) {
keyCandBase64Sz = (word32)XSTRLEN(keyCandBase64);
keyCandSz = (keyCandBase64Sz * 3 + 3) / 4;
keyCand = (byte*)WMALLOC(keyCandSz, NULL, DYNTYPE_BUFFER);
if (keyCand == NULL) {
ret = WS_MEMORY_E;
}
else {
if (Base64_Decode((byte*)keyCandBase64, keyCandBase64Sz, keyCand,
&keyCandSz) != 0) {
ret = WS_FATAL_ERROR;
}
}
}
if (ret == WSSHD_AUTH_SUCCESS) {
/* Constant-time compare to avoid leaking which prefix bytes of an
* authorized key match a candidate offered by a remote peer. */
if (keyCandSz != keySz ||
ConstantCompare(key, keyCand, keySz) != 0) {
ret = WSSHD_AUTH_FAILURE;
}
}
if (keyCand != NULL) {
WFREE(keyCand, NULL, DYNTYPE_BUFFER);
}
return ret;
}
#ifndef _WIN32
#ifdef WOLFSSH_USE_PAM
static int CheckPasswordPAM(const char* usr, const byte* pw, word32 pwSz)
{
(void)usr;
(void)pw;
(void)pwSz;
return 0;
}
#else
#if 0
static int ExtractSalt(char* hash, char** salt, int saltSz)
{
int ret = WS_SUCCESS;
int idx = 0;
char* p;
if (hash == NULL || salt == NULL || *salt == NULL || saltSz <= 0) {
ret = WS_SUCCESS;
}
if (ret == 0) {
if (hash[idx] != '$') {
ret = WS_FATAL_ERROR;
}
else {
++idx;
if (idx >= saltSz) {
ret = WS_BUFFER_E;
}
}
}
if (ret == 0) {
p = strstr(hash + idx, "$");
if (p == NULL) {
ret = -1;
}
else {
idx += (p - hash);
if (idx >= saltSz) {
ret = WS_BUFFER_E;
}
}
}
if (ret == 0) {
p = strstr(p + 1, "$");
if (p == NULL) {
ret = WS_FATAL_ERROR;
}
else {
idx += (p - (hash + idx) + 1);
if (idx >= saltSz) {
ret = WS_BUFFER_E;
}
}
}
if (ret == 0) {
memcpy(*salt, hash, idx);
(*salt)[idx] = 0;
}
return ret;
}
#endif
#if defined(WOLFSSH_HAVE_LIBCRYPT) || defined(WOLFSSH_HAVE_LIBLOGIN)
#ifdef WOLFSSHD_UNIT_TEST
int CheckPasswordHashUnix(const char* input, char* stored)
#else
static int CheckPasswordHashUnix(const char* input, char* stored)
#endif
{
int ret = WSSHD_AUTH_SUCCESS;
char* hashedInput;
word32 hashedInputSz = 0, storedSz = 0;
if (input == NULL || stored == NULL) {
ret = WS_BAD_ARGUMENT;
}
/* empty password case */
if (ret == WSSHD_AUTH_SUCCESS && stored[0] == 0 && WSTRLEN(input) == 0) {
wolfSSH_Log(WS_LOG_INFO,
"[SSHD] User logged in with empty password");
return ret;
}
if (ret == WSSHD_AUTH_SUCCESS) {
hashedInput = crypt(input, stored);
if (hashedInput == NULL) {
ret = WS_FATAL_ERROR;
}
else {
hashedInputSz = (word32)WSTRLEN(hashedInput);
storedSz = (word32)WSTRLEN(stored);
if (storedSz == 0 || stored[0] == '*' ||
hashedInputSz == 0 || hashedInput[0] == '*' ||
hashedInputSz != storedSz ||
ConstantCompare((const byte*)hashedInput,
(const byte*)stored, storedSz) != 0) {
ret = WSSHD_AUTH_FAILURE;
}
}
}
return ret;
}
#endif /* WOLFSSH_HAVE_LIBCRYPT || WOLFSSH_HAVE_LIBLOGIN */
static int CheckPasswordUnix(const char* usr, const byte* pw, word32 pwSz, WOLFSSHD_AUTH* authCtx)
{
int ret = WS_SUCCESS;
char* pwStr = NULL;
struct passwd* pwInfo;
#ifdef HAVE_SHADOW
struct spwd* shadowInfo;
#endif
/* The hash of the user's password stored on the system. */
char* storedHash;
char* storedHashCpy = NULL;
/* Allow zero length passwords, but not NULL pointers. */
if (usr == NULL || (pw == NULL && pwSz != 0)) {
ret = WS_BAD_ARGUMENT;
}
if (ret == WS_SUCCESS) {
pwStr = (char*)WMALLOC(pwSz + 1, NULL, DYNTYPE_STRING);
if (pwStr == NULL) {
ret = WS_MEMORY_E;
}
else {
if (pwSz > 0) {
XMEMCPY(pwStr, pw, pwSz);
}
pwStr[pwSz] = 0;
}
}
if (ret == WS_SUCCESS) {
pwInfo = getpwnam((const char*)usr);
if (pwInfo == NULL) {
/* user name not found on system */
ret = WS_FATAL_ERROR;
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] User name not found on system");
}
}
if (ret == WS_SUCCESS) {
#ifdef HAVE_SHADOW
if (pwInfo->pw_passwd[0] == 'x') {
#ifdef WOLFSSH_HAVE_LIBCRYPT
shadowInfo = getspnam((const char*)usr);
#else
shadowInfo = getspnam((char*)usr);
#endif
if (shadowInfo == NULL) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Error getting user password info");
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Possibly permissions level error?"
" i.e SSHD not ran as sudo");
ret = WS_FATAL_ERROR;
}
else {
storedHash = shadowInfo->sp_pwdp;
}
}
else
#endif
{
storedHash = pwInfo->pw_passwd;
}
}
if (ret == WS_SUCCESS) {
storedHashCpy = WSTRDUP(storedHash, NULL, DYNTYPE_STRING);
if (storedHashCpy == NULL) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Error getting stored hash copy");
ret = WS_MEMORY_E;
}
}
if (ret == WS_SUCCESS) {
#if defined(WOLFSSH_HAVE_LIBCRYPT) || defined(WOLFSSH_HAVE_LIBLOGIN)
ret = CheckPasswordHashUnix(pwStr, storedHashCpy);
#else
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] No compiled in password check");
ret = WS_NOT_COMPILED;
#endif
}
if (pwStr != NULL) {
ForceZero(pwStr, pwSz + 1);
WFREE(pwStr, NULL, DYNTYPE_STRING);
}
if (storedHashCpy != NULL) {
ForceZero(storedHashCpy, (word32)WSTRLEN(storedHashCpy) + 1);
WFREE(storedHashCpy, NULL, DYNTYPE_STRING);
}
WOLFSSH_UNUSED(authCtx);
return ret;
}
#endif /* WOLFSSH_USE_PAM */
#endif /* !_WIN32 */
static const char authKeysDefault[] = ".ssh/authorized_keys";
/* Resolve the authorized keys file path for a user. The pattern is the user's
* configured AuthorizedKeysFile (resolved per request from the per-user config)
* and is passed in explicitly rather than read from shared state so concurrent
* authentications (e.g. Windows threaded mode) cannot race on it. A NULL or
* empty pattern falls back to the default authorized_keys location. */
static int ResolveAuthKeysPath(const char* homeDir, const char* pattern,
char* resolved)
{
int ret = WS_SUCCESS;
char* idx;
int homeDirSz;
const char* suffix = authKeysDefault;
if (homeDir == NULL || resolved == NULL) {
ret = WS_BAD_ARGUMENT;
}
if (ret == WS_SUCCESS) {
if (pattern != NULL && *pattern != 0) {
/* TODO: token substitutions (e.g. %h) */
if (*pattern == '/') {
/* Absolute path is used as-is. Error out rather than
* silently truncate when it does not fit, mirroring the
* relative-path branch below. */
if (WSTRLEN(pattern) >= MAX_PATH_SZ) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Path for key file larger than max allowed");
ret = WS_FATAL_ERROR;
}
else {
WSTRNCPY(resolved, pattern, MAX_PATH_SZ - 1);
resolved[MAX_PATH_SZ - 1] = '\0';
}
return ret;
}
else {
suffix = pattern;
}
}
}
if (ret == WS_SUCCESS) {
idx = resolved;
homeDirSz = (int)XSTRLEN(homeDir);
if (homeDirSz + 1 + WSTRLEN(suffix) >= MAX_PATH_SZ) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Path for key file larger than max allowed");
ret = WS_FATAL_ERROR;
}
if (ret == WS_SUCCESS) {
XMEMCPY(idx, homeDir, homeDirSz);
idx += homeDirSz;
*(idx++) = '/';
/* Intentionally copying the null term from suffix. */
XMEMCPY(idx, suffix, WSTRLEN(suffix));
}
}
return ret;
}
/* Securely open a trusted file, failing closed on a symlink, bad ownership, or
* unsafe permissions, and hand back an open stream ready for reading. This is
* the single gate for every security-critical file wolfsshd loads: a user's
* authorized_keys, the host private key, the host certificate, and the user
* certificate-authority keys.
*
* path - file to open.
* ownerUid - the file itself must be owned by this user id or by root
* (0). authorized_keys uses the owning user's id; the
* daemon's trust anchors use the effective user id. Parent
* directories are checked for writability but not ownership,
* so a file may legitimately live under a directory owned by
* a third party (e.g. a key under a build checkout or a
* service account's tree).
* rejectReadable - when set, also refuse a file that is group or world
* readable. Used for secrets such as the host private key.
* heap - heap hint for the temporary path buffer.
* out - set to the open stream on success, WBADFILE otherwise.
*
* Returns WS_SUCCESS and sets *out on success; a specific reason is logged on
* failure. On platforms without POSIX ownership semantics (_WIN32) the checks
* are skipped and the file is opened directly, relying on filesystem ACLs. */
int wolfSSHD_OpenSecureFile(const char* path, WUID_T ownerUid,
int rejectReadable, void* heap, WFILE** out)
{
#ifndef _WIN32
int ret = WS_SUCCESS;
int fd = -1;
int flags;
struct stat lst;
struct stat st;
WFILE* f;
char* resolved = NULL;
char* slash;
word32 i;
if (path == NULL || out == NULL) {
return WS_BAD_ARGUMENT;
}
*out = WBADFILE;
/* The leaf must be a real, regular file. lstat() (not stat()) is used so a
* symlinked leaf is rejected outright rather than silently followed to an
* attacker-chosen target. */
if (lstat(path, &lst) != 0 || !S_ISREG(lst.st_mode)) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Refusing to load %s: missing, not a regular file, or a "
"symlink", path);
ret = WS_BAD_FILE_E;
}
/* Canonicalize the path with realpath(), resolving any intermediate
* symlinks, then open and validate that canonical path so the file opened
* and the parent chain validated below are one and the same. */
if (ret == WS_SUCCESS) {
resolved = (char*)WMALLOC(PATH_MAX, heap, DYNTYPE_BUFFER);
if (resolved == NULL) {
ret = WS_MEMORY_E;
}
}
if (ret == WS_SUCCESS) {
if (realpath(path, resolved) == NULL) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Unable to resolve path %s", path);
ret = WS_BAD_FILE_E;
}
}
/* Open the canonicalized path (not the original) so the directory chain
* validated below is exactly the chain open() traverses. realpath() already
* resolved every intermediate symlink; O_NOFOLLOW guards the
* already-verified non-symlink leaf, and O_NONBLOCK keeps the open from
* stalling on a FIFO swapped in after the lstat() and is cleared before the
* buffered reads. The original path is used only in log messages. */
if (ret == WS_SUCCESS) {
fd = open(resolved, O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
if (fd < 0) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Unable to open %s", path);
ret = WS_BAD_FILE_E;
}
}
if (ret == WS_SUCCESS) {
if (fstat(fd, &st) != 0) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Unable to stat %s", path);
ret = WS_BAD_FILE_E;
}
}
/* The ownership and mode checks run on the opened descriptor so there is no
* window to swap the file after the check. Comparing st_dev/st_ino against
* the earlier lstat() closes the narrow swap window on platforms where
* O_NOFOLLOW is unavailable and compiles to 0. */
if (ret == WS_SUCCESS) {
if (!S_ISREG(st.st_mode)) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Refusing to load %s: not a regular file", path);
ret = WS_BAD_FILE_E;
}
else if (st.st_uid != ownerUid && st.st_uid != 0) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Refusing to load %s: not owned by the user or root",
path);
ret = WS_BAD_FILE_E;
}
else if ((st.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Refusing to load %s: group or world writable", path);
ret = WS_BAD_FILE_E;
}
else if (rejectReadable && (st.st_mode & (S_IRGRP | S_IROTH)) != 0) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Refusing to load %s: group or world readable", path);
ret = WS_BAD_FILE_E;
}
else if (st.st_dev != lst.st_dev || st.st_ino != lst.st_ino) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Refusing to load %s: file changed during open", path);
ret = WS_BAD_FILE_E;
}
}
/* Validate every parent directory of the canonicalized path up to the
* filesystem root: none may be group or world writable (unless sticky),
* which is what would let another user rename the file and swap it. Ancestor
* ownership is not enforced; the leaf owner check above is what stops a file
* owned by a third party from being loaded. Since realpath() resolved all
* intermediate symlinks, this is the same chain open() traversed. The walk
* trims components from 'resolved' in place, which is fine now that the file
* is already open. */
while (ret == WS_SUCCESS) {
/* trim the last component to move up one directory */
slash = NULL;
for (i = 0; resolved[i] != '\0'; i++) {
if (resolved[i] == '/') {
slash = &resolved[i];
}
}
if (slash == NULL) {
break; /* no further parent (realpath always returns an absolute
* path, so this is not expected) */
}
if (slash == resolved) {
resolved[1] = '\0'; /* parent is the root directory "/" */
}
else {
*slash = '\0';
}
if (stat(resolved, &st) != 0) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Unable to stat directory %s", resolved);
ret = WS_BAD_FILE_E;
}
else if (!S_ISDIR(st.st_mode)) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] %s is not a directory", resolved);
ret = WS_BAD_FILE_E;
}
else if ((st.st_mode & (S_IWGRP | S_IWOTH)) != 0 &&
(st.st_mode & S_ISVTX) == 0) {
/* A world/group writable directory is unsafe unless it is sticky:
* the sticky bit stops a non-owner from renaming or deleting files
* they do not own, which is exactly the substitution this guards
* against (e.g. /tmp is mode 1777). */
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Directory %s is group or world writable", resolved);
ret = WS_BAD_FILE_E;
}
if (ret != WS_SUCCESS || WSTRCMP(resolved, "/") == 0) {
break; /* reached the filesystem root */
}
}
/* The target is a regular file, so restore blocking semantics for the
* buffered reads the caller will perform. */
if (ret == WS_SUCCESS) {
flags = fcntl(fd, F_GETFL);
if (flags != -1) {
(void)fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
}
f = fdopen(fd, "rb");
if (f == NULL) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Unable to open stream for %s", path);
ret = WS_BAD_FILE_E;
}
else {
fd = -1; /* ownership of the descriptor moved to the stream */
*out = f;
}
}
if (fd >= 0) {
close(fd);
}
if (resolved != NULL) {
WFREE(resolved, heap, DYNTYPE_BUFFER);
}
return ret;
#else
WOLFSSH_UNUSED(ownerUid);
WOLFSSH_UNUSED(rejectReadable);
WOLFSSH_UNUSED(heap);
if (path == NULL || out == NULL) {
return WS_BAD_ARGUMENT;
}
*out = WBADFILE;
if (WFOPEN(NULL, out, path, "rb") != 0) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Unable to open %s", path);
return WS_BAD_FILE_E;
}
return WS_SUCCESS;
#endif
}
static int SearchForPubKey(const char* path, const char* authKeysFile,
const WS_UserAuthData_PublicKey* pubKeyCtx,
WUID_T uid, int strictModes)
{
int ret = WSSHD_AUTH_SUCCESS;
char authKeysPath[MAX_PATH_SZ];
WFILE *f = XBADFILE;
char* lineBuf = NULL;
char* current;
word32 currentSz;
int foundKey = 0;
int rc = 0;
WMEMSET(authKeysPath, 0, sizeof(authKeysPath));
rc = ResolveAuthKeysPath(path, authKeysFile, authKeysPath);
if (rc != WS_SUCCESS) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failed to resolve authorized keys"
" file path.");
ret = rc;
}
/* When StrictModes is enabled, open through the secure gate: the file must
* be a regular file (no symlink), owned by the user or root, with no
* group/world writable component in its path. When disabled, fall back to a
* plain open. */
if (ret == WSSHD_AUTH_SUCCESS) {
if (strictModes) {
if (wolfSSHD_OpenSecureFile(authKeysPath, uid,
0 /* rejectReadable */, NULL, &f) != WS_SUCCESS) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Authorized keys file %s failed StrictModes check",
authKeysPath);
ret = WSSHD_AUTH_FAILURE;
}
}
else if (WFOPEN(NULL, &f, authKeysPath, "rb") != 0) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Unable to open %s",
authKeysPath);
ret = WS_BAD_FILE_E;
}
}
if (ret == WSSHD_AUTH_SUCCESS) {
lineBuf = (char*)WMALLOC(MAX_LINE_SZ, NULL, DYNTYPE_BUFFER);
if (lineBuf == NULL) {
ret = WS_MEMORY_E;
}
}
while (ret == WSSHD_AUTH_SUCCESS &&
(current = WFGETS(lineBuf, MAX_LINE_SZ, f)) != NULL) {
currentSz = (word32)WSTRLEN(current);
/* remove leading spaces */
while (currentSz > 0 && current[0] == ' ') {
currentSz = currentSz - 1;
current = current + 1;
}
if (currentSz <= 1) {
continue; /* empty line */
}
if (current[0] == '#') {
continue; /* commented out line */
}
rc = CheckAuthKeysLine(current, currentSz, pubKeyCtx->publicKey,
pubKeyCtx->publicKeySz);
if (rc == WSSHD_AUTH_SUCCESS) {
foundKey = 1;
break;
}
else if (rc < 0) {
ret = rc;
break;
}
}
if (f != WBADFILE) {
WFCLOSE(NULL, f);
}
if (lineBuf != NULL) {
WFREE(lineBuf, NULL, DYNTYPE_BUFFER);
}
if (ret == WSSHD_AUTH_SUCCESS && !foundKey) {
ret = WSSHD_AUTH_FAILURE;
}
return ret;
}
#ifndef _WIN32
static int CheckUserUnix(const char* name) {
int ret = WSSHD_AUTH_FAILURE;
struct passwd* pwInfo;
wolfSSH_Log(WS_LOG_INFO, "[SSHD] Unix check user");
errno = 0;
pwInfo = getpwnam(name);
if (pwInfo == NULL) {
if (errno != 0) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error calling getpwnam for user "
"%s.", name);
ret = WS_FATAL_ERROR;
}
}
else {
ret = WSSHD_AUTH_SUCCESS;
}
return ret;
}
static int CheckPublicKeyUnix(const char* name,
const WS_UserAuthData_PublicKey* pubKeyCtx,
const char* usrCaKeysFile,
const char* authorizedKeysFile,
WOLFSSHD_AUTH* authCtx)
{
int ret = WSSHD_AUTH_SUCCESS;
struct passwd* pwInfo;
#ifdef WOLFSSH_OSSH_CERTS
if (pubKeyCtx->isOsshCert) {
int rc;
byte* caKey = NULL;
word32 caKeySz;
const byte* caKeyType = NULL;
word32 caKeyTypeSz;
byte fingerprint[WC_SHA256_DIGEST_SIZE];
if (pubKeyCtx->caKey == NULL ||
pubKeyCtx->caKeySz != WC_SHA256_DIGEST_SIZE) {
ret = WS_FATAL_ERROR;
}
if (ret == WSSHD_AUTH_SUCCESS) {
f = XFOPEN(usrCaKeysFile, "rb");
if (f == XBADFILE) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Unable to open %s",
usrCaKeysFile);
ret = WS_BAD_FILE_E;
}
}
if (ret == WSSHD_AUTH_SUCCESS) {
lineBuf = (char*)WMALLOC(MAX_LINE_SZ, NULL, DYNTYPE_BUFFER);
if (lineBuf == NULL) {
ret = WS_MEMORY_E;
}
}
while (ret == WSSHD_AUTH_SUCCESS &&
(current = XFGETS(lineBuf, MAX_LINE_SZ, f)) != NULL) {
currentSz = (word32)XSTRLEN(current);
/* remove leading spaces */
while (currentSz > 0 && current[0] == ' ') {
currentSz = currentSz - 1;
current = current + 1;
}
if (currentSz <= 1) {
continue; /* empty line */
}
if (current[0] == '#') {
continue; /* commented out line */
}
rc = wolfSSH_ReadKey_buffer((const byte*)current, currentSz,
WOLFSSH_FORMAT_SSH, &caKey, &caKeySz,
&caKeyType, &caKeyTypeSz, NULL);
if (rc == WS_SUCCESS) {
rc = wc_Hash(WC_HASH_TYPE_SHA256, caKey, caKeySz, fingerprint,
WC_SHA256_DIGEST_SIZE);
if (rc == 0 && ConstantCompare(fingerprint, pubKeyCtx->caKey,
WC_SHA256_DIGEST_SIZE) == 0) {
foundKey = 1;
break;
}
}
}
}
else
#endif /* WOLFSSH_OSSH_CERTS */
{
errno = 0;
pwInfo = getpwnam((const char*)name);
if (pwInfo == NULL) {
if (errno != 0) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error calling getpwnam for user "
"%s.", name);
}
ret = WS_FATAL_ERROR;
}
if (ret == WSSHD_AUTH_SUCCESS) {
ret = SearchForPubKey(pwInfo->pw_dir, authorizedKeysFile, pubKeyCtx,
pwInfo->pw_uid, wolfSSHD_ConfigGetStrictModes(authCtx->conf));
}
}
WOLFSSH_UNUSED(usrCaKeysFile);
WOLFSSH_UNUSED(authCtx);
return ret;
}
#endif /* !_WIN32*/
#ifdef _WIN32
#include <ntstatus.h>
#include <Ntsecapi.h>
#include <Shlobj.h>
#include <UserEnv.h>
#include <KnownFolders.h>
/* Pulled in from Advapi32.dll */
extern BOOL WINAPI LogonUserExExW(LPTSTR usr,
LPTSTR dmn,
LPTSTR paswd,
DWORD logonType,
DWORD logonProv,
PTOKEN_GROUPS tokenGrp,
PHANDLE tokenPh,
PSID* loginSid,
PVOID* pBuffer,
LPDWORD pBufferLen ,
PQUOTA_LIMITS quotaLimits
);
#define MAX_USERNAME 256
static int _GetHomeDirectory(WOLFSSHD_AUTH* auth, const char* usr, WCHAR* out, int outSz)
{
int ret = WS_SUCCESS;
WCHAR usrW[MAX_USERNAME];
wchar_t* homeDir;
HRESULT hr;
size_t wr;
/* convert user name to Windows wchar type */
mbstowcs_s(&wr, usrW, MAX_USERNAME, usr, MAX_USERNAME-1);