-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathwolfsshd.c
More file actions
3759 lines (3358 loc) · 126 KB
/
Copy pathwolfsshd.c
File metadata and controls
3759 lines (3358 loc) · 126 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
/* wolfsshd.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
#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/logging.h>
#include <wolfssl/wolfcrypt/asn_public.h>
#define WOLFSSH_TEST_SERVER
#include <wolfssh/test.h>
#include "configuration.h"
#include "auth.h"
#include <signal.h>
#ifdef NO_INLINE
#include <wolfssh/misc.h>
#else
#define WOLFSSH_MISC_INCLUDED
#include "src/misc.c"
#endif
#ifndef WOLFSSHD_TIMEOUT
#define WOLFSSHD_TIMEOUT 1
#endif
#ifdef EXAMPLE_BUFFER_SZ
#warning use WOLFSSHD_SHELL_BUFFER_SZ instead of EXAMPLE_BUFFER_SZ
#define WOLFSSHD_SHELL_BUFFER_SZ EXAMPLE_BUFFER_SZ
#endif
#if defined(WOLFSSH_SHELL) && !defined(_WIN32)
#ifdef HAVE_PTY_H
#include <pty.h>
#endif
#ifdef HAVE_UTIL_H
#include <util.h>
#endif
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif
#include <pwd.h>
#include <signal.h>
#include <sys/wait.h>
#if defined(__QNX__) || defined(__QNXNTO__)
#include <errno.h>
#include <unix.h>
#else
#include <errno.h>
#endif
static volatile int ChildRunning = 0;
static void ChildSig(int sig)
{
(void)sig;
ChildRunning = 0;
}
static void ConnClose(int sig)
{
#ifndef WIN32
pid_t p;
int ret;
p = wait(&ret);
if (p == 0 || p == -1)
return; /* parent or error state*/
(void)ret;
#endif
(void)sig;
}
#endif /* WOLFSSH_SHELL */
static volatile byte debugMode = 0; /* default to off */
static WFILE* logFile = NULL;
/* catch interrupts and close down gracefully */
static volatile byte quit = 0;
/* Initial connection information to pass on to threads/forks */
typedef struct WOLFSSHD_CONNECTION {
WOLFSSH_CTX* ctx;
WOLFSSHD_AUTH* auth;
int fd;
int listenFd;
char ip[INET6_ADDRSTRLEN];
byte isThreaded;
#ifdef _WIN32
/* set when the login grace time expires before authentication completes;
* POSIX uses the file-scope loginGraceTimedOut flag instead */
volatile byte timeOut;
PTP_TIMER loginTimer; /* threadpool timer enforcing login grace time */
#endif
} WOLFSSHD_CONNECTION;
#ifdef __unix__
#include <syslog.h>
static void SyslogCb(enum wolfSSH_LogLevel level, const char *const msgStr)
{
int priority;
switch (level) {
case WS_LOG_WARN:
priority = LOG_WARNING;
break;
case WS_LOG_ERROR:
priority = LOG_ERR;
break;
case WS_LOG_DEBUG:
priority = LOG_DEBUG;
break;
case WS_LOG_INFO:
case WS_LOG_USER:
case WS_LOG_SFTP:
case WS_LOG_SCP:
case WS_LOG_AGENT:
case WS_LOG_CERTMAN:
default:
priority = LOG_INFO;
break;
}
openlog("sshd", LOG_PID, LOG_DAEMON);
syslog(priority, "%s", msgStr);
closelog();
}
#endif
#ifdef _WIN32
static void ServiceDebugCb(enum wolfSSH_LogLevel level, const char* const msgStr)
#ifdef UNICODE
{
WCHAR* wc;
size_t szWord = WSTRLEN(msgStr) + 3; /* + 3 for null terminator and new
* line */
size_t sz = szWord *sizeof(wchar_t);
wc = (WCHAR*)WMALLOC(sz, NULL, DYNAMIC_TYPE_LOG);
if (wc) {
size_t con;
if (mbstowcs_s(&con, wc, szWord, msgStr, szWord-1) == 0) {
wc[con - 1] = L'\r';
wc[con] = L'\n';
wc[con + 1] = L'\0';
OutputDebugString(wc);
}
WFREE(wc, NULL, DYNAMIC_TYPE_LOG);
}
WOLFSSH_UNUSED(level);
}
#else
{
OutputDebugString(msgStr);
WOLFSSH_UNUSED(level);
}
#endif
#endif /* _WIN32 */
static void ShowUsage(void)
{
printf("wolfSSHd %s linked with wolfSSL %s\n", LIBWOLFSSH_VERSION_STRING,
LIBWOLFSSL_VERSION_STRING);
printf(" -? display this help and exit\n");
printf(" -f <file name> Configuration file to use, default is:\n"
" /etc/ssh/sshd_config\n");
printf(" -p <int> Port number to listen on\n");
printf(" -d Turn on debug mode\n");
printf(" -D Run in foreground (do not detach)\n");
printf(" -h <file name> host private key file to use\n");
printf(" -E <file name> append to log file\n");
}
/* catch if interrupted */
static void interruptCatch(int in)
{
(void)in;
quit = 1;
}
#ifdef WIN32
#include <processthreadsapi.h>
#define WGETPID GetCurrentProcessId
#else
#define WGETPID getpid
#endif
/* redirect logging to a specific file and add the PID value */
static void wolfSSHDLoggingCb(enum wolfSSH_LogLevel lvl, const char *const str)
{
/* always log errors and optionally log other info/debug level messages */
if (lvl == WS_LOG_ERROR || debugMode) {
fprintf(logFile, "[PID %d]: %s\n", WGETPID(), str);
/* flush so each line is visible immediately, e.g. to a consumer
* reading the log file while the daemon is still running */
fflush(logFile);
}
}
/* QNX fixes the host key's owner and modes in the system image, so
* WOLFSSH_NO_HOSTKEY_PERMS hands that policy to the platform. Host key only, and
* only ownership, modes and directories. Kept outside the NO_FILESYSTEM guard
* below because SetupCTX() tests it and -Wundef is on. wolfssh-options.c repeats
* this guard so the tests can skip the negative cases; keep the two in step. */
#if defined(WOLFSSH_NO_HOSTKEY_PERMS) && \
(defined(__QNX__) || defined(__QNXNTO__))
#define WOLFSSHD_HOSTKEY_RELAX_PERMS 1
#else
#define WOLFSSHD_HOSTKEY_RELAX_PERMS 0
#endif
#ifndef NO_FILESYSTEM
static void freeBufferFromFile(byte* buf, void* heap)
{
if (buf != NULL)
WFREE(buf, heap, DYNTYPE_SSHD);
(void)heap;
}
/* Load class for getBufferFromFile(). NORMAL files (e.g. the banner) are opened
* directly. TRUST and SECRET files are trust anchors loaded through the secure
* gate (no symlink, owned by root or the daemon, no group/world writable path
* component); SECRET additionally rejects a group/world readable file, used for
* the host private key. */
enum {
WOLFSSHD_LOAD_NORMAL = 0,
WOLFSSHD_LOAD_TRUST = 1,
WOLFSSHD_LOAD_SECRET = 2
};
/* set bufSz to size wanted if too small and buf is null */
static byte* getBufferFromFile(const char* fileName, word32* bufSz, void* heap,
int loadClass)
{
FILE* file;
byte* buf = NULL;
long fileSz;
word32 readSz;
int relaxPerms = 0;
WOLFSSH_UNUSED(heap);
if (fileName == NULL) return NULL;
#if WOLFSSHD_HOSTKEY_RELAX_PERMS
if (loadClass == WOLFSSHD_LOAD_SECRET) {
relaxPerms = 1;
}
#endif
if (loadClass == WOLFSSHD_LOAD_NORMAL) {
if (WFOPEN(NULL, &file, fileName, "rb") != 0)
return NULL;
}
else {
/* Trust anchors always go through the secure gate, regardless of
* StrictModes. The owner is the daemon's effective user (or root), and
* the host private key (SECRET) is also refused if group/world
* readable, unless WOLFSSHD_HOSTKEY_RELAX_PERMS. */
if (wolfSSHD_OpenSecureFile(fileName,
#ifndef _WIN32
geteuid(),
#else
0,
#endif
loadClass == WOLFSSHD_LOAD_SECRET /* rejectReadable */,
relaxPerms, heap, &file) != WS_SUCCESS) {
return NULL;
}
}
if (!WFSEEK_SUCCESS(WFSEEK(NULL, file, 0, WSEEK_END))) {
WFCLOSE(NULL, file);
return NULL;
}
fileSz = WFTELL(NULL, file);
if (fileSz < 0) {
WFCLOSE(NULL, file);
return NULL;
}
WREWIND(NULL, file);
buf = (byte*)WMALLOC(fileSz + 1, heap, DYNTYPE_SSHD);
if (buf != NULL) {
readSz = (word32)WFREAD(NULL, buf, 1, fileSz, file);
if (readSz < (size_t)fileSz) {
WFCLOSE(NULL, file);
WFREE(buf, heap, DYNTYPE_SSHD);
return NULL;
}
/* NUL terminate so callers that treat the buffer as a C string (e.g.
* the banner via wolfSSH_CTX_SetBanner/WSTRLEN) do not read past the
* allocation. The extra byte was already accounted for above. */
buf[readSz] = '\0';
if (bufSz)
*bufSz = readSz;
}
WFCLOSE(NULL, file);
return buf;
}
#endif /* NO_FILESYSTEM */
static int UserAuthResult(byte result,
WS_UserAuthData* authData, void* userAuthResultCtx);
/* Frees up the WOLFSSH_CTX struct */
static void CleanupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx,
byte** banner)
{
if (banner != NULL && *banner != NULL) {
#ifndef NO_FILESYSTEM
freeBufferFromFile(*banner, NULL);
#endif
*banner = NULL;
}
if (ctx != NULL && *ctx != NULL) {
wolfSSH_CTX_free(*ctx);
*ctx = NULL;
}
(void)conf;
}
/* Initializes and sets up the WOLFSSH_CTX struct based on the configure options
* return WS_SUCCESS on success
*/
static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx,
byte** banner)
{
int ret = WS_SUCCESS;
byte* keyDer = NULL;
byte* privBuf = NULL;
word32 privBufSz = 0;
void* heap = NULL;
if (ctx == NULL) {
return WS_BAD_ARGUMENT;
}
/* create a new WOLFSSH_CTX */
*ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (*ctx == NULL) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Couldn't allocate SSH CTX data.");
ret = WS_MEMORY_E;
}
/* setup authority callback for checking peer connections */
if (ret == WS_SUCCESS) {
wolfSSH_SetUserAuth(*ctx, DefaultUserAuth);
wolfSSH_SetUserAuthResult(*ctx, UserAuthResult);
}
/* set banner to display on connection */
if (ret == WS_SUCCESS) {
#ifndef NO_FILESYSTEM
*banner = getBufferFromFile(wolfSSHD_ConfigGetBanner(conf),
NULL, heap, WOLFSSHD_LOAD_NORMAL);
#endif
if (*banner) {
wolfSSH_CTX_SetBanner(*ctx, (char*)*banner);
}
}
/* Load in host private key */
if (ret == WS_SUCCESS) {
char* hostKey = wolfSSHD_ConfigGetHostKeyFile(conf);
if (hostKey == NULL) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] No host private key set");
ret = WS_BAD_ARGUMENT;
}
else {
byte* data;
word32 dataSz = 0;
/* The host private key is a secret trust anchor: refuse a symlink,
* an unsafe owner or path, or a group/world readable/writable
* file. WOLFSSHD_HOSTKEY_RELAX_PERMS keeps only the symlink and
* regular-file checks. */
#if WOLFSSHD_HOSTKEY_RELAX_PERMS
wolfSSH_Log(WS_LOG_INFO, "[SSHD] Built with "
"WOLFSSH_NO_HOSTKEY_PERMS, host key ownership and permissions "
"are left to the platform");
#endif
data = getBufferFromFile(hostKey, &dataSz, heap,
WOLFSSHD_LOAD_SECRET);
if (data == NULL) {
/* NULL means the secure gate rejected the file (bad owner,
* symlink, group/world writable/readable; reason already
* logged) or the read failed, so report a file error rather
* than a memory error. */
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Error reading host key file.");
ret = WS_BAD_FILE_E;
}
if (ret == WS_SUCCESS) {
/* Host keys may be OpenSSH, PEM, or DER; detect the format
* and decode PEM/DER via wc_KeyPemToDer(), which handles
* PKCS#8 keys with no traditional DER form (e.g. ML-DSA). */
if (dataSz == 0) {
/* An empty (0-byte) file passes the NULL check above but
* carries no key material. Handle it explicitly as a file
* error instead of falling into the PEM path, where
* WMALLOC(0) is implementation-defined (may return NULL and
* be misreported as WS_MEMORY_E). */
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Host key file is empty.");
ret = WS_BAD_FILE_E;
}
else {
int keyFormat = wolfSSHD_DetectPrivKeyFormat(data, dataSz,
heap, &keyDer, &privBuf, &privBufSz);
if (keyFormat == WS_MEMORY_E) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Out of memory reading host private key.");
ret = WS_MEMORY_E;
}
else if (keyFormat < 0) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Host private key file is invalid.");
ret = WS_BAD_FILE_E;
}
else if (keyFormat == WOLFSSH_FORMAT_OPENSSH) {
wolfSSH_Log(WS_LOG_DEBUG, "[SSHD] Loading host private "
"key as OpenSSH format.");
}
else {
wolfSSH_Log(WS_LOG_DEBUG, "[SSHD] Loading host private "
"key as DER format.");
}
if (ret == WS_SUCCESS &&
wolfSSH_CTX_UsePrivateKey_buffer(*ctx, privBuf,
privBufSz, keyFormat) < 0) {
if (keyFormat == WOLFSSH_FORMAT_OPENSSH) {
/* Only composite ML-DSA keys support this format. */
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Failed to use host private key: "
"OpenSSH format is only supported for "
"composite ML-DSA keys; convert with "
"\"ssh-keygen -p -m PEM\".");
}
else {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Failed to use host private key.");
}
ret = WS_BAD_ARGUMENT;
}
}
if (keyDer != NULL) {
WS_FORCEZERO(keyDer, dataSz);
WFREE(keyDer, heap, DYNTYPE_SSHD);
}
/* data is the key material itself for raw DER/OpenSSH
* input (privBuf aliases it directly, no copy). */
WS_FORCEZERO(data, dataSz);
freeBufferFromFile(data, heap);
}
}
}
#if defined(WOLFSSH_OSSH_CERTS) || defined(WOLFSSH_CERTS)
if (ret == WS_SUCCESS) {
char* hostCert = wolfSSHD_ConfigGetHostCertFile(conf);
if (hostCert != NULL) {
byte* data;
word32 dataSz = 0;
#ifdef WOLFSSH_CERTS
byte* der = NULL;
word32 derSz = 0;
const byte* type = NULL;
word32 typeSz = 0;
byte flavor = WOLFSSH_CERT_FLAVOR_UNKNOWN;
#endif
data = getBufferFromFile(hostCert, &dataSz, heap,
WOLFSSHD_LOAD_TRUST);
if (data == NULL) {
/* secure-gate rejection or read failure, not memory */
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Error reading host certificate file.");
ret = WS_BAD_FILE_E;
}
if (ret == WS_SUCCESS) {
#ifdef WOLFSSH_CERTS
if (dataSz == 0) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Host certificate file %s is empty.", hostCert);
ret = WS_BAD_FILE_E;
}
else {
/* Already read through the secure gate, so not _file. */
ret = wolfSSH_ReadCert_buffer(data, dataSz, &der, &derSz,
&type, &typeSz, &flavor, heap);
if (ret == WS_SUCCESS
&& flavor != WOLFSSH_CERT_FLAVOR_X509) {
/* Verifying OpenSSH host certs is unimplemented. */
ret = WS_UNIMPLEMENTED_E;
}
if (ret == WS_SUCCESS) {
ret = wolfSSH_CTX_UseCert_buffer(*ctx, der, derSz,
WOLFSSH_FORMAT_ASN1);
}
if (ret != WS_SUCCESS) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Failed to load in host certificate.");
}
if (der != NULL) {
WFREE(der, heap, DYNTYPE_CERT);
}
}
#else
/* Only OpenSSH host certificates could apply here, and they are
* not implemented. Fail rather than ignore the directive. */
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] HostCertificate is set but OpenSSH host "
"certificates are not supported in this build.");
ret = WS_UNIMPLEMENTED_E;
#endif
freeBufferFromFile(data, heap);
}
}
}
#endif /* WOLFSSH_OSSH_CERTS || WOLFSSH_CERTS */
#ifdef WOLFSSH_CERTS
if (ret == WS_SUCCESS) {
char* caCert = wolfSSHD_ConfigGetUserCAKeysFile(conf);
if (caCert != NULL) {
byte* data;
word32 dataSz = 0;
wolfSSH_Log(WS_LOG_INFO, "[SSHD] Using CA keys file %s", caCert);
data = getBufferFromFile(caCert, &dataSz, heap,
WOLFSSHD_LOAD_TRUST);
if (data == NULL) {
/* secure-gate rejection or read failure, not memory */
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Error reading CA cert file.");
ret = WS_BAD_FILE_E;
}
if (ret == WS_SUCCESS && dataSz == 0) {
/* Empty means misconfigured, not a CA in another format. */
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] CA keys file %s is empty.",
caCert);
ret = WS_BAD_FILE_E;
freeBufferFromFile(data, heap);
}
else if (ret == WS_SUCCESS) {
/* A CA is never named on the wire, so it takes raw bytes. */
ret = wolfSSH_CTX_AddRootCert_buffer(*ctx, data, dataSz,
WOLFSSH_FORMAT_PEM);
if (ret != WS_SUCCESS) {
ret = wolfSSH_CTX_AddRootCert_buffer(*ctx, data, dataSz,
WOLFSSH_FORMAT_ASN1);
}
if (ret != WS_SUCCESS) {
#ifdef WOLFSSH_OSSH_CERTS
/* The file is not X.509; when OpenSSH certificates are also
* built, fall through and let the OpenSSH user-auth path
* consume TrustedUserCAKeys instead of failing startup. */
wolfSSH_Log(WS_LOG_INFO,
"[SSHD] CA keys file is not X.509; using it as an "
"OpenSSH-style CA.");
ret = WS_SUCCESS;
#else
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Failed to load in CA certificate.");
#endif
}
freeBufferFromFile(data, heap);
}
}
}
#endif
if (ret == WS_SUCCESS) {
wolfSSH_SetUserAuthTypes(*ctx, DefaultUserAuthTypes);
}
/* @TODO Load in host public key */
/* Set allowed connection type, i.e. public key / password */
(void)heap;
return ret;
}
#ifndef _WIN32
/* return 1 if set, 0 if not set and negative values on error */
static int SetupChroot(WOLFSSHD_CONFIG* usrConf)
{
int ret = 0;
char* chrootPath;
/* check for chroot set */
chrootPath = wolfSSHD_ConfigGetChroot(usrConf);
if (chrootPath != NULL) {
ret = 1;
wolfSSH_Log(WS_LOG_INFO, "[SSHD] chroot to path %s", chrootPath);
if (chdir(chrootPath) != 0) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] chdir to chroot path failed, %s", chrootPath);
ret = WS_FATAL_ERROR;
}
/* Only chroot() once the chdir() into the target succeeded, and only
* chdir("/") once inside the new root. Running a later step after an
* earlier failure could leave the process chrooted with a working
* directory outside the new root. */
if (ret == 1 && chroot(chrootPath) != 0) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] chroot failed to path %s", chrootPath);
ret = WS_FATAL_ERROR;
}
if (ret == 1 && chdir("/") != 0) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] chdir after chroot failed");
ret = WS_FATAL_ERROR;
}
}
return ret;
}
#endif
/* Resolve the force-command in effect for this session. A configured
* ForceCommand takes precedence over a certificate's force-command. Returns
* NULL when none is set. */
static const char* GetEffectiveForcedCmd(WOLFSSHD_CONNECTION* conn,
WOLFSSHD_CONFIG* usrConf)
{
const char* forcedCmd;
forcedCmd = wolfSSHD_ConfigGetForcedCmd(usrConf);
#ifdef WOLFSSH_OSSH_CERTS
forcedCmd = wolfSSHD_AuthMergeForcedCmd(forcedCmd,
wolfSSHD_AuthGetForcedCmd(conn->auth));
#else
(void)conn;
#endif
return forcedCmd;
}
/* The force-command carried by an authenticated certificate, or NULL. A
* configured ForceCommand does not mask it: the certificate restricts what the
* session may do, while ForceCommand replaces what is run. */
static const char* GetCertForcedCmd(WOLFSSHD_CONNECTION* conn)
{
#ifdef WOLFSSH_OSSH_CERTS
return wolfSSHD_AuthGetForcedCmd(conn->auth);
#else
(void)conn;
return NULL;
#endif
}
#ifdef WOLFSSH_SCP
static int SCP_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh,
WPASSWD* pPasswd, WOLFSSHD_CONFIG* usrConf)
{
int ret = WS_SUCCESS;
int error = WS_SUCCESS;
int select_ret = 0;
#ifndef _WIN32
/* temporarily elevate permissions to get users information */
if (wolfSSHD_AuthRaisePermissions(conn->auth) != WS_SUCCESS) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Failure to raise permissions for auth");
return WS_FATAL_ERROR;
}
/* set additional groups if needed */
if (wolfSSHD_AuthSetGroups(conn->auth, wolfSSH_GetUsername(ssh),
pPasswd->pw_gid) != WS_SUCCESS) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error setting groups");
ret = WS_FATAL_ERROR;
}
if (ret == WS_SUCCESS) {
error = SetupChroot(usrConf);
if (error < 0) {
ret = error; /* error case with setup chroot */
}
}
if (wolfSSHD_AuthReducePermissionsUser(conn->auth, pPasswd->pw_uid,
pPasswd->pw_gid) != WS_SUCCESS) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error setting user ID");
/* could not drop to the authenticated user; terminate the
* per-connection process rather than continue at a higher
* privilege level */
exit(1);
}
#else
/* impersonate the logged on user for file permissions */
if (ImpersonateLoggedOnUser(wolfSSHD_GetAuthToken(conn->auth)) == FALSE) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Error impersonating logged on user");
ret = WS_FATAL_ERROR;
}
#endif
if (ret == WS_SUCCESS) {
ret = wolfSSH_accept(ssh);
error = wolfSSH_get_error(ssh);
while (ret != WS_SUCCESS && ret != WS_SCP_COMPLETE
&& (error == WS_WANT_READ || error == WS_WANT_WRITE)) {
select_ret = tcp_select(conn->fd, 1);
if (select_ret == WS_SELECT_RECV_READY ||
select_ret == WS_SELECT_ERROR_READY ||
error == WS_WANT_WRITE)
{
ret = wolfSSH_accept(ssh);
error = wolfSSH_get_error(ssh);
}
else if (select_ret == WS_SELECT_TIMEOUT)
error = WS_WANT_READ;
else
error = WS_FATAL_ERROR;
}
}
if (ret != WS_SUCCESS && ret != WS_SCP_COMPLETE) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Failed to finish SCP operation from IP %s",
conn->ip);
}
(void)conn;
#ifdef _WIN32
/* stop impersonating the user */
RevertToSelf();
#endif
return ret;
}
#endif /* WOLFSSH_SCP */
#ifdef WOLFSSH_SFTP
#define TEST_SFTP_TIMEOUT 1
#define TEST_SFTP_TIMEOUT_NONE 0
/* handle SFTP operations
* returns WS_SUCCESS on success
*/
static int SFTP_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh,
WPASSWD* pPasswd, WOLFSSHD_CONFIG* usrConf)
{
int ret = WS_SUCCESS;
int error = WS_SUCCESS;
WS_SOCKET_T sockfd;
int select_ret = 0;
int timeout = TEST_SFTP_TIMEOUT_NONE;
byte peek_buf[1];
#ifndef _WIN32
/* temporarily elevate permissions to get users information */
if (wolfSSHD_AuthRaisePermissions(conn->auth) != WS_SUCCESS) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Failure to raise permissions for auth");
return WS_FATAL_ERROR;
}
/* set additional groups if needed */
if (wolfSSHD_AuthSetGroups(conn->auth, wolfSSH_GetUsername(ssh),
pPasswd->pw_gid) != WS_SUCCESS) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error setting groups");
ret = WS_FATAL_ERROR;
}
if (ret == WS_SUCCESS) {
error = SetupChroot(usrConf);
if (error == 1) {
/* chroot was executed */
if (wolfSSH_SFTP_SetDefaultPath(ssh, "/") != WS_SUCCESS) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Error setting SFTP default path");
ret = WS_FATAL_ERROR;
}
}
else if (error < 0) {
ret = error; /* error case with setup chroot */
}
}
/* set starting SFTP directory */
if (ret == WS_SUCCESS) {
WDIR dir;
/* if home directory exists than set it as the default */
if (WOPENDIR(NULL, NULL, &dir, pPasswd->pw_dir) == 0) {
if (wolfSSH_SFTP_SetDefaultPath(ssh, pPasswd->pw_dir)
!= WS_SUCCESS) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Error setting SFTP default home path");
ret = WS_FATAL_ERROR;
}
WCLOSEDIR(NULL, &dir);
}
}
if (wolfSSHD_AuthReducePermissionsUser(conn->auth, pPasswd->pw_uid,
pPasswd->pw_gid) != WS_SUCCESS) {
wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error setting user ID");
/* could not drop to the authenticated user; terminate the
* per-connection process rather than continue at a higher
* privilege level */
exit(1);
}
#else
char r[MAX_PATH];
size_t rSz = 0;
WCHAR h[MAX_PATH];
ret = wolfSSHD_GetHomeDirectory(conn->auth, ssh, h, MAX_PATH);
/* convert home directory from wchar type to char */
if (ret == WS_SUCCESS) {
if (wcstombs_s(&rSz, r, MAX_PATH, h, MAX_PATH - 1) != 0) {
ret = WS_FATAL_ERROR;
}
}
if (ret == WS_SUCCESS) {
wolfSSH_Log(WS_LOG_INFO,
"[SSHD] Using directory %s for SFTP connection", r);
if (wolfSSH_SFTP_SetDefaultPath(ssh, r) != WS_SUCCESS) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Error setting SFTP default home path");
ret = WS_FATAL_ERROR;
}
}
/* impersonate the logged on user for file permissions */
if (ImpersonateLoggedOnUser(wolfSSHD_GetAuthToken(conn->auth)) == FALSE) {
wolfSSH_Log(WS_LOG_ERROR,
"[SSHD] Error impersonating logged on user");
ret = WS_FATAL_ERROR;
}
#endif
if (ret == WS_SUCCESS) {
sockfd = (WS_SOCKET_T)wolfSSH_get_fd(ssh);
do {
if (wolfSSH_SFTP_PendingSend(ssh)) {
/* Yes, process the SFTP data. */
ret = wolfSSH_SFTP_read(ssh);
error = wolfSSH_get_error(ssh);
timeout = (ret == WS_REKEYING) ?
TEST_SFTP_TIMEOUT : TEST_SFTP_TIMEOUT_NONE;
if (error == WS_WANT_READ || error == WS_WANT_WRITE ||
error == WS_CHAN_RXD || error == WS_REKEYING ||
error == WS_WINDOW_FULL)
ret = error;
if (error == WS_WANT_WRITE && wolfSSH_SFTP_PendingSend(ssh)) {
continue; /* no need to spend time attempting to pull data
* if there is still pending sends */
}
if (error == WS_EOF) {
/* An ordinary session end, not a failure. */
ret = 0;
break;
}
}
select_ret = tcp_select(sockfd, timeout);
if (select_ret == WS_SELECT_ERROR_READY) {
break;
}
if (ret == WS_WANT_READ || ret == WS_WANT_WRITE ||
select_ret == WS_SELECT_RECV_READY) {
ret = wolfSSH_worker(ssh, NULL);
error = wolfSSH_get_error(ssh);
if (ret == WS_REKEYING) {
/* In a rekey, keeping turning the crank. */
timeout = TEST_SFTP_TIMEOUT;
continue;
}
if (error == WS_WANT_READ || error == WS_WANT_WRITE ||
error == WS_WINDOW_FULL) {
timeout = TEST_SFTP_TIMEOUT;
ret = error;
continue;
}
/* Drain what is buffered first. A rekey is not a drained
* channel: peek reports it without looking. */
if (error == WS_EOF) {
int peekRet = wolfSSH_stream_peek(ssh, NULL, 1);
if (peekRet != WS_REKEYING && peekRet <= 0) {
/* An ordinary session end, not a failure. */
ret = 0;
break;
}
}
if (ret != WS_SUCCESS && ret != WS_CHAN_RXD
&& ret != WS_EOF) {
/* If not successful and no channel data, leave. */
break;
}
}
ret = wolfSSH_stream_peek(ssh, peek_buf, sizeof(peek_buf));
if (ret > 0) {
/* Yes, process the SFTP data. */
ret = wolfSSH_SFTP_read(ssh);
error = wolfSSH_get_error(ssh);
timeout = (ret == WS_REKEYING) ?
TEST_SFTP_TIMEOUT : TEST_SFTP_TIMEOUT_NONE;
if (error == WS_WANT_READ || error == WS_WANT_WRITE ||
error == WS_CHAN_RXD || error == WS_REKEYING ||
error == WS_WINDOW_FULL)
ret = error;
if (error == WS_EOF) {
/* An ordinary session end, not a failure. */
ret = 0;
break;
}
continue;
}
else if (ret == WS_REKEYING) {
timeout = TEST_SFTP_TIMEOUT;
continue;
}
else if (ret < 0) {
error = wolfSSH_get_error(ssh);
if (error == WS_EOF) {
/* An ordinary session end, not a failure. */
ret = 0;
break;
}
}
else {
/* Channel is live with nothing buffered. Let the next select
* block instead of polling at its 100 us floor. */
timeout = TEST_SFTP_TIMEOUT;
continue;
}
if (ret == WS_FATAL_ERROR && error == 0) {
WOLFSSH_CHANNEL* channel =
wolfSSH_ChannelNext(ssh, NULL);
if (channel && wolfSSH_ChannelGetEof(channel)) {
ret = 0;
break;
}