File: util.c

package info (click to toggle)
rssh 2.3.4-5+deb9u4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,036 kB
  • sloc: ansic: 4,437; sh: 1,069; makefile: 62; awk: 19
file content (498 lines) | stat: -rw-r--r-- 14,655 bytes parent folder | download
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
/*
 * util.c - utility functions for rssh
 * 
 * Copyright 2003-2006 Derek D. Martin ( code at pizzashack dot org ).
 *
 * This program is licensed under a BSD-style license, as follows: 
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *	notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *	notice, this list of conditions and the following disclaimer in the
 *	documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

/* SYSTEM INCLUDES */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif /* HAVE_STDLIB_H */
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNISTD_H */
#ifdef HAVE_STRING_H
#include <string.h>
#endif /* HAVE_STRING_H */
#ifdef HAVE_CTYPE_H
#include <ctype.h>
#endif /* CTYPE_H */
#ifdef HAVE_SYSLOG_H
#include <syslog.h>
#endif /* HAVE_SYSLOG_H */
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif /* HAVE_PWD_H */
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif /* HAVE_SYS_TYPES_H */
#ifdef HAVE_LIBGEN_H
#include <libgen.h>
#endif /* HAVE_LIBGEN_H */
#include <regex.h>

/* LOCAL INCLUDES */
#include "pathnames.h"
#include "rssh.h"
#include "log.h"
#include "rsshconf.h"

extern char *username;
extern char *progname;


void fail( int flags, int argc, char **argv )
{
	char *cmd;	/* string for allowed commands */
	int  size = 0;

	log_set_priority(LOG_ERR);

	/* determine which commands are usable for error message */
	if ( flags & RSSH_ALLOW_SCP ) size += 4;   /* "scp" plus a space */
	if ( flags & RSSH_ALLOW_SFTP ) size += 5;
	if ( flags & RSSH_ALLOW_CVS ) size += 4;
	if ( flags & RSSH_ALLOW_RDIST ) size += 6;
	if ( flags & RSSH_ALLOW_RSYNC ) size += 6;
	if ( flags & RSSH_ALLOW_SVNSERVE ) size += 8; /* last one, no space */

	/* create msg indicating what is allowed */
	if ( !size ) cmd = "This user is locked out.";
	else {
		size += 18 + 1;
		if ( !(cmd = (char *)malloc(size)) ){
			log_msg("fatal error: out of mem allocating log msg");
			exit(1);
		}
		cmd[0] = '\0';
		strncat(cmd, "Allowed commands: ", size);
		if ( flags & RSSH_ALLOW_SCP )
			strncat(cmd, "scp ", size);
		if ( flags & RSSH_ALLOW_SFTP )
			strncat(cmd, "sftp ", size);
		if ( flags & RSSH_ALLOW_CVS )
			strncat(cmd, "cvs ", size);
		if ( flags & RSSH_ALLOW_RDIST )
			strncat(cmd, "rdist ", size);
		if ( flags & RSSH_ALLOW_RSYNC )
			strncat(cmd, "rsync ", size);
		if ( flags & RSSH_ALLOW_SVNSERVE )
			strncat(cmd, "svnserve", size);
	}

	/* print error message to user and log attempt */
	fprintf(stderr, "\nThis account is restricted by rssh.\n"
		"%s\n\nIf you believe this is in error, please contact "
		"your system administrator.\n\n", cmd);
	if ( argc < 3 )
		log_msg("user %s attempted to log in with a shell",
			username);
	else{
		log_msg("user %s attempted to execute forbidden commands",
			username);
		log_msg("command: %s", argv[2]);
	}

	exit(1);
}


/*
 * opt_exist() - takes a string representing a command line, and a single
 *               character representing a command-line option flag (e.g. "-S")
 *               to search for.  If the option exists in the command line,
 *               return TRUE.  This function is a little over-zealous about
 *               returning a match, but in this case that is better than not
 *               being zealous enough.  And frankly, I don't want to spend the
 *               time required to get it 100% right.  It's not worth the
 *               effort.
 */
bool opt_exist(char *cl, char opt)
{
	int	i = 1;
	int	len;

	len = strlen(cl);

	/* process command line character by character */
	if (!(cl[0] == '-')) return FALSE;
	while ( i < (len) ){
		if ( cl[i] == opt ) return TRUE;
		i++;
	}
	return FALSE;
}


bool opt_filter(char **vec, const char opt)
{
	while (vec && *vec){
		if (opt_exist(*vec, opt)){
			fprintf(stderr, "\nillegal insecure %c option", opt);
			log_msg("insecure %c option in command line!", opt);
			return TRUE;
		}
		vec++;
	}
	return FALSE;
}


bool check_command( char *cl, ShellOptions_t *opts, char *cmd, int cmdflag )
{
	char	*prog;		/* basename of cmd */
	char 	*tmp = cl;
	bool	need_free = FALSE;
	bool	rc = FALSE;
	int 	i;
	size_t	len;


	if ( opts->shell_flags & cmdflag ){
		/* cl may be a full command line; if so get first word */
		len = strlen(cl);
		for (i=0; i < len && !isspace(*(cl + i)); i++);
		if (i < len){
			if (!(tmp = (char *)malloc(sizeof (char) * (i+1)))){
				log_msg("malloc() failed in check_command()");
				return FALSE;
			}
			need_free = TRUE;
			memcpy(tmp, cl, i);
			tmp[i] = '\0';
		}

		/* compare tmp to cmd and prog for match */
		prog = basename(cmd);
		if ( !(strcmp(tmp, cmd)) || !(strcmp(tmp, prog))){
			log_msg("cmd '%s' approved", prog);
			rc = TRUE;
		}	
	}
	if (need_free) free(tmp);
	return rc;
}


/*
 * rsync_okay() - require --server on all rsh command lines, check that -e
 *		  contains only protocol information, and reject any --rsh,
 *		  --config, or --daemon option. Returns FALSE if the command
 *		  line should not be allowed, TRUE if it is okay.
 */
static int rsync_okay( char **vec )
{
	regex_t	re;
	int	server = FALSE;
	int	e_found = FALSE;

	/*
	 * rsync will send -e, followed by either just "." (meaning no special
	 * protocol) or "N.N" (meaning a pre-release protocol version),
	 * followed by some number of alphabetic flags indicating various
	 * supported options.  There may be other options between - and the e,
	 * but -e will always be the last option in the string.	 A typical
	 * option passed by the client is "-ltpre.iL".
	 *
	 * Note that if --server is given, this should never be parsed as a
	 * shell, but we'll tightly verify it anyway, just in case.
	 *
	 * This regex matches the acceptable flags containing -e, so if it
	 * does not match, the command line should be rejected.
	 */
	static const char pattern[]
	    = "^-[a-df-zA-Z]*e[0-9]*\\.[0-9]*[a-zA-Z]*$";

	/*
	 * Only recognize --server if it's the first option.  rsync itself
	 * always passes it that way, and if it's not the first argument, it
	 * could be hidden from the server as an argument to some other
	 * option.
	 */
	if ( !(vec && vec[0] && vec[1] && strcmp(vec[1], "--server") == 0) )
		return FALSE;

	/* Check the remaining options for -e or --rsh. */
	if ( regcomp(&re, pattern, REG_EXTENDED | REG_NOSUB) != 0 ){
		return FALSE;
	}
	while (vec && *vec){
		if ( strcmp(*vec, "--rsh") == 0
		     || strcmp(*vec, "--daemon") == 0
		     || strcmp(*vec, "--config") == 0
		     || strncmp(*vec, "--rsh=", strlen("--rsh=")) == 0
		     || strncmp(*vec, "--config=", strlen("--config=")) == 0 ){
			regfree(&re);
			return FALSE;
		}
		if ( strncmp(*vec, "--", 2) != 0 && opt_exist(*vec, 'e') ){
			e_found = TRUE;
			if ( regexec(&re, *vec, 0, NULL, 0) != 0 ){
				regfree(&re);
				return FALSE;
			}
		}
		vec++;
	}
	regfree(&re);
	return TRUE;
}


/*
 * scp_okay() - take the command line and check that it is a hopefully-safe scp
 *		server command line, accepting only very specific options.
 *		Returns FALSE if the command line should not be allowed, TRUE
 *		if it is okay.
 */
static int scp_okay( char **vec )
{
	int saw_f_or_t = FALSE;

	for ( vec++; vec && *vec; vec++ ){
		/* Allowed options. */
		if ( strcmp(*vec, "-v") == 0 ) continue;
		if ( strcmp(*vec, "-r") == 0 ) continue;
		if ( strcmp(*vec, "-p") == 0 ) continue;
		if ( strcmp(*vec, "-d") == 0 ) continue;
		if ( strcmp(*vec, "-f") == 0 || strcmp(*vec, "-pf") == 0 ){
			saw_f_or_t = TRUE;
			continue;
		}
		if ( strcmp(*vec, "-t") == 0 || strcmp(*vec, "-pt") == 0 ){
			saw_f_or_t = TRUE;
			continue;
		}

		/* End of arguments. */
		if ( strcmp(*vec, "--") == 0 ) break;

		/* Any other argument is not allowed. */
		if ( *vec[0] == '-' ) return FALSE;
	}

	/* Either -f or -t must have been given. */
	return saw_f_or_t;
}


/*
 * check_command_line() - take the command line passed to rssh, and verify
 *			  that the specified command is one the user is
 *			  allowed to run and validate the arguments.  Return the
 *			  path of the command which will be run if it is ok, or
 *			  return NULL if it is not.
 */
char *check_command_line( char **cl, ShellOptions_t *opts )
{

	/* Here we call check_command not to validate, but to match */
	if ( check_command(*cl, opts, PATH_SFTP_SERVER, RSSH_ALLOW_SFTP) )
		return PATH_SFTP_SERVER;

	if ( check_command(*cl, opts, PATH_SCP, RSSH_ALLOW_SCP) ){
		if ( !scp_okay(cl) ){
			fprintf(stderr, "\ninsecure scp option not allowed.");
			log_msg("insecure scp option in scp command line");
			return NULL;
		}
		return PATH_SCP;
	}

	if ( check_command(*cl, opts, PATH_CVS, RSSH_ALLOW_CVS) ){
		if ( opt_filter(cl, 'e') ) return NULL;
		return PATH_CVS;
	}

	if ( check_command(*cl, opts, PATH_RDIST, RSSH_ALLOW_RDIST) ){
		/* filter -P option */
		if ( opt_filter(cl, 'P') ) return NULL;
		return PATH_RDIST;
	}

	if ( check_command(*cl, opts, PATH_RSYNC, RSSH_ALLOW_RSYNC) ){
		if ( !rsync_okay(cl) ){
			fprintf(stderr, "\ninsecure rsync options not allowed.");
			log_msg("insecure rsync options in rsync command line!");
			return NULL;
		}

		/*
		 * rsync is linked with popt, which recognizes a configuration
		 * file ~/.popt that can, among other things, define aliases.
		 * If someone can write to the home directory of the rssh
		 * user, they can upload a ~/.popt file that contains
		 * something like "rsync alias --server --rsh" and then
		 * execute commands they upload.  popt does not try to read
		 * its configuration file if HOME is not set, so unset HOME to
		 * disable this behavior.
		 */
		if ( unsetenv("HOME") < 0 ){
			log_msg("cannot unsetenv() HOME");
			return NULL;
		}

		return PATH_RSYNC;
	}
	if ( check_command(*cl, opts, PATH_SVNSERVE, RSSH_ALLOW_SVNSERVE) ){
		/* check command line */
		if( cl[1] == NULL || strcmp(cl[1], "-t") != 0 || cl[2] != NULL){
			fprintf(stderr, "\nextra svnserver parameter(s) not allowed.");
			log_msg("unallowed option(s) in svnserver command line!");
			return NULL;
		}

		return PATH_SVNSERVE;
	}
	/* No match, return NULL */
	return NULL;
}


/*
 * get_command() - take the command line passed to rssh, and verify
 *		   that the specified command is one the user is allowed to run.
 *		   Return the path of the command which will be run if it is ok,
 *		   or return NULL if it is not.
 */
char *get_command( char *cl, ShellOptions_t *opts )
{

	if ( check_command(cl, opts, PATH_SFTP_SERVER, RSSH_ALLOW_SFTP) )
		return PATH_SFTP_SERVER;
	if ( check_command(cl, opts, PATH_SCP, RSSH_ALLOW_SCP) )
		return PATH_SCP;
	if ( check_command(cl, opts, PATH_CVS, RSSH_ALLOW_CVS) )
		return PATH_CVS;
	if ( check_command(cl, opts, PATH_RDIST, RSSH_ALLOW_RDIST) )
		return PATH_RDIST;
	if ( check_command(cl, opts, PATH_RSYNC, RSSH_ALLOW_RSYNC) )
		return PATH_RSYNC;
	if ( check_command(cl, opts, PATH_SVNSERVE, RSSH_ALLOW_SVNSERVE) )
		return PATH_SVNSERVE;
	return NULL;
}



/*
 * extract_root() - takes a root directory and the full path to some other
 *                  directory, and returns a pointer to a string which
 *                  contains the path of the second directory relative to the
 *                  first.  In the event the second dir is not located
 *                  somewhere in the first, NULL is returned.
 */
char *extract_root( char *root, char *path )
{
	char	*temp;
	int	len;

	len = strlen(root);
	/* get rid of a trailing / from the root path */
	if ( root[len - 1] == '/' ){
		root[len - 1] = '\0';
		len--;
	}
	if ( (strncmp(root, path, len)) ) return NULL;
	
	/*
	 * path[len] is the first character of path which is not part of root.
	 * If it is not '/' then we chopped path off in the middle of a path
	 * element, and the result is not reliable.  Assume an error.
	 */
	if ( path[len] != '/' ) return NULL;
	if ( !(temp = strdup(path + len)) ){
		log_set_priority(LOG_ERR);
		log_msg("can't allocate memory in function extract_root()");
		exit(1);
	}
	return temp;
}

/*
 * validate_mask() - takes a string which should be a umask, converts it, and
 *                   validates that it is a valid umask.  Returns true if it's
 *                   good, false if it isn't.  The integer umask is returned
 *                   in the integer pointer mask.
 */
int validate_umask( const char *temp, int *mask )
{
	char	*err = NULL;	/* for strtol() */

	/* convert the umask to a number */
	*mask = strtol(temp, &err, 8);
	if ( *err ) return FALSE;
	/* make sure it's a good umask */
	if ( (*mask < 0) || (*mask > 0777) ) return FALSE;
	return TRUE;
}


/*
 * validate_access() - takes a string which should be the access bits for
 *                     allow_sftp and allow_scp (in that order), and validates
 *                     them.  Returns the bits in the bool pointers of the
 *                     same name, and returns FALSE if the bits are not valid
 */
int validate_access( const char *temp, bool *allow_sftp, bool *allow_scp,
		     bool *allow_cvs, bool *allow_rdist, bool *allow_rsync,
		     bool *allow_svnserve )
{
	int	i;

#define NUM_ACCESS_BITS 6

	if ( strlen(temp) != NUM_ACCESS_BITS ) return FALSE;
	/* make sure the bits are valid */
	for ( i = 0; i < NUM_ACCESS_BITS; i++ )
		if ( temp[i] < '0' || temp[i] > '1' ) return FALSE;
	/* This is easier to read if we allign the = */
	*allow_rsync	= temp[0] - '0';
	*allow_rdist	= temp[1] - '0';
	*allow_cvs	= temp[2] - '0';
	*allow_sftp	= temp[3] - '0';
	*allow_scp	= temp[4] - '0';
	*allow_svnserve	= temp[5] - '0';
	return TRUE;
}

/*
 * get_username() - get the username of the user, or return unknown
 *
 */
char *get_username( void )
{
	struct passwd	*temp;

	if ( !(temp = getpwuid(getuid()) ) ) return "unknown user!";
	return temp->pw_name;
}