/
chressh.c
1446 lines (1352 loc) · 43.3 KB
/
chressh.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
/* chressh.c
* restricted (non-)login shell to allow (non-shell) users to run commands --
* such as scp, sftp-server, rsync, and unison -- over a secure channel.
* chroot()s a user to homedir, or, optionally, to shared directory above it,
* before starting target command.
* (further information in Notes section located at the bottom of this file)
*
*
* Copyright (c) 2003 Glue Logic LLC All rights reserved code()gluelogic.com
*
* This program 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 2
* of the License, or (at your option) any later version.
*
* This program 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 this program; if not, write to the
* Free Software Foundation, Inc.
* 59 Temple Place - Suite 330
* Boston, MA 02111-1307, USA
*
* Full text of the GNU General Public License may be found at:
* http://www.gnu.org/copyleft/gpl.html
*/
/*
* CONFIGURATION BEGIN
*/
/* user's shell in passwd database MUST match this hard-coded path
* (this is for the same reason that the system allows only root to chroot())
*/
#ifndef CHROOTING_SHELL
#define CHROOTING_SHELL "/usr/local/sbin/chressh"
#endif
/* chrooted path (relative to starting dir (homedir)) to directory containing
* allowed (and secured) programs. It must end in '/'. (use "./" for root)
*/
#ifndef CHROOTED_CMD_DIR
#define CHROOTED_CMD_DIR ".chressh/bin/"
#endif
/* chroot dir instead of homedir when user is a member of multiple groups
* (user's homedir must be beneath this directory or else this is not used)
* (This program will chroot to homedir if user is member of only one group)
* (Include the trailing slash for a full directory path segment prefix match.
* While the GROUP_CHROOT_DIR then will not match if homedir is identical to
* GROUP_CHROOT_DIR (without a trailing slash), the results will be the same:
* chroot()ing to the homedir (which is the same dir as GROUP_CHROOT_DIR))
*/
#ifndef GROUP_CHROOT_DIR
#define GROUP_CHROOT_DIR "/nonexistent/" /* set to bogus dir to disable */
/* #define GROUP_CHROOT_DIR "/pub/" */
#endif
/* umask default */
#ifndef UMASK
#define UMASK 0022
/* #define UMASK 0002 */ /* useful in environments based around groups */
#endif
/* path to 'passwd' (or equivalent) command */
#ifndef PASSWD_PROGRAM
#define PASSWD_PROGRAM "/usr/bin/passwd"
#endif
/* #undef PASSWD_PROGRAM */ /* undefine PASSWD_PROGRAM to disable */
/* system priority and resource limits */
#define CHRESSH_PRIO 15 /* lower priority to 15 */
#define CHRESSH_STACK 16777216L /* arbitrarily 16MiB stack size */
#define CHRESSH_DATA 33554432L /* arbitrarily 32MiB memory size */
/* define to a value of 1 as appropriate if system has <wordexp.h> or <glob.h>
* The reason this is not autoconf'ed is that on some systems, wordexp() forks
* a subshell to do its expansion, and that will fail in our restricted chroot.
* On those systems, leave #define HAVE_WORDEXP_H 0.
*/
#define HAVE_WORDEXP_H 1
#define HAVE_GLOB_H 0
/*
* CONFIGURATION END
*/
#include <errno.h>
#include <limits.h>
#include <pwd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <syslog.h>
#include <unistd.h>
extern char **environ;
#if HAVE_WORDEXP_H
#include <wordexp.h>
#endif
#if HAVE_GLOB_H
#include <glob.h>
#endif
/* minimum number of processes each target requires to run */
#define NPROC_RSYNC 3
#define NPROC_SCP 1
#define NPROC_SFTP_SERVER 1
#define NPROC_UNISON 1
/* informative message to return if a system call failed */
#define SYSTEM_ERROR_MESG \
"\n\tA system error occurred while attempting to execute your command.\n" \
"\n\tPlease contact the systems administrator for further assistance.\n\n"
/* informative message to return if login attempt is made */
#define NOLOGIN_MESG \
"\n\tYou do not have interactive login access to this machine.\n" \
"\n\tPlease contact the systems administrator for further assistance.\n\n"
/* informative message to return if a this program is not user's shell */
#define SHELL_MISMATCH_MESG \
"\n\tYou are not permitted to call this program.\n" \
"\n\tPlease contact the systems administrator for further assistance.\n\n"
/* informative message to return if run as root */
#define ROOT_RUID_MESG \
"\n\treal UID (target UID) of root is not allowed\n\n"
/* informative message to return if invalid args passed */
#define BAD_ARGS_MESG \
"\n\tInvalid arguments; command not allowed.\n" \
"\n\tPlease contact the systems administrator for further assistance.\n\n"
static void __attribute__((noreturn))
fatal(const int argc,
/*@null@*/ const struct passwd * const pw,
/*@null@*/ const char * const chroot_dir)
/*@globals errno@*/
/*@modifies errno@*/
{
const int s_errno = errno;
const char *mesg = NULL;
openlog("chressh", LOG_PID, LOG_AUTHPRIV);
if (s_errno) {
syslog (LOG_NOTICE, "system error occurred for uid %lu (%s) (%s)",
(unsigned long) (pw ? pw->pw_uid : getuid()),
pw ? pw->pw_name : "", strerror(s_errno));
mesg = SYSTEM_ERROR_MESG;
}
else if (NULL == pw) {
syslog (LOG_NOTICE, "login attempted by invalid uid %lu",
(unsigned long) getuid());
mesg = NOLOGIN_MESG;
}
else if (0 == pw->pw_uid) {
syslog (LOG_NOTICE, "real UID (target UID) of root is not allowed");
mesg = ROOT_RUID_MESG;
}
else if (0 != memcmp(pw->pw_shell,CHROOTING_SHELL,sizeof(CHROOTING_SHELL))){
syslog (LOG_NOTICE, "shell mismatch by uid %lu (%s)",
(unsigned long) pw->pw_uid, pw->pw_name);
mesg = SHELL_MISMATCH_MESG;
}
else if (NULL != chroot_dir) {
syslog (LOG_NOTICE, "unsafe ownership or permissions on chroot (%s)"
"for uid %lu (%s)", chroot_dir, (unsigned long) pw->pw_uid,
pw->pw_name);
mesg = SYSTEM_ERROR_MESG;
}
else if (1 == argc) {
syslog (LOG_NOTICE, "login attempted by uid %lu (%s)",
(unsigned long) pw->pw_uid, pw->pw_name);
mesg = NOLOGIN_MESG;
}
else {
syslog (LOG_NOTICE, "bad args passed by uid %lu (%s)",
(unsigned long) pw->pw_uid, pw->pw_name);
mesg = BAD_ARGS_MESG;
}
(void) sleep(3);
if (NULL != mesg) {
(void) write(STDERR_FILENO, mesg, strlen(mesg));
}
exit(s_errno ? s_errno : 1);
}
/* Perl script used to generate hash_long_args[] from lists below
#!/usr/bin/perl -Tw
use constant HASH_SIZE => 32;
my @hash;
my $val;
$hash[$_] = [] foreach (0..HASH_SIZE);
foreach my $arg (<>) {
chomp $arg;
$val = 0;
map { $val = ($val + ord($_)) % HASH_SIZE } split //,$arg;
push @{$hash[$val]},$arg;
}
my $list = " {\n";
foreach (@hash) {
$list .=
scalar @$_
? (' { "' . join('", "', @$_) . "\", NULL },\n")
: " { NULL },\n";
}
substr($list,-2,2,"\n }\n");
print $list;
*/
/* rsync
* Disallow "--daemon" "--no-detach" "--address" "--port" "--config"
* "--devices" "--owner" "--rsh=COMMAND" "--rsync-path=PATH" along with "-e"
*
* Allowed rsync long args with required param
*
suffix
block-size
max-delete
timeout
modify-window
temp-dir
compare-dest
link-dest
exclude
exclude-from
include
include-from
files-from
log-format
password-file
bwlimit
write-batch
read-batch
*
* Allowed rsync long args with no param
*
server
sender
verbose
quiet
checksum
archive
recurse
relative
no-relative
no-implied-dirs
backup
backup-dir
update
links
copy-links
copy-unsafe-links
safe-links
hard-links
perms
owner
group
devices
times
sparse
dry-run
whole-file
no-whole-file
one-file-system
existing
ignore-existing
delete
delete-excluded
delete-after
ignore-errors
partial
force
numeric-ids
ignore-times
size-only
compress
cvs-exclude
from0
version
blocking-io
no-blocking-io
stats
progress
help
*/
/* unison
* Disallow "-socket" "-server" "-servercmd" "-rshcmd" "-rshargs" "-editor"
* "-diff" "-merge" "-merge2" "-owner" "-sshcmd" "-sshversion"
*
* Allowed unison "long" args with required param
*
addprefsto
backup
debug
doc
fastcheck
follow
force
height
ignore
ignorenot
key
label
logfile
maxbackups
path
perms
prefer
root
rootalias
sortfirst
sortlast
statusdepth
ui
*
* Allowed unison "long" args with no param
*
addversionno
auto
backups
batch
contactquietly
dumbtty
group
help
ignorecase
killserver
log
numericids
silent
sortbysize
sortnewfirst
terse
testserver
times
version
xferbycopying
*/
/* hard-code allowed args and reject others (default deny, not default allow) */
#define HASH_SIZE (1<<5) /* 1<<5 == 32; must be a power of 2 */
enum { HASH_RSYNC_A=0, HASH_RSYNC_B=1, HASH_UNISON_A=2, HASH_UNISON_B=3 };
static const char *hash_long_args[4][HASH_SIZE+1][8] =
{
{ /* rsync (with param) */
{ "password-file", NULL },
{ NULL },
{ "temp-dir", NULL },
{ NULL },
{ "compare-dest", "include", NULL },
{ "include-from", NULL },
{ "max-delete", NULL },
{ "timeout", NULL },
{ NULL },
{ NULL },
{ "exclude", NULL },
{ "link-dest", "exclude-from", "read-batch", NULL },
{ NULL },
{ "modify-window", NULL },
{ NULL },
{ NULL },
{ NULL },
{ NULL },
{ NULL },
{ "block-size", NULL },
{ "files-from", NULL },
{ "suffix", NULL },
{ NULL },
{ NULL },
{ "log-format", "bwlimit", NULL },
{ NULL },
{ "write-batch", NULL },
{ NULL },
{ NULL },
{ NULL },
{ NULL },
{ NULL },
{ NULL }
},
{ /* rsync (no param) */
{ "numeric-ids", NULL },
{ "sender", "links", "one-file-system", NULL },
{ "archive", "backup-dir", "times", NULL },
{ "update", "devices", "cvs-exclude", NULL },
{ "from0", NULL },
{ NULL },
{ "no-relative", "version", NULL },
{ "perms", NULL },
{ "quiet", NULL },
{ "copy-links", "help", NULL },
{ "size-only", NULL },
{ "owner", "existing", NULL },
{ "whole-file", "compress", NULL },
{ "no-implied-dirs", "safe-links", "hard-links", "group", "partial",NULL},
{ "sparse", "delete-excluded", "ignore-errors", "blocking-io", NULL },
{ "force", "stats", NULL },
{ NULL },
{ "dry-run", NULL },
{ "delete-after", NULL },
{ "checksum", "delete", "ignore-times", NULL },
{ NULL },
{ "progress", NULL },
{ "verbose", "backup", "no-whole-file", NULL },
{ "server", NULL },
{ "copy-unsafe-links", "no-blocking-io", NULL },
{ "recurse", NULL },
{ NULL },
{ NULL },
{ "relative", "ignore-existing", NULL },
{ NULL },
{ NULL },
{ NULL },
{ NULL }
},
{ /* unison (with param) */
{ "label", NULL },
{ NULL },
{ "logfile", NULL },
{ NULL },
{ "ignore", "prefer", "root", NULL },
{ NULL },
{ NULL },
{ "debug", "perms", NULL },
{ NULL },
{ "key", NULL },
{ NULL },
{ NULL },
{ "addprefsto", "fastcheck", NULL },
{ "path", NULL },
{ "rootalias", NULL },
{ "force", "maxbackups", NULL },
{ "sortfirst", NULL },
{ NULL },
{ NULL },
{ "follow", NULL },
{ NULL },
{ "ignorenot", NULL },
{ "backup", "doc", NULL },
{ NULL },
{ NULL },
{ "height", "statusdepth", NULL },
{ NULL },
{ NULL },
{ "sortlast", NULL },
{ NULL },
{ "ui", NULL },
{ NULL },
{ NULL }
},
{ /* unison (no param) */
{ "ignorecase", NULL },
{ NULL },
{ "batch", "log", "times", NULL },
{ "killserver", "terse", NULL },
{ NULL },
{ NULL },
{ "version", NULL },
{ NULL },
{ NULL },
{ "backups", "dumbtty", "help", "xferbycopying", NULL },
{ NULL },
{ NULL },
{ "addversionno", NULL },
{ "group", NULL },
{ NULL },
{ "silent", NULL },
{ NULL },
{ NULL },
{ NULL },
{ "numericids", NULL },
{ NULL },
{ NULL },
{ NULL },
{ "testserver", NULL },
{ NULL },
{ "auto", "contactquietly", NULL },
{ "sortnewfirst", NULL },
{ NULL },
{ NULL },
{ NULL },
{ "sortbysize", NULL },
{ NULL },
{ NULL }
}
};
static int
hash_lookup_long_arg(const int hash_e, const char * const str)
/*@globals hash_rsync, hash_unison_a, hash_unison_b@*/
/*@modifies nothing@*/
{
const char * const *h;
const char c = *str;
unsigned char * const s = (unsigned char *) str;
unsigned char *p;
const size_t len = (NULL == (p=strchr(s,'='))) ? strlen(s) : (size_t)(p-s);
size_t i;
int val = 0;
for (i = 0; i < len; i++)
val = (val + s[i]) & (HASH_SIZE-1);
h = hash_long_args[hash_e][val];
for (i = 0; NULL != h[i] && (c != *h[i] || 0 != memcmp(h[i],str,len)); i++)
;
return (NULL != h[i]);
}
static int
filter_args_rsync(char ** const argv)
/*@modifies nothing@*/
{
char *s;
unsigned int require_param = 0;
size_t i = 0;
size_t j = 0;
while (NULL != (s = argv[i++])) {
if (1 == require_param || '-' != s[0]) {
require_param = 0;
}
else if ('-' != s[1]) {
for (j = 1; s[j] != '\0'; j++) { /* (implicity allows "-" arg) */
/* "-e" disallowed */
if ('B' == s[j] || 'T' == s[1]) {
require_param = 1;
if ('\0' != s[j+1]) {
return -1; /* bad combination of args */
}
}
else if (NULL == strchr("046CDHILPRSWabcghlnopqrtuvxz", s[j])) {
/* long args beginning with single '-' are rejected
* here even though they are supported by popt,
* which is employed by rsync to parse its args
*/
return -1; /* disallowed or unknown */
}
}
}
else if ('\0' == s[2]) { /* "--" indicates end of args */
return 0;
}
else if (0 != hash_lookup_long_arg(HASH_RSYNC_A, s+2)) {
if (NULL == strchr(s+2, '=')) {
require_param = 1;
}
}
else if (0 == hash_lookup_long_arg(HASH_RSYNC_B, s+2)) {
return -1; /* disallowed or unknown */
}
}
return (0 == require_param) ? 0 : -1;
}
static int
filter_args_unison(char ** const argv)
/*@modifies nothing@*/
{
char *s;
unsigned int require_param = 0;
size_t i = 0;
/* Check the number of non-options because unison profiles are
* not allowed (they can be used to execute arbitrary programs).
* Usage: unison [options] (1 non-option)
* or unison root1 root2 [options] (3 non-options)
* or unison profilename [options] (disallowed)
* (also unison profilename root1 root2 [options]) (disallowed)
* (MUST TEST HOW UNISON HANDLES "-" AS PROFILENAME OR ROOT)
* (and if it handles "--")
*/
while (NULL != argv[i] && ('-' != argv[i][0] || '\0' == argv[i][1])) {
i++;
}
if (1 != i && 3 != i) {
return -1; /* unison profiles disallowed */
}
while (NULL != (s = argv[i++])) {
if (1 == require_param) {
require_param = 0;
}
else if ('-' != s[0]) {
return -1; /* disallowed or unknown */
}
else if (0 != hash_lookup_long_arg(HASH_UNISON_A, s+1)) {
require_param = 1;
}
else if (0 == hash_lookup_long_arg(HASH_UNISON_B, s+1)) {
return -1; /* disallowed or unknown */
}
}
return (0 == require_param) ? 0 : -1;
}
#if !HAVE_WORDEXP_H
/* This routine is quite simpleton. It performs very loose syntax checking,
* and treats newlines as spaces. It supports only brain-dead limited quoting
* (no quoting within words), and provides absolutely no support for escaping.
*/
/*@null@*/
static char **
simpleton_wordsplit(char *args)
/*@globals errno@*/
/*@modifies errno@*/
{
int i = -1;
const int max = 31; /*(arbitrarily limit to command + 30 args + NULL)*/
char ** const argv = malloc((max + 1) * sizeof(char *));
if (NULL == argv) {
return NULL;
}
while ('\0' != *args && i < max) {
switch (*args) {
case ' ' :
case '\t':
case '\n':*args++;
continue;
case '"': argv[++i] = ++args;
args = strchr(args, '"');
break;
case '\'':argv[++i] = ++args;
args = strchr(args, '\'');
break;
default: argv[++i] = args++;
args += strcspn(args, " \t\n");
if ('\0' != *args) {
*args++ = '\0';
}
continue;
}
/* (limited to supporting quotes around entire word) */
if (NULL != args) {
*args++ = '\0';
}
else {
return (free(argv), NULL);
}
}
return (i < max || '\0'==*args) ? (argv[i+1]=NULL,argv) : (free(argv),NULL);
}
#endif /* !HAVE_WORDEXP_H */
#if !HAVE_WORDEXP_H && HAVE_GLOB_H
#include <stdio.h>
static int
glob_errfunc(const char *epath, int eerrno)
{
(void) fprintf(stderr, "\nglob() error (%s) for path:\n%s\n",
strerror(eerrno), epath);
return 1; /* (anything non-zero) */
}
#endif /* !HAVE_WORDEXP_H && HAVE_GLOB_H */
/*@null@*/
static char **
shell_parse(char * const args)
/*@globals errno@*/
/*@modifies errno@*/
{
char **argv;
#if HAVE_WORDEXP_H || HAVE_GLOB_H
int rv;
struct rlimit limits;
rlim_t soft_limit;
#ifdef RLIMIT_AS
rv = getrlimit(RLIMIT_AS, &limits);
#else
rv = getrlimit(RLIMIT_DATA, &limits);
#endif
if (0 == rv) {
soft_limit = limits.rlim_cur;
if (soft_limit > (ARG_MAX<<5)) {
limits.rlim_cur = ARG_MAX<<5;
#ifdef RLIMIT_AS
rv = setrlimit(RLIMIT_AS, &limits);
#else
rv = setrlimit(RLIMIT_DATA, &limits);
#endif
}
}
if (0 != rv) {
return NULL;
}
#endif /* HAVE_WORDEXP_H || HAVE_GLOB_H */
#if HAVE_WORDEXP_H
/* (wordexp() implementations that execute a subshell will probably fail) */
/* (tilde expansion will probably fail because chroot; prefer ~/ or $HOME)*/
/* (we.we_wordv contents malloc()ed even though 'we' is from stack) */
{
wordexp_t we;
switch (wordexp(args, &we, WRDE_NOCMD|WRDE_UNDEF)) {
case 0: argv = we.we_wordv; break;
case WRDE_NOSPACE: errno = ENOMEM; /*@fallthrough@*/
default: wordfree(&we); return NULL;
}
}
#else /* !HAVE_WORDEXP_H */
argv = simpleton_wordsplit(args);
#if HAVE_GLOB_H
if (NULL != argv) {
size_t i = 0;
glob_t gl;
rv = GLOB_ABORTED;
gl.gl_pathv = NULL;
if (NULL != argv[0]) {
rv = glob(argv[0], GLOB_ERR|GLOB_NOSORT|GLOB_NOCHECK,
glob_errfunc, &gl);
}
while ((0 == rv || GLOB_NOMATCH == rv) && NULL != argv[++i]) {
rv = glob(argv[i], GLOB_ERR|GLOB_NOSORT|GLOB_NOCHECK|GLOB_APPEND,
glob_errfunc, &gl);
}
/* (gl.gl_pathv contents malloc()ed even though 'gl' is from stack) */
switch (rv) {
case 0:
case GLOB_NOMATCH:
free(argv);
argv = gl.gl_pathv;
break;
case GLOB_NOSPACE:
errno = ENOMEM; /*@fallthrough@*/
case GLOB_ABORTED:
default:
if (NULL != argv[i]) {
(void)
fprintf(stderr, "glob() error at pattern:\n%s\n\n", argv[i]);
}
globfree(&gl);
free(argv);
argv = NULL;
exit(1);
}
}
#endif /* HAVE_GLOB_H */
#endif /* !HAVE_WORDEXP_H */
#if HAVE_WORDEXP_H || HAVE_GLOB_H
if (soft_limit > limits.rlim_cur) {
limits.rlim_cur = soft_limit;
#ifdef RLIMIT_AS
(void) setrlimit(RLIMIT_AS, &limits);
#else
(void) setrlimit(RLIMIT_DATA, &limits);
#endif
}
#endif /* HAVE_WORDEXP_H || HAVE_GLOB_H */
return argv;
}
static int
set_limits(const rlim_t nproc)
/*@globals errno@*/
/*@modifies errno@*/
{
int rv;
struct rlimit limits;
errno = 0;
rv = getpriority(PRIO_PROCESS, 0);
if (rv < 15 && (rv != -1 || 0 == errno)) {
rv = setpriority(PRIO_PROCESS, 0, CHRESSH_PRIO);
}
if (0 != rv) {
return rv;
}
#ifdef RLIMIT_AS
rv = getrlimit(RLIMIT_AS, &limits);
#else
rv = getrlimit(RLIMIT_DATA, &limits);
#endif
if (0 == rv) {
if (limits.rlim_max > CHRESSH_DATA) {
limits.rlim_cur = CHRESSH_DATA;
limits.rlim_max = CHRESSH_DATA;
#ifdef RLIMIT_AS
rv = setrlimit(RLIMIT_AS, &limits);
#else
rv = setrlimit(RLIMIT_DATA, &limits);
#endif
}
}
if (0 != rv) {
return rv;
}
rv = getrlimit(RLIMIT_STACK, &limits);
if (0 == rv) {
if (limits.rlim_max > CHRESSH_STACK) {
limits.rlim_cur = CHRESSH_STACK;
limits.rlim_max = CHRESSH_STACK;
rv = setrlimit(RLIMIT_STACK, &limits);
}
}
if (0 != rv) {
return rv;
}
limits.rlim_cur = nproc;
limits.rlim_max = nproc;
return setrlimit(RLIMIT_NPROC, &limits); /* limit num processes allowed */
}
/* preserve only minimalist environment for sftp, rsync, and unison to work
* Note that it is expected that environment is created by system on login
* and therefore that the environment is sane, e.g. no duplicated variables
* or other mischief.
*/
static char **
env_clean(char **env, struct passwd * const pw,
/*@null@*/ const char * const home)
/*@globals errno@*/
/*@modifies env, errno@*/
{
unsigned int i;
unsigned int j;
char **path = NULL;
size_t home_len = 0;
unsigned int need_home = 0;
unsigned int need_posixly_correct = 1;
if (NULL != home) {
home_len = strlen(home);
need_home = 1;
}
for (i = j = 0; env[j] != NULL; j++) {
switch (*env[j]) {
case 'C': if (0 == memcmp(env[j], "CVSIGNORE=", 10))
break;
continue;
case 'H': if (0 == memcmp(env[j], "HOME=", 5)) {
if (NULL != home) {
if (strlen(env[j]+5) >= home_len) {
memcpy(env[j]+5, home, home_len+1);
need_home = 0;
break;
}
}
else {
break;
}
}
continue;
case 'L': if (0 == memcmp(env[j], "LANG=", 5)
|| 0 == memcmp(env[j], "LANGUAGE=", 9)
|| 0 == memcmp(env[j], "LC_", 3)) /*(prefix match)*/
break;
else if (0 == memcmp(env[j], "LOGNAME=", 8))
break; /* (or could force pw->pw_name) */
continue;
case 'P': if (0 == memcmp(env[j], "PATH=", 5)) {
path = &env[i];
break;
}
else if (0 == memcmp(env[j], "POSIX", 5)){/*(prefix match)*/
if (0 == memcmp(env[j]+5, "LY_CORRECT=", 11)) {
if ('\0' != env[j][16]) {
env[j][16] = '1';
env[j][17] = '\0';
need_posixly_correct = 0;
break;
}
}
else {
break;
}
}
continue;
case 'R': if (0 == memcmp(env[j], "RSYNC_", 6) /*(prefix match)*/
&& 0 != memcmp(env[j]+6, "RSH", 4)) /*(no RSYNC_RSH)*/
break;
continue;
case 'S': if (0 == memcmp(env[j], "SHELL=", 6))
break; /* (or could force pw->pw_shell) */
else if (0 == memcmp(env[j], "SSH", 3)) /*(prefix match)*/
break;
continue;
case 'T': if (0 == memcmp(env[j], "TZ=", 3))
break;
continue;
case 'U': if (0 == memcmp(env[j], "UNISON", 6) /*(prefix match)*/
&& '=' != env[j][6]) /* disallow "UNISON=..." */
break; /* allow UNISONLOCALHOSTNAME, UNISONBACKUPDIR */
else if (0 == memcmp(env[j], "USER=", 5))
break; /* (or could force pw->pw_name) */
continue;
default : continue;
}
env[i++] = env[j];
}
if ((i + (NULL!=home&&NULL==path) + need_home + need_posixly_correct) > j) {
char ** const env_new = malloc((i+4)*sizeof(char *));
if (NULL == env_new) {
fatal(0, pw, NULL);
}
env = memcpy(env_new, env, i*sizeof(char *));
}
if (NULL != home) {
if (NULL == path) {
path = env+(i++);
}
*path = malloc(5 + home_len + 1 + sizeof(CHROOTED_CMD_DIR));
if (NULL == *path) {
fatal(0, pw, NULL);
}
memcpy(*path, "PATH=", 5);
memcpy((*path)+5, home, home_len);
(*path)[5 + home_len] = '/';
memcpy((*path)+5+home_len+1,CHROOTED_CMD_DIR,sizeof(CHROOTED_CMD_DIR));
if (need_home) {
char * const home_env = malloc(5 + home_len + 1);
if (NULL == *path) {
fatal(0, pw, NULL);
}
memcpy(home_env, "HOME=", 5);
memcpy(home_env+5, home, home_len + 1);
env[i++] = home_env;
}
}
if (need_posixly_correct) {
/* insert POSIXLY_CORRECT=1 so that there is a better chance that
* programs using getopt_long() will parse args similar to how the
* filter_args_*() routines do in this program
*/
static char posixly_correct[] = "POSIXLY_CORRECT=1";
env[i++] = posixly_correct;
}
env[i] = NULL;
return env;
}
int
main(const int argc, char * const argv[])
/*@globals environ, errno@*/
/*@modifies environ, errno@*/
{
struct passwd *pw;
char **target_env = environ;
static char *empty_env[] = { NULL };
environ = empty_env;
(void) umask(~(mode_t)0); /* (no file perms, if signalled to dump core)*/
/* check that calling UID exists, is not root, and shell matches */
if (NULL != (pw = getpwuid(getuid()))
&& 0 != pw->pw_uid
&& 0 == memcmp(pw->pw_shell,CHROOTING_SHELL,sizeof(CHROOTING_SHELL)) ) {
/* require commands of the form: "sh" "-c" "command args args args" */
if (3 == argc && 0 == memcmp(argv[1], "-c", 3)) {
const char *chroot_dir = (const char *)pw->pw_dir;
const char *home = "/";
struct stat st;
if (0 == memcmp(pw->pw_dir, GROUP_CHROOT_DIR,
sizeof(GROUP_CHROOT_DIR)-1)