-
Notifications
You must be signed in to change notification settings - Fork 7
/
win-sftp-server.c
2701 lines (2354 loc) · 74 KB
/
win-sftp-server.c
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
/*
* Copyright (c) 1995 Tatu Ylonen <[email protected]>, Espoo, Finland.
* Copyright (c) 1999-2008 Markus Friedl. All rigths reserved.
* Copyright (c) 2001-2012 Damien Miller. All rigths reserved.
* Copyright (c) 2016 Qindel Formacion y Servicios SL. All rigths reserved.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#define _WIN32_WINNT 0x0600
#include <winsock2.h>
#include <windows.h>
#include <strsafe.h>
#include <aclapi.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <stdarg.h>
#include <stdint.h>
#include <wchar.h>
#include <ntdef.h>
#include <winbase.h>
#include <inttypes.h>
#include <time.h>
#define SSH2_FILEXFER_VERSION 3
#define SFTP_MAX_MSG_LENGTH (256 * 1024)
#define SSH2_FXP_INIT 1
#define SSH2_FXP_OPEN 3
#define SSH2_FXP_CLOSE 4
#define SSH2_FXP_READ 5
#define SSH2_FXP_WRITE 6
#define SSH2_FXP_LSTAT 7
#define SSH2_FXP_STAT_VERSION_0 7
#define SSH2_FXP_FSTAT 8
#define SSH2_FXP_SETSTAT 9
#define SSH2_FXP_FSETSTAT 10
#define SSH2_FXP_OPENDIR 11
#define SSH2_FXP_READDIR 12
#define SSH2_FXP_REMOVE 13
#define SSH2_FXP_MKDIR 14
#define SSH2_FXP_RMDIR 15
#define SSH2_FXP_REALPATH 16
#define SSH2_FXP_STAT 17
#define SSH2_FXP_RENAME 18
#define SSH2_FXP_READLINK 19
#define SSH2_FXP_SYMLINK 20
/* server to client */
#define SSH2_FXP_VERSION 2
#define SSH2_FXP_STATUS 101
#define SSH2_FXP_HANDLE 102
#define SSH2_FXP_DATA 103
#define SSH2_FXP_NAME 104
#define SSH2_FXP_ATTRS 105
#define SSH2_FXP_EXTENDED 200
#define SSH2_FXP_EXTENDED_REPLY 201
/* attributes */
#define SSH2_FILEXFER_ATTR_SIZE 0x00000001
#define SSH2_FILEXFER_ATTR_UIDGID 0x00000002
#define SSH2_FILEXFER_ATTR_PERMISSIONS 0x00000004
#define SSH2_FILEXFER_ATTR_ACMODTIME 0x00000008
#define SSH2_FILEXFER_ATTR_EXTENDED 0x80000000
/* portable open modes */
#define SSH2_FXF_READ 0x00000001
#define SSH2_FXF_WRITE 0x00000002
#define SSH2_FXF_APPEND 0x00000004
#define SSH2_FXF_CREAT 0x00000008
#define SSH2_FXF_TRUNC 0x00000010
#define SSH2_FXF_EXCL 0x00000020
/* status messages */
#define SSH2_FX_OK 0
#define SSH2_FX_EOF 1
#define SSH2_FX_NO_SUCH_FILE 2
#define SSH2_FX_PERMISSION_DENIED 3
#define SSH2_FX_FAILURE 4
#define SSH2_FX_BAD_MESSAGE 5
#define SSH2_FX_NO_CONNECTION 6
#define SSH2_FX_CONNECTION_LOST 7
#define SSH2_FX_OP_UNSUPPORTED 8
#define SSH2_FX_MAX 8
typedef unsigned int uint;
typedef struct {
uint32_t flags;
uint64_t size;
uint32_t uid;
uint32_t gid;
uint32_t perm;
uint32_t atime;
uint32_t mtime;
} Attrib;
#define SSHBUF_SIZE_MAX 0x8000000 /* Hard maximum size */
struct sshbuf {
uint8_t *d; /* Data */
size_t off; /* First available byte is buf->d + buf->off */
size_t size; /* Last byte is buf->d + buf->size - 1 */
size_t max_size; /* Maximum size of buffer */
size_t alloc; /* Total bytes allocated to buf->d */
};
static int debug_mode = 0;
static int list_system_files = 0;
static int list_hidden_files = 0;
static int delete_socket_file = 0;
/* input and output queue */
static struct sshbuf *iqueue;
static struct sshbuf *oqueue;
/* Version of client */
static uint version;
/* SSH2_FXP_INIT received */
static int init_done;
/* Disable writes */
static int readonly = 0;
static wchar_t *rootdir;
/* Portable attributes, etc. */
struct Stat {
wchar_t *name;
wchar_t *long_name;
Attrib attrib;
};
typedef struct Stat Stat;
/* Packet handlers */
static void process_open(uint32_t id);
static void process_close(uint32_t id);
static void process_read(uint32_t id);
static void process_write(uint32_t id);
static void process_stat(uint32_t id);
static void process_lstat(uint32_t id);
static void process_fstat(uint32_t id);
static void process_setstat(uint32_t id);
static void process_fsetstat(uint32_t id);
static void process_opendir(uint32_t id);
static void process_readdir(uint32_t id);
static void process_remove(uint32_t id);
static void process_mkdir(uint32_t id);
static void process_rmdir(uint32_t id);
static void process_realpath(uint32_t id);
static void process_rename(uint32_t id);
static void process_readlink(uint32_t id);
static void process_symlink(uint32_t id);
static void process_extended_posix_rename(uint32_t id);
static void process_extended_hardlink(uint32_t id);
static void process_extended_fsync(uint32_t id);
static void process_extended(uint32_t id);
struct sftp_handler {
const char *name; /* user-visible name for fine-grained perms */
const char *ext_name; /* extended request name */
uint type; /* packet type, for non extended packets */
void (*handler)(uint32_t);
int does_write; /* if nonzero, banned for readonly mode */
};
static struct sftp_handler handlers[] = {
/* NB. SSH2_FXP_OPEN does the readonly check in the handler itself */
{ "open", NULL, SSH2_FXP_OPEN, process_open, 0 },
{ "close", NULL, SSH2_FXP_CLOSE, process_close, 0 },
{ "read", NULL, SSH2_FXP_READ, process_read, 0 },
{ "write", NULL, SSH2_FXP_WRITE, process_write, 1 },
{ "lstat", NULL, SSH2_FXP_LSTAT, process_lstat, 0 },
{ "fstat", NULL, SSH2_FXP_FSTAT, process_fstat, 0 },
{ "setstat", NULL, SSH2_FXP_SETSTAT, process_setstat, 1 },
{ "fsetstat", NULL, SSH2_FXP_FSETSTAT, process_fsetstat, 1 },
{ "opendir", NULL, SSH2_FXP_OPENDIR, process_opendir, 0 },
{ "readdir", NULL, SSH2_FXP_READDIR, process_readdir, 0 },
{ "remove", NULL, SSH2_FXP_REMOVE, process_remove, 1 },
{ "mkdir", NULL, SSH2_FXP_MKDIR, process_mkdir, 1 },
{ "rmdir", NULL, SSH2_FXP_RMDIR, process_rmdir, 1 },
{ "realpath", NULL, SSH2_FXP_REALPATH, process_realpath, 0 },
{ "stat", NULL, SSH2_FXP_STAT, process_stat, 0 },
{ "rename", NULL, SSH2_FXP_RENAME, process_rename, 1 },
{ "readlink", NULL, SSH2_FXP_READLINK, process_readlink, 0 },
{ "symlink", NULL, SSH2_FXP_SYMLINK, process_symlink, 1 },
{ "extended", NULL, SSH2_FXP_EXTENDED, process_extended, 0 },
{ NULL, NULL, 0, NULL, 0 }
};
/* SSH2_FXP_EXTENDED submessages */
static struct sftp_handler extended_handlers[] = {
{ "posix-rename", "[email protected]", 0,
process_extended_posix_rename, 1 },
{ "hardlink", "[email protected]", 0, process_extended_hardlink, 1 },
{ "fsync", "[email protected]", 0, process_extended_fsync, 1 },
{ NULL, NULL, 0, NULL, 0 }
};
static FILE *log_fh = NULL;
static void fatal(const char *, ...) __attribute__((noreturn)) __attribute__((format(printf, 1, 2)));
static void debug(const char *fmt,...);
static void do_log(const char *fmt, va_list args);
static void cleanup_exit(int) __attribute__((noreturn));
#define MINIMUM(a, b) (((a) < (b)) ? (a) : (b))
#define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b))
#define HOWMANY(x, y) (((x)+((y)-1))/(y))
#define ROUNDUP(x, y) (HOWMANY(x, y) * (y))
//#define SIZE_MAX ((unsigned long)-1)
#define S_ISUID 2048
#define S_ISGID 1024
#define S_ISVTX 512
//#define S_IRGRP 32
//#define S_IWGRP 16
//#define S_IXGRP 8
//#define S_IROTH 4
//#define S_IWOTH 2
//#define S_IXOTH 1
#define tell_error(msg) debug("%s: %lu at %s", (msg), GetLastError(), __func__)
#define fatal_error(msg) fatal("%s: %lu at %s", (msg), GetLastError(), __func__)
#define MODELEN (11 + 1)
static void *
xmalloc(size_t size)
{
void *ptr;
if (size == 0)
fatal("xmalloc: zero size");
ptr = HeapAlloc(GetProcessHeap(), 0, size);
if (ptr == NULL)
fatal_error("HeapAlloc failed");
return ptr;
}
static void
xfree(void *ptr) {
DWORD last_error = GetLastError();
if (ptr && !HeapFree(GetProcessHeap(), 0, ptr))
fatal_error("HeapFree failed");
SetLastError(last_error);
}
static void *
xcalloc(size_t nmemb, size_t size)
{
void *ptr;
if (size == 0 || nmemb == 0)
fatal("xcalloc: zero size");
if (SIZE_MAX / nmemb < size)
fatal("xcalloc: nmemb * size > SIZE_MAX");
ptr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nmemb * size);
if (ptr == NULL)
fatal_error("HeapAlloc failed");
return ptr;
}
static void *
xcopy(void *data, size_t size) {
void *ptr = xmalloc(size);
memcpy(ptr, data, size);
return ptr;
}
#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
static void *
xmallocarray(size_t nmemb, size_t size)
{
if ((nmemb < MUL_NO_OVERFLOW && size < MUL_NO_OVERFLOW) ||
nmemb == 0 || SIZE_MAX / nmemb > size)
return xmalloc(size * nmemb);
fatal("xmallocarray: arguments out of limits, %" PRIu64 " elements of %" PRIu64 " bytes",
nmemb, size);
}
static wchar_t *
xwcsalloc(size_t nmemb) {
return xmallocarray(nmemb, sizeof(wchar_t));
}
static wchar_t *
xwcsdup(const wchar_t *wstr)
{
if (wstr == NULL) fatal("xwcsdup: NULL pointer");
size_t len = wcslen(wstr) + 1;
wchar_t *cp = xwcsalloc(len);
wmemcpy(cp, wstr, len);
return cp;
}
static void *
xrealloc(void *ptr, size_t size) {
void *new_ptr = (ptr
? HeapReAlloc(GetProcessHeap(), 0, ptr, size)
: HeapAlloc(GetProcessHeap(), 0, size));
if (new_ptr == NULL)
fatal_error("HeapReAlloc/HeapAlloc failed");
return new_ptr;
}
static void *
xreallocarray(void *ptr, size_t nmemb, size_t size)
{
if ((nmemb < MUL_NO_OVERFLOW && size < MUL_NO_OVERFLOW) ||
nmemb == 0 || SIZE_MAX / nmemb > size)
return xrealloc(ptr, size * nmemb);
fatal("xreallocarray: arguments out of limits, %" PRIu64 " elements of %" PRIu64 " bytes",
nmemb, size);
}
static wchar_t *
xwcscat(wchar_t *str, wchar_t *cat) {
size_t str_len = wcslen(str);
size_t cat_len = wcslen(cat);
wchar_t *cp = xwcsalloc(str_len + cat_len + 1);
wmemcpy(cp, str, str_len);
wmemcpy(cp + str_len, cat, cat_len + 1);
return cp;
}
static wchar_t *
xprintf(const wchar_t *fmt, ...) {
size_t max = 100;
wchar_t *line = NULL;
while (1) {
line = xreallocarray(line, max, sizeof(wchar_t));
va_list args;
va_start(args, fmt);
HRESULT rc = StringCchVPrintfW(line, max, fmt, args);
va_end(args);
switch (rc) {
case S_OK:
return line;
case STRSAFE_E_INVALID_PARAMETER:
fatal_error("StringCchVprintf failed");
}
max *= 2;
}
}
static void
open_log(const wchar_t *name) {
FILE *log_fh_1 = _wfopen(name, L"a");
if (log_fh_1) {
if (log_fh) fclose(log_fh);
log_fh = log_fh_1;
}
}
static void
do_log(const char *fmt, va_list args)
{
int saved_error = GetLastError();
FILE *fh = (log_fh ? log_fh : stderr);
time_t cur_time = time(NULL);
struct tm cur_tm = *localtime(&cur_time);
fprintf(fh, "[%02d/%02d/%02d %02d:%02d:%02d] ",
cur_tm.tm_year + 1900, cur_tm.tm_mon + 1, cur_tm.tm_mday,
cur_tm.tm_hour, cur_tm.tm_min, cur_tm.tm_sec);
fprintf(fh, "sftp-server: ");
vfprintf(fh, fmt, args);
fprintf(fh, "\n");
fflush(fh);
SetLastError(saved_error);
}
void
debug(const char *fmt,...)
{
if (debug_mode) {
va_list args;
va_start(args, fmt);
do_log(fmt, args);
va_end(args);
}
}
static void
fatal(const char *fmt,...)
{
if (debug_mode) {
va_list args;
va_start(args, fmt);
do_log(fmt, args);
va_end(args);
}
cleanup_exit(255);
}
#define PEEK_U64(p) \
(((uint64_t)(((const uint8_t *)(p))[0]) << 56) | \
((uint64_t)(((const uint8_t *)(p))[1]) << 48) | \
((uint64_t)(((const uint8_t *)(p))[2]) << 40) | \
((uint64_t)(((const uint8_t *)(p))[3]) << 32) | \
((uint64_t)(((const uint8_t *)(p))[4]) << 24) | \
((uint64_t)(((const uint8_t *)(p))[5]) << 16) | \
((uint64_t)(((const uint8_t *)(p))[6]) << 8) | \
(uint64_t)(((const uint8_t *)(p))[7]))
#define PEEK_U32(p) \
(((uint32_t)(((const uint8_t *)(p))[0]) << 24) | \
((uint32_t)(((const uint8_t *)(p))[1]) << 16) | \
((uint32_t)(((const uint8_t *)(p))[2]) << 8) | \
(uint32_t)(((const uint8_t *)(p))[3]))
#define PEEK_U16(p) \
(((uint16_t)(((const uint8_t *)(p))[0]) << 8) | \
(uint16_t)(((const uint8_t *)(p))[1]))
#define POKE_U64(p, v) \
do { \
const uint64_t __v = (v); \
((uint8_t *)(p))[0] = (__v >> 56) & 0xff; \
((uint8_t *)(p))[1] = (__v >> 48) & 0xff; \
((uint8_t *)(p))[2] = (__v >> 40) & 0xff; \
((uint8_t *)(p))[3] = (__v >> 32) & 0xff; \
((uint8_t *)(p))[4] = (__v >> 24) & 0xff; \
((uint8_t *)(p))[5] = (__v >> 16) & 0xff; \
((uint8_t *)(p))[6] = (__v >> 8) & 0xff; \
((uint8_t *)(p))[7] = __v & 0xff; \
} while (0)
#define POKE_U32(p, v) \
do { \
const uint32_t __v = (v); \
((uint8_t *)(p))[0] = (__v >> 24) & 0xff; \
((uint8_t *)(p))[1] = (__v >> 16) & 0xff; \
((uint8_t *)(p))[2] = (__v >> 8) & 0xff; \
((uint8_t *)(p))[3] = __v & 0xff; \
} while (0)
#define POKE_U16(p, v) \
do { \
const uint16_t __v = (v); \
((uint8_t *)(p))[0] = (__v >> 8) & 0xff; \
((uint8_t *)(p))[1] = __v & 0xff; \
} while (0)
static uint32_t
get_u32(const void *vp)
{
const uint8_t *p = (const uint8_t *)vp;
uint32_t v;
v = (uint32_t)p[0] << 24;
v |= (uint32_t)p[1] << 16;
v |= (uint32_t)p[2] << 8;
v |= (uint32_t)p[3];
return (v);
}
static void
put_u32(void *vp, uint32_t v)
{
uint8_t *p = (uint8_t *)vp;
p[0] = (uint8_t)(v >> 24) & 0xff;
p[1] = (uint8_t)(v >> 16) & 0xff;
p[2] = (uint8_t)(v >> 8) & 0xff;
p[3] = (uint8_t)v & 0xff;
}
void
sshbuf_assert_sanity(const struct sshbuf *buf)
{
if (buf == NULL ||
buf->d == NULL ||
buf->max_size > SSHBUF_SIZE_MAX ||
buf->alloc > buf->max_size ||
buf->size > buf->alloc ||
buf->off > buf->size) {
/* Do not try to recover from corrupted buffer internals */
fatal("Internal error: corrupted buffer at %p", buf);
}
}
#define SSHBUF_SIZE_INIT 256 /* Initial allocation */
#define SSHBUF_SIZE_INC 256 /* Preferred increment length */
#define SSHBUF_PACK_MIN 8192 /* Minimim packable offset */
static struct sshbuf *
sshbuf_new(void)
{
struct sshbuf *ret;
ret = xcalloc(sizeof(*ret), 1);
ret->alloc = SSHBUF_SIZE_INIT;
ret->max_size = SSHBUF_SIZE_MAX;
ret->d = xcalloc(1, ret->alloc);
return ret;
}
static void
sshbuf_free(struct sshbuf *buf)
{
if (buf == NULL)
return;
/*
* The following will leak on insane buffers, but this is the safest
* course of action - an invalid pointer or already-freed pointer may
* have been passed to us and continuing to scribble over memory would
* be bad.
*/
sshbuf_assert_sanity(buf);
/*
* If we are a parent with still-extant children, then don't free just
* yet. The last child's call to sshbuf_free should decrement our
* refcount to 0 and trigger the actual free.
*/
memset(buf, 0, sizeof(*buf));
xfree(buf);
}
static size_t
sshbuf_len(const struct sshbuf *buf)
{
sshbuf_assert_sanity(buf);
return buf->size - buf->off;
}
static const uint8_t *
sshbuf_ptr(const struct sshbuf *buf)
{
sshbuf_assert_sanity(buf);
return buf->d + buf->off;
}
static int
sshbuf_check_reserve(const struct sshbuf *buf, size_t len)
{
sshbuf_assert_sanity(buf);
/* Check that len is reasonable and that max_size + available < len */
if (len <= buf->max_size && buf->max_size - len >= buf->size - buf->off)
return 1;
debug("no space in buffer!");
return 0;
}
static void
sshbuf_maybe_pack(struct sshbuf *buf, int force)
{
if (buf->off == 0)
return;
if (force ||
(buf->off >= SSHBUF_PACK_MIN && buf->off >= buf->size / 2)) {
memmove(buf->d, buf->d + buf->off, buf->size - buf->off);
buf->size -= buf->off;
buf->off = 0;
}
}
static int
sshbuf_reserve(struct sshbuf *buf, size_t len, uint8_t **dpp)
{
if (dpp != NULL)
*dpp = NULL;
if (!sshbuf_check_reserve(buf, len))
return 0;
/*
* If the requested allocation appended would push us past max_size
* then pack the buffer, zeroing buf->off.
*/
sshbuf_maybe_pack(buf, buf->size + len > buf->max_size);
if (len + buf->size > buf->alloc) {
/*
* Prefer to alloc in SSHBUF_SIZE_INC units, but
* allocate less if doing so would overflow max_size.
*/
size_t need = len + buf->size - buf->alloc;
size_t rlen = ROUNDUP(buf->alloc + need, SSHBUF_SIZE_INC);
if (rlen > buf->max_size)
rlen = buf->alloc + need;
buf->d = xrealloc(buf->d, rlen);
buf->alloc = rlen;
if (!sshbuf_check_reserve(buf, len))
fatal("internal error: reallocated buffer is too small! should never happen!!!");
}
if (dpp != NULL)
*dpp = buf->d + buf->size;
buf->size += len;
return 1;
}
static int
sshbuf_consume(struct sshbuf *buf, size_t len)
{
sshbuf_assert_sanity(buf);
if (len > sshbuf_len(buf)) {
SetLastError(ERROR_INVALID_DATA);
debug("not enough data in buffer for consume %d", len);
return 0;
}
buf->off += len;
return 1;
}
static int
sshbuf_peek_string_direct(const struct sshbuf *buf, const uint8_t **valp,
size_t *lenp)
{
if (valp) *valp = NULL;
if (lenp) *lenp = 0;
if (sshbuf_len(buf) < 4) {
debug("sshbuf: message incomplete, len: %d", sshbuf_len(buf));
SetLastError(ERROR_INVALID_DATA);
return 0;
}
const uint8_t *p = sshbuf_ptr(buf);
uint32_t len = PEEK_U32(p);
if (len > SSHBUF_SIZE_MAX - 4) {
debug("sshbuf: string too large, len: %d", len);
SetLastError(ERROR_INVALID_DATA);
return 0;
}
if (sshbuf_len(buf) - 4 < len) {
debug("sshbuf: message incomplete, len: %d, buffer len: %d", len, sshbuf_len(buf));
SetLastError(ERROR_INVALID_DATA);
return 0;
}
if (valp) *valp = p + 4;
if (lenp) *lenp = len;
return 1;
}
#define sshbuf_skip_string(buf) sshbuf_get_string_direct(buf, NULL, NULL)
static int
sshbuf_get_string_direct(struct sshbuf *buf, const uint8_t **valp, size_t *lenp)
{
size_t len;
const uint8_t *p;
if (sshbuf_peek_string_direct(buf, &p, &len)) {
if (sshbuf_consume(buf, len + 4)) {
if (valp) *valp = p;
if (lenp) *lenp = len;
return 1;
}
fatal("sshbuf: internal error, sshbuf_consume failed");
}
if (valp) *valp = NULL;
if (lenp) *lenp = 0;
return 0;
}
static int
sshbuf_get_string(struct sshbuf *buf, uint8_t **valp, size_t *lenp)
{
const uint8_t *val;
size_t len;
if (sshbuf_get_string_direct(buf, &val, &len)) {
if (valp) {
*valp = xmalloc(len + 1);
if (len) memcpy(*valp, val, len);
(*valp)[len] = '\0';
}
if (lenp) *lenp = len;
return 1;
}
if (valp) *valp = NULL;
if (lenp) *lenp = 0;
return 0;
}
static int
sshbuf_get_cstring(struct sshbuf *buf, char **valp) {
size_t len;
const uint8_t *p;
if (sshbuf_peek_string_direct(buf, &p, &len)) {
if (len == 0 || !memchr(p , '\0', len - 1)) {
if (sshbuf_skip_string(buf)) {
*valp = xmalloc(len + 1);
memcpy(*valp, p, len);
(*valp)[len] = '\0';
return 1;
}
}
}
*valp = NULL;
return 0;
}
static int
sshbuf_get_path(struct sshbuf *buf, wchar_t **valp, int append_bar)
{
append_bar = (append_bar ? 1 : 0);
*valp = NULL;
size_t len;
const uint8_t *p;
if (!sshbuf_peek_string_direct(buf, &p, &len) ||
!sshbuf_skip_string(buf))
return 0;
static const uint8_t forbidden_path_chr[] = "<>:\"|?*";
static const uint8_t current_dir[] = ".";
if (len == 0) {
debug("zero length path given, taken as '.'");
p = current_dir;
len = 1;
}
else {
if (len >= 2 && p[0] == '\\' && p[1] == '\\') {
debug("sshbud_get_path failed, \\\\... paths are forbidden");
SetLastError(ERROR_BAD_PATHNAME);
return 0;
}
debug("path before cleanup: >>%*s<< (len: %ld)", (int)len, p, len);
/* convert '/' to '\\' and colapse multiple bars into one. */
int i, bars;
uint8_t *wp = (uint8_t *)p;
for (bars = i = 0; i < len; i++) {
uint8_t c = p[i];
if (c == '/' || c == '\\') {
if (bars++) continue;
c = '\\';
}
else
bars = 0;
*wp++ = c;
}
len = wp - p;
debug("path after cleanup: >>%*s<< (len: %ld)", (int)len, p, len);
int skip_vol = 0;
if (len >= 2 && isalpha(p[0]) && p[1] == ':') {
if (len == 2 || p[2] != '\\') {
/* TODO: use GetFullPathName() to resolve the path */
if (p[0] != rootdir[0]) {
debug("sshbuf_get_path (%*s) failed, relative paths after a volume name are fobidden",
len, p);
SetLastError(ERROR_BAD_PATHNAME);
return 0;
}
}
skip_vol = 2;
}
for (i = skip_vol; i < len; i++) {
if (memchr(forbidden_path_chr, p[i], sizeof(forbidden_path_chr))) {
debug("sshbuf_get_path failed, character %c (0x%2x) is forbidden in path names", p[i], p[i]);
SetLastError(ERROR_BAD_PATHNAME);
return 0;
}
}
/* remove trailing '/' characters except when it is
the first character */
for (i = len; --i > skip_vol;) {
if (p[i] != '\\') break;
len--;
}
if (p[i] == '\\') append_bar = 0;
if (len == skip_vol) {
p = (unsigned char*)".";
len = 1;
}
}
int wlen = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
(const char *)p, len, NULL, 0);
if (!wlen) {
tell_error("MultiByteToWideChar failed");
return 0;
}
*valp = xwcsalloc(wlen + append_bar + 1);
if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
(const char *)p, len, *valp, wlen) == wlen) {
if (append_bar) {
(*valp)[wlen] = '\\';
(*valp)[wlen + 1] = 0;
}
else
(*valp)[wlen] = 0;
return 1;
}
else {
tell_error("MultibyteToWideChar failed");
xfree(*valp);
*valp = NULL;
return 0;
}
}
static int
sshbuf_get_two_paths(struct sshbuf *buf, wchar_t **path1, wchar_t **path2) {
if (sshbuf_get_path(buf, path1, 0)) {
if (sshbuf_get_path(buf, path2, 0))
return 1;
xfree(*path1);
}
*path1 = NULL;
*path2 = NULL;
return 0;
}
static int
sshbuf_get_u64(struct sshbuf *buf, uint64_t *valp)
{
const uint8_t *p = sshbuf_ptr(buf);
if (sshbuf_consume(buf, 8)) {
if (valp) *valp = PEEK_U64(p);
return 1;
}
return 0;
}
static int
sshbuf_get_u32(struct sshbuf *buf, uint32_t *valp)
{
const uint8_t *p = sshbuf_ptr(buf);
if (sshbuf_consume(buf, 4)) {
if (valp) *valp = PEEK_U32(p);
return 1;
}
return 0;
}
static int
sshbuf_get_u8(struct sshbuf *buf, uint8_t *valp)
{
const uint8_t *p = sshbuf_ptr(buf);
if (sshbuf_consume(buf, 1)) {
if (valp) *valp = (uint8_t)*p;
return 1;
}
return 0;
}
static int
sshbuf_put_u64(struct sshbuf *buf, uint64_t val)
{
uint8_t *p;
if (sshbuf_reserve(buf, 8, &p)) {
POKE_U64(p, val);
return 1;
}
return 0;
}
static int
sshbuf_put_u32(struct sshbuf *buf, uint32_t val)
{
uint8_t *p;
if (sshbuf_reserve(buf, 4, &p)) {
POKE_U32(p, val);
return 1;
}
return 0;
}
static int
sshbuf_put_u8(struct sshbuf *buf, uint8_t val)
{
uint8_t *p;
if (sshbuf_reserve(buf, 1, &p)) {
p[0] = val;
return 1;
}
return 0;
}
static int
sshbuf_put_string(struct sshbuf *buf, const void *v, size_t len)
{
if (len > SSHBUF_SIZE_MAX - 4)
fatal("no space left in buffer");
uint8_t *d;
if (sshbuf_reserve(buf, len + 4, &d)) {
POKE_U32(d, len);
if (len) memcpy(d + 4, v, len);
return 1;
}
return 0;
}
#ifndef WC_ERR_INVALID_CHARS
#define WC_ERR_INVALID_CHARS 0x80
#endif
static int
sshbuf_put_wcs(struct sshbuf *buf, const wchar_t *v, size_t wlen)
{
if (!wlen) return sshbuf_put_string(buf, "", 0);
size_t alen = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, v, wlen,
NULL, 0, NULL, NULL);
if (alen) {
uint8_t *d;
if ((alen <= SSHBUF_SIZE_MAX - 4) &&
sshbuf_reserve(buf, alen + 4, &d)) {
POKE_U32(d, alen);
if (WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, v, wlen,
(char *)d + 4, alen, NULL, NULL) == alen)
return 1;
tell_error("WideCharToMultiByte failed (2)");
}
else debug("buffer is to slow, wlen: %ld, alen: %ld", wlen, alen);
}
else tell_error("WideCharToMultiByte failed (1)");
return 0;
}
static int
sshbuf_put_cstring(struct sshbuf *buf, const char *v)
{
return sshbuf_put_string(buf, (uint8_t *)v, v == NULL ? 0 : strlen(v));
}
static int
sshbuf_put_path(struct sshbuf *buf, const wchar_t *v)
{
return sshbuf_put_wcs(buf, v, v == NULL ? 0 : wcslen(v));
}
static int
sshbuf_put_stringb(struct sshbuf *buf, const struct sshbuf *v)
{
return sshbuf_put_string(buf, sshbuf_ptr(v), sshbuf_len(v));
}
static int
sshbuf_put(struct sshbuf *buf, const void *v, size_t len)
{
uint8_t *p;
if (sshbuf_reserve(buf, len, &p)) {
if (len) memcpy(p, v, len);
return 1;
}
return 0;
}
static void
sshbuf_reset(struct sshbuf *buf)
{
sshbuf_assert_sanity(buf);
memset(buf->d, 0, buf->alloc);
buf->off = buf->size = 0;
if (buf->alloc != SSHBUF_SIZE_INIT) {
buf->d = xrealloc(buf->d, SSHBUF_SIZE_INIT);
buf->alloc = SSHBUF_SIZE_INIT;
}
}
static int
win_error_to_portable(int win_error) {
switch (win_error) {
case ERROR_SUCCESS:
return SSH2_FX_OK;