/
lshell.py
executable file
·1463 lines (1313 loc) · 58.9 KB
/
lshell.py
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
#!/usr/bin/env python
#
# Limited command Shell (lshell)
#
# $Id: lshell.py,v 1.80 2010-10-26 22:35:28 ghantoos Exp $
#
# Copyright (C) 2008-2009 Ignace Mouzannar (ghantoos) <ghantoos@ghantoos.org>
#
# This file is part of lshell
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
"""lshell restricts a user's shell environment to limited sets of commands
lshell is a shell coded in Python that lets you restrict a user's environment
to limited sets of commands, choose to enable/disable any command over SSH
(e.g. SCP, SFTP, rsync, etc.), log user's commands, implement timing
"""
import cmd
import sys
import os
import ConfigParser
from getpass import getpass, getuser
import string
import re
import getopt
import logging
import signal
import readline
import grp
import time
import glob
__author__ = "Ignace Mouzannar <ghantoos@ghantoos.org>"
__version__ = "0.9.15"
# Required config variable list per user
required_config = ['allowed', 'forbidden', 'warning_counter']
# 'timer', 'scp', 'sftp']
# set configuration file path depending on sys.exec_prefix
# on *Linux sys.exec_prefix = '/usr' and default path must be in '/etc'
# on *BSD sys.exec_prefix = '/usr/{pkg,local}/' and default path
# is '/usr/{pkg,local}/etc'
if sys.exec_prefix != '/usr':
# for *BSD
conf_prefix = sys.exec_prefix
else:
# for *Linux
conf_prefix = ''
configfile = conf_prefix + '/etc/lshell.conf'
# history file
history_file = ".lhistory"
# lock_file
lock_file = ".lshell_lock"
# help text
usage = """Usage: lshell [OPTIONS]
--config <file> : Config file location (default %s)
--log <dir> : Log files directory
-h, --help : Show this help message
--version : Show version
""" % configfile
help_help = """Limited Shell (lshell) limited help.
Cheers.
"""
# Intro Text
intro = """You are in a limited shell.
Type '?' or 'help' to get the list of allowed commands"""
class ShellCmd(cmd.Cmd, object):
""" Main lshell CLI class
"""
def __init__(self, userconf, args, stdin=None, stdout=None, stderr=None, \
g_cmd=None, g_line=None):
if stdin is None:
self.stdin = sys.stdin
else:
self.stdin = stdin
if stdout is None:
self.stdout = sys.stdout
else:
self.stdout = stdout
if stderr is None:
self.stderr = sys.stderr
else:
self.stderr = stderr
self.args = args
self.conf = userconf
self.log = self.conf['logpath']
# Set timer
if self.conf['timer'] > 0: self.mytimer(self.conf['timer'])
self.identchars = self.identchars + '+./-'
self.log.error('Logged in')
cmd.Cmd.__init__(self)
if self.conf.has_key('prompt'):
self.promptbase = self.conf['prompt']
self.promptbase = self.promptbase.replace('%u', getuser())
self.promptbase = self.promptbase.replace('%h', \
os.uname()[1].split('.')[0])
else:
self.promptbase = getuser()
self.prompt = '%s:~$ ' % self.promptbase
self.intro = self.conf['intro']
# initialize oldpwd variable to home directory
self.oldpwd = self.conf['home_path']
# initialize cli variables
self.g_cmd = g_cmd
self.g_line = g_line
def __getattr__(self, attr):
""" This method actually takes care of all the called method that are \
not resolved (i.e not existing methods). It actually will simulate \
the existance of any method entered in the 'allowed' variable list. \
e.g. You just have to add 'uname' in list of allowed commands in \
the 'allowed' variable, and lshell will react as if you had \
added a do_uname in the ShellCmd class!
"""
# in case the configuration file has been modified, reload it
if self.conf['config_mtime'] != os.path.getmtime(self.conf['configfile']):
self.conf = CheckConfig(self.args).returnconf()
self.prompt = '%s:~$ ' % self.setprompt(self.conf)
self.log = self.conf['logpath']
if self.g_cmd in ['quit', 'exit', 'EOF']:
self.log.error('Exited')
if self.g_cmd == 'EOF':
self.stdout.write('\n')
sys.exit(0)
if self.check_secure(self.g_line, self.conf['strict']) == 1:
return object.__getattribute__(self, attr)
if self.check_path(self.g_line, strict = self.conf['strict']) == 1:
return object.__getattribute__(self, attr)
if self.g_cmd in self.conf['allowed']:
self.g_arg = re.sub('^~$|^~/', '%s/' %self.conf['home_path'], \
self.g_arg)
self.g_arg = re.sub(' ~/', ' %s/' %self.conf['home_path'], \
self.g_arg)
if type(self.conf['aliases']) == dict:
self.g_line = get_aliases(self.g_line, self.conf['aliases'])
self.log.info('CMD: "%s"' %self.g_line)
if self.g_cmd == 'cd':
self.cd()
# builtin lpath function: list all allowed path
elif self.g_cmd == 'lpath':
self.lpath()
# builtin lsudo function: list all allowed sudo commands
elif self.g_cmd == 'lsudo':
self.lsudo()
# builtin history function: print command history
elif self.g_cmd == 'history':
self.history()
# builtin export function
elif self.g_cmd == 'export':
self.export()
else:
os.system(self.g_line)
elif self.g_cmd not in ['', '?', 'help', None]:
self.log.warn('INFO: unknown syntax -> "%s"' %self.g_line)
self.stderr.write('*** unknown syntax: %s\n' %self.g_cmd)
self.g_cmd, self.g_arg, self.g_line = ['', '', '']
return object.__getattribute__(self, attr)
def setprompt(self, conf):
""" set prompt used by the shell
"""
if conf.has_key('prompt'):
promptbase = conf['prompt']
promptbase = promptbase.replace('%u', getuser())
promptbase = promptbase.replace('%h', os.uname()[1].split('.')[0])
else:
promptbase = getuser()
return promptbase
def lpath(self):
""" lists allowed and forbidden path
"""
if self.conf['path'][0]:
sys.stdout.write("Allowed:\n")
for path in self.conf['path'][0].split('|'):
if path:
sys.stdout.write(" %s\n" %path[:-2])
if self.conf['path'][1]:
sys.stdout.write("Denied:\n")
for path in self.conf['path'][1].split('|'):
if path:
sys.stdout.write(" %s\n" %path[:-2])
def lsudo(self):
""" lists allowed sudo commands
"""
if self.conf.has_key('sudo_commands'):
sys.stdout.write("Allowed sudo commands:\n")
for command in self.conf['sudo_commands']:
sys.stdout.write(" - %s\n" % command)
def history(self):
""" print the commands history
"""
try:
try:
readline.write_history_file(self.conf['history_file'])
except IOError:
self.log.error('WARN: couldn\'t write history ' \
'to file %s\n' % self.conf['history_file'])
f = open(self.conf['history_file'], 'r')
i = 1
for item in f.readlines():
sys.stdout.write("%d: %s" % (i, item) )
i += 1
except:
self.log.critical('** Unable to read the history file.')
def export(self):
""" export environment variables """
# if command contains at least 1 space
if self.g_line.count(' '):
env = self.g_line.split(" ", 1)[1]
# if it conatins the equal sign, consider only the first one
if env.count('='):
var, value = env.split(' ')[0].split('=')[0:2]
os.environ.update({var:value})
def cd(self):
""" implementation of the "cd" command
"""
if len(self.g_arg) >= 1:
# add wildcard completion support to cd
if self.g_arg.find('*'):
# get all files and directories matching wildcard
wildall = glob.glob(self.g_arg)
wilddir = []
# filter to only directories
for item in wildall:
if os.path.isdir(item):
wilddir.append(item)
# sort results
wilddir.sort()
# if any results are returned, pick first one
if len(wilddir) >= 1:
self.g_arg = wilddir[0]
# go previous directory
if self.g_arg == '-':
self.g_arg = self.oldpwd
# store current directory in oldpwd variable
self.oldpwd = os.getcwd()
# change directory
try:
os.chdir(os.path.realpath(self.g_arg))
self.updateprompt(os.getcwd())
except OSError, (ErrorNumber, ErrorMessage):
sys.stdout.write("lshell: %s: %s\n" %(self.g_arg, ErrorMessage))
else:
os.chdir(self.conf['home_path'])
self.updateprompt(os.getcwd())
def check_secure(self, line, strict=None, ssh=None):
"""This method is used to check the content on the typed command. \
Its purpose is to forbid the user to user to override the lshell \
command restrictions.
The forbidden characters are placed in the 'forbidden' variable.
Feel free to update the list. Emptying it would be quite useless..: )
A warining counter has been added, to kick out of lshell a user if he \
is warned more than X time (X beeing the 'warning_counter' variable).
"""
if re.findall('[:cntrl:].*\n', line):
if not ssh:
if strict:
self.counter_update('syntax')
else:
self.log.critical('*** forbidden syntax -> %s' % line)
return 1
for item in self.conf['forbidden']:
# allow '&&' and '||' even if singles are forbidden
if item in ['&', '|']:
if re.findall("[^\%s]\%s[^\%s]" %(item, item, item), line):
if not ssh:
if strict:
self.counter_update('syntax')
else:
self.log.critical('*** forbidden syntax -> %s' \
% line)
return 1
else:
if item in line:
if not ssh:
if strict:
self.counter_update('syntax')
else:
self.log.critical('*** forbidden syntax -> %s' \
% line)
return 1
returncode = 0
# check if the line contains $(foo) executions, and check them
executions = re.findall('\$\([^)]+[)]', line)
for item in executions:
returncode += self.check_path(item[2:-1].strip(), strict = strict)
returncode += self.check_secure(item[2:-1].strip(), strict = strict)
# check fot executions using back quotes '`'
executions = re.findall('\`[^`]+[`]', line)
for item in executions:
returncode += self.check_secure(item[1:-1].strip(), strict = strict)
# check if the line contains ${foo=bar}, and check them
curly = re.findall('\$\{[^}]+[}]', line)
for item in curly:
# split to get variable only, and remove last character "}"
if re.findall(r'=|\+|\?|\-', item):
variable = re.split('=|\+|\?|\-', item, 1)
else:
variable = item
returncode += self.check_path(variable[1][:-1], strict = strict)
# if unknown commands where found, return 1 and don't execute the line
if returncode > 0:
return 1
# in case the $(foo) or `foo` command passed the above tests
elif line.startswith('$(') or line.startswith('`'):
return 0
# in case ';', '|' or '&' are not forbidden, check if in line
lines = re.split('&|\||;', line)
# remove trailing parenthesis
line = re.sub('\)$', '', line)
for sperate_line in lines:
splitcmd = sperate_line.strip().split(' ')
command = splitcmd[0]
if len(splitcmd) > 1:
cmdargs = splitcmd
else: cmdargs = None
# in case of a sudo command, check in sudo_commands list if allowed
if command == 'sudo':
if type(cmdargs) == list:
if cmdargs[1] not in self.conf['sudo_commands'] and cmdargs:
if self.conf['strict'] == 1:
if not ssh:
self.counter_update('command')
else:
self.log.critical('*** forbidden sudo -> %s' \
% line )
return 1
# if over SSH, replaced allowed list with the one of overssh
if ssh:
self.conf['allowed'] = self.conf['overssh']
# for all other commands check in allowed list
if command not in self.conf['allowed'] and command:
if not ssh:
if strict:
self.counter_update('command', line)
else:
self.log.critical('*** unknown command: %s' %command)
return 1
return 0
def counter_update(self, messagetype, path=None):
""" Update the warning_counter, log and display a warning to the user
"""
if path:
line = path
else:
line = self.g_line
# if warning_counter is set to -1, just warn, don't kick
if self.conf['warning_counter'] == -1:
self.log.critical('*** forbidden %s -> "%s"' \
% (messagetype ,line))
else:
self.conf['warning_counter'] -= 1
if self.conf['warning_counter'] < 0:
self.log.critical('*** forbidden %s -> "%s"' \
% (messagetype ,line))
self.log.critical('*** Kicked out')
sys.exit(1)
else:
self.log.critical('*** forbidden %s -> "%s"' \
% (messagetype ,line))
self.stderr.write('*** You have %s warning(s) left,' \
' before getting kicked out.\n' \
%(self.conf['warning_counter']))
self.stderr.write('This incident has been reported.\n')
def check_path(self, line, completion=None, ssh=None, strict=None):
""" Check if a path is entered in the line. If so, it checks if user \
are allowed to see this path. If user is not allowed, it calls \
self.counter_update. I case of completion, it only returns 0 or 1.
"""
allowed_path_re = str(self.conf['path'][0])
denied_path_re = str(self.conf['path'][1][:-1])
# split line depending on the operators
sep=re.compile(r'\ |;|\||&')
line = line.strip()
line = sep.split(line)
for item in line:
# remove potential quotes
try:
item = eval(item)
except:
pass
# if item has been converted to somthing other than a string
# or an int, reconvert it to a string
if type(item) not in ['str', 'int']:
item = str(item)
# replace "~" with home path
item = os.path.expanduser(item)
# if contains a shell variable
if re.findall('\$|\*|\?', item):
# remove quotes if available
item = re.sub("\"|\'", "", item)
# expand shell variables (method 1)
#for var in re.findall(r'\$(\w+|\{[^}]*\})', item):
# # get variable value (if defined)
# if os.environ.has_key(var):
# value = os.environ[var]
# else: value = ''
# # replace the variable
# item = re.sub('\$%s|\${%s}' %(var, var), value, item)
# expand shell variables and wildcards using "echo"
# i know, this a bit nasty...
try:
import subprocess
p = subprocess.Popen( "`which echo` %s" % item,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE )
(cin, cout) = (p.stdin, p.stdout)
except ImportError:
cin, cout = os.popen2('`which echo` %s' % item)
item = cout.readlines()[0].split(' ')[0].strip()
item = os.path.expandvars(item)
tomatch = os.path.realpath(item)
if os.path.isdir(tomatch) and tomatch[-1] != '/': tomatch += '/'
match_allowed = re.findall(allowed_path_re, tomatch)
if denied_path_re:
match_denied = re.findall(denied_path_re, tomatch)
else: match_denied = None
if not match_allowed or match_denied:
if not completion:
if not ssh:
if strict:
self.counter_update('path', tomatch)
else:
self.log.critical('*** Forbidden path: %s' \
% tomatch)
return 1
else:
return 1
if not completion:
if not re.findall(allowed_path_re, os.getcwd()+'/'):
if not ssh:
if strict:
self.counter_update('path', os.getcwd())
os.chdir(self.conf['home_path'])
self.updateprompt(os.getcwd())
else:
self.log.critical('*** Forbidden path: %s' \
%os.getcwd())
return 1
else:
return 1
return 0
def updateprompt(self, path):
""" Update prompt when changing directory
"""
if path is self.conf['home_path']:
self.prompt = '%s:~$ ' % self.promptbase
elif self.conf['prompt_short'] == 1:
self.prompt = '%s: %s$ ' % (self.promptbase, path.split('/')[-1])
elif re.findall(self.conf['home_path'], path):
self.prompt = '%s:~%s$ ' % ( self.promptbase, \
path.split(self.conf['home_path'])[1])
else:
self.prompt = '%s:%s$ ' % (self.promptbase, path)
def cmdloop(self, intro=None):
"""Repeatedly issue a prompt, accept input, parse an initial prefix \
off the received input, and dispatch to action methods, passing them \
the remainder of the line as argument.
"""
self.preloop()
if self.use_rawinput and self.completekey:
try:
readline.read_history_file(self.conf['history_file'])
readline.set_history_length(self.conf['history_size'])
except IOError:
# if history file does not exist
try:
open(self.conf['history_file'], 'w').close()
readline.read_history_file(self.conf['history_file'])
except IOError:
pass
self.old_completer = readline.get_completer()
readline.set_completer(self.complete)
readline.parse_and_bind(self.completekey+": complete")
try:
if self.conf['intro']:
self.stdout.write(str(self.conf['intro'])+"\n")
stop = None
while not stop:
if self.cmdqueue:
line = self.cmdqueue.pop(0)
else:
if self.use_rawinput:
try:
line = raw_input(self.prompt)
except EOFError:
line = 'EOF'
except KeyboardInterrupt:
self.stdout.write('\n')
line = ''
else:
self.stdout.write(self.prompt)
self.stdout.flush()
line = self.stdin.readline()
if not len(line):
line = 'EOF'
else:
line = line[:-1] # chop \n
line = self.precmd(line)
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
self.postloop()
finally:
if self.use_rawinput and self.completekey:
try:
readline.set_completer(self.old_completer)
except ImportError:
pass
try:
readline.write_history_file(self.conf['history_file'])
except IOError:
self.log.error('WARN: couldn\'t write history ' \
'to file %s\n' % self.conf['history_file'])
def complete(self, text, state):
"""Return the next possible completion for 'text'.
If a command has not been entered, then complete against command list.
Otherwise try to call complete_<command> to get list of completions.
"""
if state == 0:
origline = readline.get_line_buffer()
line = origline.lstrip()
# in case '|', ';', '&' used, take last part of line to complete
line = re.split('&|\||;', line)[-1].lstrip()
stripped = len(origline) - len(line)
begidx = readline.get_begidx() - stripped
endidx = readline.get_endidx() - stripped
if line.split(' ')[0] == 'sudo' and len(line.split(' ')) <= 2:
compfunc = self.completesudo
elif len (line.split(' ')) > 1 \
and line.split(' ')[0] in self.conf['allowed']:
compfunc = self.completechdir
elif begidx > 0:
cmd, args, foo = self.parseline(line)
if cmd == '':
compfunc = self.completedefault
else:
try:
compfunc = getattr(self, 'complete_' + cmd)
except AttributeError:
compfunc = self.completedefault
else:
compfunc = self.completenames
self.completion_matches = compfunc(text, line, begidx, endidx)
try:
return self.completion_matches[state]
except IndexError:
return None
def default(self, line):
""" This method overrides the original default method.
It was originally used to warn when an unknown command was entered \
(e.g. *** Unknown syntax: blabla).
It has been implemented in the __getattr__ method.
So it has no use here. Its output is now empty.
"""
self.stdout.write('')
def completenames(self, text, *ignored):
""" This method overrides the original completenames method to overload\
it's output with the command available in the 'allowed' variable \
This is useful when typing 'tab-tab' in the command prompt
"""
dotext = 'do_'+text
names = self.get_names()
for command in self.conf['allowed']:
names.append('do_' + command)
return [a[3:] for a in names if a.startswith(dotext)]
def completesudo(self, text, line, begidx, endidx):
""" complete sudo command """
return [a for a in self.conf['sudo_commands'] if a.startswith(text)]
def completechdir(self, text, line, begidx, endidx):
""" complete directories """
toreturn = []
tocomplete = line.split()[-1]
# replace "~" with home path
tocomplete = re.sub('^~', self.conf['home_path'], tocomplete)
try:
directory = os.path.realpath(tocomplete)
except:
directory = os.getcwd()
if not os.path.isdir(directory):
directory = directory.rsplit('/', 1)[0]
if directory == '': directory = '/'
if not os.path.isdir(directory):
directory = os.getcwd()
if self.check_path(directory, 1) == 0:
for instance in os.listdir(directory):
if os.path.isdir(os.path.join(directory, instance)):
instance = instance + '/'
else: instance = instance + ' '
if instance.startswith('.'):
if text.startswith('.'):
toreturn.append(instance)
else: pass
else: toreturn.append(instance)
return [a for a in toreturn if a.startswith(text)]
else:
return None
def onecmd(self, line):
""" This method overrides the original onecomd method, to put the cmd, \
arg and line variables in class global variables: self.g_cmd, \
self.g_arg and self.g_line.
Thos variables are then used by the __getattr__ method
"""
cmd, arg, line = self.parseline(line)
self.g_cmd, self.g_arg, self.g_line = [cmd, arg, line]
if not line:
return self.emptyline()
if cmd is None:
return self.default(line)
self.lastcmd = line
if cmd == '':
return self.default(line)
else:
try:
func = getattr(self, 'do_' + cmd)
except AttributeError:
return self.default(line)
return func(arg)
def emptyline(self):
""" This method overrides the original emptyline method, so it doesn't \
repeat the last command if last command was empty.
I just found this annoying..
"""
if self.lastcmd:
return 0
def do_help(self, arg):
""" This method overrides the original do_help method.
Instead of printing out the that are documented or not, it returns the \
list of allowed commands when '?' or 'help' is entered.
Of course, it doesn't override the help function: any help_* method \
will be called (e.g. help_help(self) )
"""
if arg:
try:
func = getattr(self, 'help_' + arg)
except AttributeError:
try:
doc = getattr(self, 'do_' + arg).__doc__
if doc:
self.stdout.write("%s\n"%str(doc))
return
except AttributeError:
pass
self.stdout.write("%s\n"%str(self.nohelp % (arg,)))
return
func()
else:
# Get list of allowed commands, remove duplicate 'help' then sort it
list_tmp = dict.fromkeys(self.completenames('')).keys()
list_tmp.sort()
self.columnize(list_tmp)
def help_help(self):
""" Print Help on Help """
self.stdout.write(help_help)
def mytimer(self, timeout):
""" This function is kicks you out the the lshell after \
the 'timer' variable exprires. 'timer' is set in seconds.
"""
# set timer
signal.signal(signal.SIGALRM, self._timererror)
signal.alarm(self.conf['timer'])
def _timererror(self, signum, frame):
raise LshellTimeOut, "lshell timer timeout"
class CheckConfig:
""" Check the configuration file.
"""
def __init__(self, args, stdin=None, stdout=None, stderr=None):
""" Force the calling of the methods below
"""
if stdin is None:
self.stdin = sys.stdin
else:
self.stdin = stdin
if stdout is None:
self.stdout = sys.stdout
else:
self.stdout = stdout
if stderr is None:
self.stderr = sys.stderr
else:
self.stderr = stderr
self.conf = {}
self.conf, self.arguments = self.getoptions(args, self.conf)
configfile = self.conf['configfile']
self.conf['config_mtime'] = self.get_config_mtime(configfile)
self.check_file(configfile)
self.get_global()
self.check_log()
self.get_config()
self.check_user_integrity()
self.get_config_user()
self.check_env()
self.check_scp_sftp()
self.check_passwd()
def getoptions(self, arguments, conf):
""" This method checks the usage. lshell.py must be called with a \
configuration file.
If no configuration file is specified, it will set the configuration \
file path to /etc/lshell.confelf.conf['allowed'].append('exit')
"""
# uncomment the following to set the -c/--config as mandatory argument
#if '-c' not in arguments and '--config' not in arguments:
# usage()
# set configfile as default configuration file
conf['configfile'] = configfile
try:
optlist, args = getopt.getopt(arguments, \
'hc:', \
['config=','log=','help','version'])
except getopt.GetoptError:
self.stderr.write('Missing or unknown argument(s)\n')
self.usage()
for option, value in optlist:
if option in ['--config']:
conf['configfile'] = os.path.realpath(value)
if option in ['--log']:
conf['logpath'] = os.path.realpath(value)
if option in ['-c']:
conf['ssh'] = value
if option in ['-h', '--help']:
self.usage()
if option in ['--version']:
self.version()
# put the expanded path of configfile and logpath (if exists) in
# LSHELL_ARGS environment variable
args = ['--config', conf['configfile']]
if conf.has_key('logpath'): args += ['--log', conf['logpath']]
os.environ['LSHELL_ARGS'] = str(args)
# if lshell is invoked using shh autorized_keys file e.g.
# command="/usr/bin/lshell", ssh-dss ....
if os.environ.has_key('SSH_ORIGINAL_COMMAND'):
conf['ssh'] = os.environ['SSH_ORIGINAL_COMMAND']
return conf, args
def usage(self):
""" Prints the usage """
sys.stderr.write(usage)
sys.exit(0)
def version(self):
""" Prints the version """
sys.stderr.write('lshell-%s - Limited Shell\n' %__version__)
sys.exit(0)
def check_env(self):
""" Load environment variable set in configuration file """
if self.conf.has_key('env_vars'):
env_vars = self.conf['env_vars']
for key in env_vars.keys():
os.environ[key] = str(env_vars[key])
def check_file(self, file):
""" This method checks the existence of the "argumently" given \
configuration file.
"""
if not os.path.exists(file):
self.stderr.write("Error: Config file doesn't exist\n")
self.stderr.write(usage)
sys.exit(0)
else: self.config = ConfigParser.ConfigParser()
def get_global(self):
""" Loads the [global] parameters from the configuration file
"""
try:
self.config.read(self.conf['configfile'])
except (ConfigParser.MissingSectionHeaderError, \
ConfigParser.ParsingError), argument:
self.stderr.write('ERR: %s\n' %argument)
sys.exit(0)
if not self.config.has_section('global'):
self.stderr.write('Config file missing [global] section\n')
sys.exit(0)
for item in self.config.items('global'):
if not self.conf.has_key(item[0]):
self.conf[item[0]] = item[1]
def check_log(self):
""" Sets the log level and log file
"""
# define log levels dict
self.levels = { 1 : logging.CRITICAL,
2 : logging.ERROR,
3 : logging.WARNING,
4 : logging.DEBUG }
# create logger for lshell application
if self.conf.has_key('syslogname'):
try:
logname = eval(self.conf['syslogname'])
except:
logname = self.conf['syslogname']
else:
logname = 'lshell'
logger = logging.getLogger("%s.%s" % (logname, \
self.conf['config_mtime']))
# close any logger handler/filters if exists
# this is useful if configuration is reloaded
for loghandler in logger.handlers:
logging.shutdown(logger.handlers)
for logfilter in logger.filters:
logger.removeFilter(logfilter)
formatter = logging.Formatter('%%(asctime)s (%s): %%(message)s' \
% getuser() )
syslogformatter = logging.Formatter('%s[%s]: %s: %%(message)s' \
% (logname, os.getpid(), getuser() ))
logger.setLevel(logging.DEBUG)
# set log to output error on stderr
logsterr = logging.StreamHandler()
logger.addHandler(logsterr)
logsterr.setFormatter(logging.Formatter('%(message)s'))
logsterr.setLevel(logging.CRITICAL)
# log level must be 1, 2, 3 , 4 or 0
if not self.conf.has_key('loglevel'): self.conf['loglevel'] = 0
try:
self.conf['loglevel'] = int(self.conf['loglevel'])
except ValueError:
self.conf['loglevel'] = 0
if self.conf['loglevel'] > 4: self.conf['loglevel'] = 4
elif self.conf['loglevel'] < 0: self.conf['loglevel'] = 0
# read logfilename is exists, and set logfilename
if self.conf.has_key('logfilename'):
try:
logfilename = eval(self.conf['logfilename'])
except:
logfilename = self.conf['logfilename']
currentime = time.localtime()
logfilename = logfilename.replace('%y','%s' %currentime[0])
logfilename = logfilename.replace('%m','%02d' %currentime[1])
logfilename = logfilename.replace('%d','%02d' %currentime[2])
logfilename = logfilename.replace('%h','%02d%02d' % (currentime[3] \
, currentime[4]))
logfilename = logfilename.replace('%u', getuser())
else:
logfilename = getuser()
if self.conf['loglevel'] > 0:
try:
if logfilename == "syslog":
from logging.handlers import SysLogHandler
syslog = SysLogHandler(address='/dev/log')
syslog.setFormatter(syslogformatter)
syslog.setLevel(self.levels[self.conf['loglevel']])
logger.addHandler(syslog)
else:
# if log file is writable add new log file handler
logfile = os.path.join(self.conf['logpath'], \
logfilename+'.log')
fp = open(logfile,'a').close()
self.logfile = logging.FileHandler(logfile)
self.logfile.setFormatter(formatter)
self.logfile.setLevel(self.levels[self.conf['loglevel']])
logger.addHandler(self.logfile)
except IOError:
# uncomment the 2 following lines to warn if log file is not \
# writable
#sys.stderr.write('Warning: Cannot write in log file: '
# 'Permission denied.\n')
#sys.stderr.write('Warning: Actions will not be logged.\n')
pass
self.conf['logpath'] = logger
self.log = logger
def get_config(self):
""" Load default, group and user configuation. Then merge them all.
The loadpriority is done in the following order:
1- User section
2- Group section
3- Default section
"""
self.config.read(self.conf['configfile'])
self.user = getuser()
self.conf_raw = {}
# get 'default' configuration if any
self.get_config_sub('default')
# get groups configuration if any.
# for each group the user belongs to, check if specific configuration \
# exists. The primary group has the highest priority.
grplist = os.getgroups()
grplist.reverse()
for gid in grplist:
try:
grpname = grp.getgrgid(gid)[0]
section = 'grp:' + grpname
self.get_config_sub(section)
except KeyError:
pass
# get user configuration if any
self.get_config_sub(self.user)
def get_config_sub(self, section):
""" this function is used to interpret the configuration +/-,
'all' etc.
"""
if self.config.has_section(section):
for item in self.config.items(section):
key = item[0]
value = item[1]
split = re.split('([\+\-\s]+\[[^\]]+\])', value.replace(' ', \
''))
if len(split) > 1 and key in ['path', \
'overssh', \
'allowed', \