-
Notifications
You must be signed in to change notification settings - Fork 4
/
repy.py
executable file
·453 lines (356 loc) · 14.6 KB
/
repy.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
"""
<Author>
Justin Cappos
Ivan Beschastnikh (12/24/08) -- added usage
Brent Couvrette (2/27/09) -- added servicelog commandline option
Conrad Meyer (5/22/09) -- switch option parsing to getopt
<Start Date>
June 26th, 2008
<Description>
Restricted execution environment for python. Should stop someone
from doing "bad things" (which is also defined to include many
useful things). This module allows the user to define code that
gets called either on the reciept of a packet, when a timer fires,
on startup, and on shutdown. The restricted code can only do a few
"external" things like send data packets and store data to disk.
The CPU, memory, disk usage, and network bandwidth are all limited.
<Usage>
Usage: repy.py [options] restrictionsfile program_to_run.repy [program args]
Where [options] are some combination of the following:
--simple : Simple execution mode -- execute and exit
--execinfo : Display information regarding the current execution state.
--ip IP : This flag informs Repy that it is allowed to bind to the given given IP.
: This flag may be asserted multiple times.
: Repy will attempt to use IP's and interfaces in the order they are given.
--iface interface : This flag informs Repy that it is allowed to bind to the given interface.
: This flag may be asserted multiple times.
--nootherips : Instructs Repy to only use IP's and interfaces that are explicitly given.
: It should be noted that loopback (127.0.0.1) is always permitted.
--logfile filename.txt : Set up a circular log buffer and output to logfilename.txt
--stop filename : Repy will watch for the creation of this file and abort when it happens
: File can have format EXITCODE;EXITMESG. Code 44 is Stopped and is the default.
: EXITMESG will be printed prior to exiting if it is non-null.
--status filename.txt : Write status information into this file
--cwd dir : Set Current working directory
--servicelog : Enable usage of the servicelogger for internal errors
"""
# Let's make sure the version of python is supported
import checkpythonversion
checkpythonversion.ensure_python_version_is_supported()
import safe
import sys
import getopt
import emulcomm
import idhelper
import namespace
import nanny
import restrictions
import time
import threading
import loggingrepy
import nmstatusinterface
import harshexit
import statusstorage
import repy_constants
import os
# Armon: Using VirtualNamespace as an abstraction around direct execution
import virtual_namespace
## we'll use tracebackrepy to print our exceptions
import tracebackrepy
# This block allows or denies different actions in the safe module. I'm
# doing this here rather than the natural place in the safe module because
# I want to keep that module unmodified to make upgrading easier.
# Allow the user to do try, except, finally, etc.
safe._NODE_CLASS_OK.append("TryExcept")
safe._NODE_CLASS_OK.append("TryFinally")
safe._NODE_CLASS_OK.append("Raise")
safe._NODE_CLASS_OK.append("ExcepthandlerType")
safe._NODE_CLASS_OK.append("Invert")
# needed for traceback
# NOTE: still needed for tracebackrepy
safe._BUILTIN_OK.append("isinstance")
safe._BUILTIN_OK.append("BaseException")
safe._BUILTIN_OK.append("WindowsError")
safe._BUILTIN_OK.append("type")
safe._BUILTIN_OK.append("issubclass")
# needed to allow primitive marshalling to be built
safe._BUILTIN_OK.append("ord")
safe._BUILTIN_OK.append("chr")
# should not be used! Use exitall instead.
safe._BUILTIN_OK.remove("exit")
safe._BUILTIN_OK.remove("quit")
safe._STR_OK.append("__repr__")
safe._STR_OK.append("__str__")
safe._STR_OK.append("__del__")
# allow __ in strings. I'm 99% sure this is okay (do I want to risk it?)
safe._NODE_ATTR_OK.append('value')
# Disables safe, and resumes normal fork
def nonSafe_fork():
val = __orig_fork()
if val == 0 and safe._builtin_globals_r != None:
safe._builtin_restore()
return val
# Only override fork if it exists (e.g. Windows)
if "fork" in dir(os):
__orig_fork = os.fork
os.fork = nonSafe_fork
def main(restrictionsfn, program, args):
# Armon: Initialize the circular logger before forking in init_restrictions()
if logfile:
# time to set up the circular logger
loggerfo = loggingrepy.circular_logger(logfile)
# and redirect err and out there...
sys.stdout = loggerfo
sys.stderr = loggerfo
else:
# let's make it so that the output (via print) is always flushed
sys.stdout = loggingrepy.flush_logger(sys.stdout)
# start the nanny up and read the restrictions files.
restrictions.init_restrictions(restrictionsfn)
# Armon: Update our IP cache
emulcomm.update_ip_cache()
# These will be the functions and variables in the user's namespace (along
# with the builtins allowed by the safe module).
usercontext = {'mycontext':{}}
# Add to the user's namespace wrapped versions of the API functions we make
# available to the untrusted user code.
namespace.wrap_and_insert_api_functions(usercontext)
# Convert the usercontext from a dict to a SafeDict
usercontext = safe.SafeDict(usercontext)
# Allow some introspection by providing a reference to the context
usercontext["_context"] = usercontext
# let's try three times to load the file...
for attempts in range(3):
try:
# grab the user code from the file
usercode = file(program).read()
# and then exit the loop on success
break
except (OSError, IOError), e:
# Might be an interrupted system call, if so retry... (#840)
if 'nterrupred system call' in str(e):
continue
print "Failed to read the specified file: '"+program+"'"
raise
except:
print "Failed to read the specified file: '"+program+"'"
raise
else:
print "Failed to read the specified file with multiple attempts: '"+program+"'"
# Armon: Create the main namespace
main_namespace = virtual_namespace.VirtualNamespace(usercode, program)
# Let the code string get GC'ed
usercode = None
# Insert program log separator and execution information
if displayexecinfo:
print '=' * 40
print "Running program:", program
if simpleexec:
print "(Simple execution mode)"
else:
print "Arguments:", args
print '=' * 40
# If we are in "simple execution" mode, execute and exit
if simpleexec:
main_namespace.evaluate(usercontext)
sys.exit(0)
# I'll use this to detect when the program is idle so I know when to quit...
idlethreadcount = threading.activeCount()
# call the initialize function
usercontext['callfunc'] = 'initialize'
usercontext['callargs'] = args[:]
initialize_id = idhelper.getuniqueid()
try:
nanny.tattle_add_item('events', initialize_id)
except Exception, e:
tracebackrepy.handle_internalerror("Failed to aquire event for '" + \
"initialize' event.\n(Exception was: %s)" % e.message, 140)
try:
main_namespace.evaluate(usercontext)
except SystemExit:
raise
except:
# I think it makes sense to exit if their code throws an exception...
tracebackrepy.handle_exception()
harshexit.harshexit(6)
finally:
nanny.tattle_remove_item('events', initialize_id)
# I've changed to the threading library, so this should increase if there are
# pending events
while threading.activeCount() > idlethreadcount:
# do accounting here?
time.sleep(0.25)
# Once there are no more pending events for the user thread, we give them
# an "exit" event. This allows them to clean up, etc. if needed.
# call the user program to notify them that we are exiting...
usercontext['callfunc'] = 'exit'
exit_id = idhelper.getuniqueid()
try:
nanny.tattle_add_item('events', exit_id)
except Exception, e:
tracebackrepy.handle_internalerror("Failed to aquire event for '" + \
"exit' event.\n(Exception was: %s)" % e.message, 141)
try:
main_namespace.evaluate(usercontext)
except SystemExit:
raise
except:
# I think it makes sense to exit if their code throws an exception...
tracebackrepy.handle_exception()
harshexit.harshexit(7)
finally:
nanny.tattle_remove_item('events', exit_id)
# normal exit...
harshexit.harshexit(0)
def usage(str_err=""):
# Ivan 12/24/2008
"""
<Purpose>
Prints repy.py usage and possibly an error supplied argument
<Arguments>
str_err (string):
Options error to print to stdout
<Exceptions>
None
<Side Effects>
Modifies stdout
<Returns>
None
"""
print
if str_err:
print "Error:", str_err
print """
Usage: repy.py [options] restrictionsfile program_to_run.repy [program args]
Where [options] are some combination of the following:
--simple : Simple execution mode -- execute and exit
--execinfo : Display information regarding the current execution state.
--ip IP : This flag informs Repy that it is allowed to bind to the given given IP.
: This flag may be asserted multiple times.
: Repy will attempt to use IP's and interfaces in the order they are given.
--iface interface : This flag informs Repy that it is allowed to bind to the given interface.
: This flag may be asserted multiple times.
--nootherips : Instructs Repy to only use IP's and interfaces that are explicitly given.
: It should be noted that loopback (127.0.0.1) is always permitted.
--logfile filename.txt : Set up a circular log buffer and output to logfilename.txt
--stop filename : Repy will watch for the creation of this file and abort when it happens
: File can have format EXITCODE;EXITMESG. Code 44 is Stopped and is the default.
: EXITMESG will be printed prior to exiting if it is non-null.
--status filename.txt : Write status information into this file
--cwd dir : Set Current working directory
--servicelog : Enable usage of the servicelogger for internal errors
--norestrictions : Disable the use of function restrictions, but not resource limits
"""
return
if __name__ == '__main__':
global simpleexec
global logfile
global displayexecinfo
# Armon: The CMD line path to repy is the first argument
repy_location = sys.argv[0]
# Get the directory repy is in
repy_directory = os.path.dirname(repy_location)
# Translate into an absolute path
if os.path.isabs(repy_directory):
absolute_repy_directory = repy_directory
else:
# This will join the currect directory with the relative path
# and then get the absolute path to that location
absolute_repy_directory = os.path.abspath(os.path.join(os.getcwd(), repy_directory))
# Store the absolute path as the repy startup directory
repy_constants.REPY_START_DIR = absolute_repy_directory
# For security, we need to make sure that the Python path doesn't change even
# if the directory does...
newsyspath = []
for item in sys.path[:]:
if item == '' or item == '.':
newsyspath.append(os.getcwd())
else:
newsyspath.append(item)
# It should be safe now. I'm assuming the user isn't trying to undercut us
# by setting a crazy python path
sys.path = newsyspath
args = sys.argv[1:]
try:
optlist, fnlist = getopt.getopt(args, '', [
'simple', 'execinfo', 'ip=', 'iface=', 'nootherips', 'logfile=',
'stop=', 'status=', 'cwd=', 'servicelog', 'norestrictions'
])
except getopt.GetoptError:
usage()
sys.exit(1)
# Set up the simple variable if needed
simpleexec = False
# By default we don't want to use the service logger
servicelog = False
# Default logfile (if the option --logfile isn't passed)
logfile = None
# Default stopfile (if the option --stopfile isn't passed)
stopfile = None
# Default stopfile (if the option --stopfile isn't passed)
statusfile = None
# Don't display exec info (if the option --execinfo isn't passed)
displayexecinfo = False
if len(fnlist) < 2:
usage("Must supply a restrictions file and a program file to execute")
sys.exit(1)
for option, value in optlist:
if option == '--simple':
simpleexec = True
elif option == '--norestrictions':
restrictions.disablerestrictions = True
elif option == '--ip':
emulcomm.user_ip_interface_preferences = True
# Append this ip to the list of available ones if it is new, since
# multiple IP's may be specified
if (True, value) not in emulcomm.user_specified_ip_interface_list:
emulcomm.user_specified_ip_interface_list.append((True, value))
elif option == '--iface':
emulcomm.user_ip_interface_preferences = True
# Append this interface to the list of available ones if it is new
if (False, value) not in emulcomm.user_specified_ip_interface_list:
emulcomm.user_specified_ip_interface_list.append((False, value))
# Check if they have told us explicitly not to allow other IP's
elif option == '--nootherips':
# Set user preference to True
emulcomm.user_ip_interface_preferences = True
# Disable nonspecified IP's
emulcomm.allow_nonspecified_ips = False
elif option == '--logfile':
# set up the circular log buffer...
logfile = value
elif option == '--stop':
# Watch for the creation of this file and abort when it happens...
stopfile = value
elif option == '--status':
# Write status information into this file...
statusfile = value
# Set Current Working Directory
elif option == '--cwd':
os.chdir(value)
# Enable logging of internal errors to the service logger.
elif option == '--servicelog':
servicelog = True
# Insert program execution separators and log calling information
elif option == '--execinfo':
displayexecinfo = True
# Update repy current directory
repy_constants.REPY_CURRENT_DIR = os.path.abspath(os.getcwd())
# Initialize the NM status interface
nmstatusinterface.init(stopfile, statusfile)
# Write out our initial status
statusstorage.write_status("Started")
restrictionsfn = fnlist[0]
progname = fnlist[1]
progargs = fnlist[2:]
# We also need to pass in whether or not we are going to be using the service
# log for repy. We provide the repy directory so that the vessel information
# can be found regardless of where we are called from...
tracebackrepy.initialize(servicelog, absolute_repy_directory)
try:
main(restrictionsfn, progname, progargs)
except SystemExit:
harshexit.harshexit(4)
except:
tracebackrepy.handle_exception()
harshexit.harshexit(3)