forked from SeattleTestbed/repy_v1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnamespace.py
1505 lines (1100 loc) · 48.9 KB
/
namespace.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
"""
<Program>
namespace.py
<Started>
September 2009
<Author>
Justin Samuel
<Purpose>
This is the namespace layer that ensures separation of the namespaces of
untrusted code and our code. It provides a single public function to be
used to setup the context in which untrusted code is exec'd (that is, the
context that is seen as the __builtins__ by the untrusted code).
The general idea is that any function or object that is available between
trusted and untrusted code gets wrapped in a function or object that does
validation when the function or object is used. In general, if user code
is not calling any functions improperly, neither the user code nor our
trusted code should ever notice that the objects and functions they are
dealing with have been wrapped by this namespace layer.
All of our own api functions are wrapped in NamespaceAPIFunctionWrapper
objects whose wrapped_function() method is mapped in to the untrusted
code's context. When called, the wrapped_function() method performs
argument, return value, and exception validation as well as additional
wrapping and unwrapping, as needed, that is specific to the function
that was ultimately being called. If the return value or raised exceptions
are not considered acceptable, a NamespaceViolationError is raised. If the
arguments are not acceptable, a TypeError is raised.
Note that callback functions that are passed from untrusted user code
to trusted code are also wrapped (these are arguments to wrapped API
functions, so we get to wrap them before calling the underlying function).
The reason we wrap these is so that we can intercept calls to the callback
functions and wrap arguments passed to them, making sure that handles
passed as arguments to the callbacks get wrapped before user code sees them.
The function and object wrappers have been defined based on the API as
documented at https://seattle.cs.washington.edu/wiki/RepyLibrary
Example of using this module (this is really the only way to use the module):
import namespace
usercontext = {}
namespace.wrap_and_insert_api_functions(usercontext)
safe.safe_exec(usercode, usercontext)
The above code will result in the dict usercontext being populated with keys
that are the names of the functions available to the untrusted code (such as
'open') and the values are the wrapped versions of the actual functions to be
called (such as 'emulfile.emulated_open').
Note that some functions wrapped by this module lose some python argument
flexibility. Wrapped functions can generally only have keyword args in
situations where the arguments are optional. Using keyword arguments for
required args may not be supported, depending on the implementation of the
specific argument check/wrapping/unwrapping helper functions for that
particular wrapped function. If this becomes a problem, it can be dealt with
by complicating some of the argument checking/wrapping/unwrapping code in
this module to make the checking functions more flexible in how they take
their arguments.
Implementation details:
The majority of the code in this module is made up of helper functions to do
argument checking, etc. for specific wrapped functions.
The most important parts to look at in this module for maintenance and
auditing are the following:
USERCONTEXT_WRAPPER_INFO
The USERCONTEXT_WRAPPER_INFO is a dictionary that defines the API
functions that are wrapped and inserted into the user context when
wrap_and_insert_api_functions() is called.
FILE_OBJECT_WRAPPER_INFO
SOCKET_OBJECT_WRAPPER_INFO
LOCK_OBJECT_WRAPPER_INFO
VIRTUAL_NAMESPACE_OBJECT_WRAPPER_INFO
The above four dictionaries define the methods available on the wrapped
objects that are returned by wrapped functions. Additionally, timerhandle
and commhandle objects are wrapped but instances of these do not have any
public methods and so no *_WRAPPER_INFO dictionaries are defined for them.
NamespaceObjectWrapper
NamespaceAPIFunctionWrapper
The above two classes are the only two types of objects that will be
allowed in untrusted code. In fact, instances of NamespaceAPIFunctionWrapper
are never actually allowed in untrusted code. Rather, each function that
is wrapped has a single NamespaceAPIFunctionWrapper instance created
when wrap_and_insert_api_functions() is called and what is actually made
available to the untrusted code is the wrapped_function() method of each
of the corresponding NamespaceAPIFunctionWrapper instances.
NamespaceViolationError
This is the error that is raised from a wrapped function if any namespace
violation occurs other than invalid arguments. Invalid arguments raise
a TypeError to keep the behavior compatible with python's normal way of
handling numbers of or names of arguments.
"""
import types
# To check if objects are thread.LockType objects.
import thread
import emulfile
import emultimer
import emulcomm
import emulmisc
# Used to get SafeDict
import safe
# Used to get VirtualNamespace
import virtual_namespace
# Save a copy of a few functions not available at runtime.
_saved_getattr = getattr
_saved_callable = callable
_saved_id = id
##############################################################################
# Public functions of this module to be called from the outside.
##############################################################################
def wrap_and_insert_api_functions(usercontext):
"""
This is the main public function in this module at the current time. It will
wrap each function in the usercontext dict in a wrapper with custom
restrictions for that specific function. These custom restrictions are
defined in the dictionary USERCONTEXT_WRAPPER_INFO.
"""
_init_namespace()
for function_name in USERCONTEXT_WRAPPER_INFO:
function_info = USERCONTEXT_WRAPPER_INFO[function_name]
wrapperobj = NamespaceAPIFunctionWrapper(function_info)
usercontext[function_name] = wrapperobj.wrapped_function
##############################################################################
# Helper functions for the above public function.
##############################################################################
# Whether _init_namespace() has already been called.
initialized = False
def _init_namespace():
"""
Performs one-time initialization of the namespace module.
"""
global initialized
if not initialized:
initialized = True
_prepare_wrapped_functions_for_object_wrappers()
# These dictionaries will ultimately contain keys whose names are allowed
# methods that can be called on the objects and values which are the wrapped
# versions of the functions which are exposed to users. If a dictionary
# is empty, it means no methods can be called on a wrapped object of that type.
file_object_wrapped_functions_dict = {}
socket_object_wrapped_functions_dict = {}
lock_object_wrapped_functions_dict = {}
virtual_namespace_object_wrapped_functions_dict = {}
def _prepare_wrapped_functions_for_object_wrappers():
"""
Wraps functions that will be used whenever a wrapped object is created.
After this has been called, the dictionaries such as
file_object_wrapped_functions_dict have been populated and therefore can be
used by functions such as wrap_socket_obj().
"""
objects_tuples = [(FILE_OBJECT_WRAPPER_INFO, file_object_wrapped_functions_dict),
(SOCKET_OBJECT_WRAPPER_INFO, socket_object_wrapped_functions_dict),
(LOCK_OBJECT_WRAPPER_INFO, lock_object_wrapped_functions_dict),
(VIRTUAL_NAMESPACE_OBJECT_WRAPPER_INFO, virtual_namespace_object_wrapped_functions_dict)]
for description_dict, wrapped_func_dict in objects_tuples:
for function_name in description_dict:
function_info = description_dict[function_name]
wrapperobj = NamespaceAPIFunctionWrapper(function_info)
wrapped_func_dict[function_name] = wrapperobj.wrapped_function
##############################################################################
# Helper functions that raise NamespaceRequirementError if the argument
# does not meet the required conditions.
##############################################################################
class NamespaceRequirementError(Exception):
"""
Indicates that some namespace requirement has not been met. This is not an
exception that should be returned to the user. Instead, it is to signal to
our own code that there is a violation. We then raise a
NamespaceViolationError which will be seen by the offending user code.
"""
def _is_in(obj, sequence):
"""
A helper function to do identity ("is") checks instead of equality ("==")
when using X in [A, B, C] type constructs. So you would write:
if _is_in(type(foo), [int, long]):
instead of:
if type(foo) in [int, long]:
"""
for item in sequence:
if obj is item:
return True
return False
def _require_string(obj):
if not _is_in(type(obj), [str, unicode]):
raise NamespaceRequirementError
def _require_integer(obj):
if not _is_in(type(obj), [int, long]):
raise NamespaceRequirementError
def _require_float(obj):
if type(obj) is not float:
raise NamespaceRequirementError
def _require_integer_or_float(obj):
if not _is_in(type(obj), [int, long, float]):
raise NamespaceRequirementError
def _require_bool(obj):
if type(obj) is not bool:
raise NamespaceRequirementError
def _require_bool_or_integer(obj):
if not _is_in(type(obj), [bool, int, long]):
raise NamespaceRequirementError
def _require_tuple(obj):
if type(obj) is not tuple:
raise NamespaceRequirementError
def _require_list(obj):
if type(obj) is not list:
raise NamespaceRequirementError
def _require_tuple_or_list(obj):
if not _is_in(type(obj), [tuple, list]):
raise NamespaceRequirementError
def _require_user_function(obj):
if not _is_in(type(obj), [types.FunctionType, types.LambdaType, types.MethodType]):
raise NamespaceRequirementError
def _require_list_of_strings(obj):
_require_list(obj)
for item in obj:
_require_string(item)
def _require_dict_or_safedict(obj):
if type(obj) is not dict and not isinstance(obj, safe.SafeDict):
raise NamespaceRequirementError
def _require_safedict(obj):
if not isinstance(obj, safe.SafeDict):
raise NamespaceRequirementError
##############################################################################
# Functions that are used in the USERCONTEXT_WRAPPER_INFO to defined how each
# wrapper should be constructed. These raise NamespaceRequirementError if
# something is not considered acceptable.
##############################################################################
def allow_all(*args, **kwargs):
pass
def allow_no_args(*args, **kwargs):
if len(args) != 0 or len(kwargs.keys()) != 0:
raise NamespaceRequirementError("No arguments allowed.")
def allow_args_single_integer_or_float(*args, **kwargs):
if len(args) != 1:
raise NamespaceRequirementError
if len(kwargs.keys()) != 0:
raise NamespaceRequirementError
_require_integer_or_float(args[0])
def allow_return_none(retval):
if retval is not None:
raise NamespaceRequirementError
def allow_return_integer(retval):
_require_integer(retval)
def allow_return_float(retval):
_require_float(retval)
def allow_return_bool(retval):
_require_bool(retval)
# Armon: Boolean tuple with exactly 2 elements
def allow_return_two_bools_tuple(retval):
# First validate it is a boolean tuple
_require_tuple(retval)
for elem in retval:
_require_bool(elem)
# Check the size of the tuple is exactly 2
if len(retval) != 2:
raise NamespaceRequirementError
def allow_args_single_string(*args, **kwargs):
if len(args) != 1:
raise NamespaceRequirementError
if len(kwargs.keys()) != 0:
raise NamespaceRequirementError
_require_string(args[0])
def allow_return_string(retval):
_require_string(retval)
def allow_return_gethostbyname_ex(retval):
_require_tuple(retval)
if len(retval) != 3:
raise NamespaceRequirementError
hostname, aliaslist, ipaddrlist = retval
_require_string(hostname)
_require_list_of_strings(aliaslist)
_require_list_of_strings(ipaddrlist)
def allow_args_recvmess_callback(remoteIP, remoteport, message, commhandle):
# The callback function should receive the following arguments:
# (remoteIP, remoteport, message, commhandle)
_require_string(remoteIP)
_require_integer(remoteport)
_require_string(message)
# There isn't much to check with the commhandle as once it is wrapped
# there isn't any way user code can interact with it.
def wrap_args_recvmess_callback(remoteIP, remoteport, message, commhandle):
"""
Wrap the commhandle passed into the callback function before the callback
function is actually called.
"""
# The callback function should receive the following arguments:
# (remoteIP, remoteport, message, commhandle)
wrapped_commhandle = wrap_commhandle_obj(commhandle)
args = (remoteIP, remoteport, message, wrapped_commhandle)
kwargs = {}
return args, kwargs
def allow_args_recvmess(localip, localport, function):
_require_string(localip)
_require_integer(localport)
_require_user_function(function)
def wrap_args_recvmess(localip, localport, function):
"""
Wrap the callback function passed from user code to privileged code. This is
done so that we can intercept calls to the callback function and check and
wrap arguments passed into the untrusted callback function.
"""
function_info = {'target_func' : function,
'arg_checking_func' : allow_args_recvmess_callback,
'arg_wrapping_func' : wrap_args_recvmess_callback,
'return_checking_func' : allow_all}
wrapperobj = NamespaceAPIFunctionWrapper(function_info)
args = (localip, localport, wrapperobj.wrapped_function)
kwargs = {}
return args, kwargs
def allow_args_sendmess(desthost, destport, message, localip=None, localport=None):
_require_string(desthost)
_require_integer(destport)
_require_string(message)
# The user must provide either both or neither of localip and localport,
# but we're going to let the actual sendmess worry about that.
if localip is not None:
_require_string(localip)
if localport is not None:
_require_integer(localport)
def allow_args_openconn(desthost, destport, localip=None, localport=0, timeout=5):
# TODO: the wiki:RepyLibrary gives localport=0 as the default for this function,
# slightly different than the localport=None it gives for sendmess(). This
# should either be verified as intentional or made the same.
_require_string(desthost)
_require_integer(destport)
# The user must provide either both or neither of localip and localport,
# but we're going to let the actual sendmess worry about that.
if localip is not None:
_require_string(localip)
# We accept a localport of None to mean the same thing as 0.
if localport is not None:
_require_integer(localport)
# We accept a timeout of None to mean the same as 0.
if timeout is not None:
_require_integer_or_float(timeout)
def allow_args_waitforconn_callback(remoteip, remoteport, socketlikeobj, thiscommhandle, listencommhandle):
# The callback function should receive the following arguments:
# (remoteip, remoteport, socketlikeobj, thiscommhandle, listencommhandle)
_require_string(remoteip)
_require_integer(remoteport)
_require_emulated_socket(socketlikeobj)
# There isn't much to check with the commhandles as once they are wrapped
# there isn't any way user code can interact with them.
def wrap_args_waitforconn_callback(remoteip, remoteport, socketlikeobj, thiscommhandle, listencommhandle):
"""
Wrap the socketlikeobj, thiscommhandle, listencommhandle passed into the
callback function before the callback function is actually called.
"""
# The callback function should receive the following arguments:
# (remoteip, remoteport, socketlikeobj, thiscommhandle, listencommhandle)
wrapped_socketlikeobj = wrap_socket_obj(socketlikeobj)
wrapped_thiscommhandle = wrap_commhandle_obj(thiscommhandle)
wrapped_listencommhandle = wrap_commhandle_obj(listencommhandle)
args = (remoteip, remoteport, wrapped_socketlikeobj, wrapped_thiscommhandle,
wrapped_listencommhandle)
kwargs = {}
return args, kwargs
def allow_args_waitforconn(localip, localport, function):
_require_string(localip)
_require_integer(localport)
_require_user_function(function)
def wrap_args_waitforconn(localip, localport, function):
"""
Wrap the callback function passed from user code to privileged code. This is
done so that we can intercept calls to the callback function and check and
wrap arguments passed into the untrusted callback function.
"""
function_info = {'target_func' : function,
'arg_checking_func' : allow_args_waitforconn_callback,
'arg_wrapping_func' : wrap_args_waitforconn_callback,
'return_checking_func' : allow_all}
wrapperobj = NamespaceAPIFunctionWrapper(function_info)
args = (localip, localport, wrapperobj.wrapped_function)
kwargs = {}
return args, kwargs
def allow_args_stopcomm(wrapped_commhandle):
try:
if wrapped_commhandle._wrapped__type_name != "commhandle":
raise NamespaceRequirementError
except AttributeError:
raise NamespaceRequirementError
def allow_args_open(filename, mode='r'):
_require_string(filename)
_require_string(mode)
def allow_return_list_of_strings(retval):
_require_list_of_strings(retval)
def allow_args_settimer(waittime, function, args):
_require_integer_or_float(waittime)
_require_user_function(function)
_require_tuple_or_list(args)
def allow_args_canceltimer(wrapped_timerhandle):
try:
if wrapped_timerhandle._wrapped__type_name != "timerhandle":
raise NamespaceRequirementError
except AttributeError:
raise NamespaceRequirementError
def allow_args_virtual_namespace(code, name="<string>"):
_require_string(code)
_require_string(name)
def wrap_commhandle_obj(commhandle):
# There are no attributes to be accessed on commhandles.
return NamespaceObjectWrapper("commhandle", commhandle, [])
def wrap_timerhandle_obj(timerhandle):
# There are no attributes to be accessed on timerhandles.
return NamespaceObjectWrapper("timerhandle", timerhandle, [])
def wrap_socket_obj(socketobj):
_require_emulated_socket(socketobj)
return NamespaceObjectWrapper("socket", socketobj, socket_object_wrapped_functions_dict)
def wrap_lock_obj(lockobj):
_require_lock_object(lockobj)
return NamespaceObjectWrapper("lock", lockobj, lock_object_wrapped_functions_dict)
def wrap_file_obj(fileobj):
_require_emulated_file(fileobj)
return NamespaceObjectWrapper("file", fileobj, file_object_wrapped_functions_dict)
def wrap_virtual_namespace_obj(virt):
_require_virtual_namespace_object(virt)
return NamespaceObjectWrapper("VirtualNamespace", virt, virtual_namespace_object_wrapped_functions_dict)
def unwrap_single_arg(*args, **kwargs):
unwrapped_args = (args[0]._wrapped__object,)
unwrapped_kwargs = {}
return unwrapped_args, unwrapped_kwargs
##############################################################################
# Constants that define which functions should be wrapped and how. These are
# used by the functions wrap_and_insert_api_functions() and
# wrap_builtin_functions().
##############################################################################
# These are the functions in the user's name space excluding the builtins we
# allow. Each function is a key in the dictionary. Each value is a dictionary
# that defines the functions to be used by the wrapper when a call is
# performed. It is the same dictionary that is passed as a constructor to
# the NamespaceAPIFunctionWrapper class to create the actual wrappers.
# The public function wrap_and_insert_api_functions() uses this dictionary as
# the basis for what is populated in the user context. Anything function
# defined here will be wrapped and made available to untrusted user code.
USERCONTEXT_WRAPPER_INFO = {
# emulated open function
'open' :
{'target_func' : emulfile.emulated_open,
'arg_checking_func' : allow_args_open,
# Even though the checking function is allow_all, the wrapping function
# does check the type.
'return_checking_func' : allow_all,
'return_wrapping_func' : wrap_file_obj},
# emulated file object
'file' :
{'target_func' : emulfile.emulated_open,
'arg_checking_func' : allow_args_open,
# Even though the checking function is allow_all, the wrapping function
# does check the type.
'return_checking_func' : allow_all,
'return_wrapping_func' : wrap_file_obj},
# List the files in the sandboxed program's area
'listdir' :
{'target_func' : emulfile.listdir,
'arg_checking_func' : allow_no_args,
'return_checking_func' : allow_return_list_of_strings},
# remove a file in the sandboxed program's area
'removefile' :
{'target_func' : emulfile.removefile,
'arg_checking_func' : allow_args_single_string,
'return_checking_func' : allow_return_none},
# provides an external IP
'getmyip' :
{'target_func' : emulcomm.getmyip,
'arg_checking_func' : allow_no_args,
'return_checking_func' : allow_return_string},
# same as socket method
'gethostbyname_ex' :
{'target_func' : emulcomm.gethostbyname_ex,
'arg_checking_func' : allow_args_single_string,
'return_checking_func' : allow_return_gethostbyname_ex},
# message receive (UDP)
'recvmess' :
{'target_func' : emulcomm.recvmess,
'arg_checking_func' : allow_args_recvmess,
'arg_wrapping_func' : wrap_args_recvmess,
'return_checking_func' : allow_all,
'return_wrapping_func' : wrap_commhandle_obj},
# message sending (UDP)
'sendmess' :
{'target_func' : emulcomm.sendmess,
'arg_checking_func' : allow_args_sendmess,
'return_checking_func' : allow_return_integer},
# reliable comm channel (TCP)
'openconn' :
{'target_func' : emulcomm.openconn,
'arg_checking_func' : allow_args_openconn,
# Even though the checking function is allow_all, the wrapping function
# does check the type.
'return_checking_func' : allow_all,
'return_wrapping_func' : wrap_socket_obj},
# reliable comm listen (TCP)
'waitforconn' :
{'target_func' : emulcomm.waitforconn,
'arg_checking_func' : allow_args_waitforconn,
'arg_wrapping_func' : wrap_args_waitforconn,
# There isn't much to check in terms of the return value as the commhandle
# wrapper doesn't let anything be done to the wrapped object.
'return_checking_func' : allow_all,
'return_wrapping_func' : wrap_commhandle_obj},
# stop receiving (TCP/UDP)
'stopcomm' :
{'target_func' : emulcomm.stopcomm,
'arg_checking_func' : allow_args_stopcomm,
'arg_unwrapping_func' : unwrap_single_arg,
'return_checking_func' : allow_return_bool},
# sets a timer
'settimer' :
{'target_func' : emultimer.settimer,
'arg_checking_func' : allow_args_settimer,
# There isn't much to check in terms of the return value as the timerhandle
# wrapper doesn't let anything be done to the wrapped object.
'return_checking_func' : allow_all,
'return_wrapping_func' : wrap_timerhandle_obj},
# stops a timer if it hasn't fired
'canceltimer' :
{'target_func' : emultimer.canceltimer,
'arg_checking_func' : allow_args_canceltimer,
'arg_unwrapping_func' : unwrap_single_arg,
'return_checking_func' : allow_return_bool},
# blocks the thread for some time
'sleep' :
{'target_func' : emultimer.sleep,
'arg_checking_func' : allow_args_single_integer_or_float,
'return_checking_func' : allow_return_none},
# same as random.random()
'randomfloat' :
{'target_func' : emulmisc.randomfloat,
'arg_checking_func' : allow_no_args,
'return_checking_func' : allow_return_float},
# amount of time the program has run
'getruntime' :
{'target_func' : emulmisc.getruntime,
'arg_checking_func' : allow_no_args,
'return_checking_func' : allow_return_float},
# acquire a lock object
'getlock' :
{'target_func' : emulmisc.getlock,
'arg_checking_func' : allow_no_args,
# Even though the checking function is allow_all, the wrapping function
# does check the type.
'return_checking_func' : allow_all,
'return_wrapping_func' : wrap_lock_obj},
# Stops executing the sandboxed program
'exitall' :
{'target_func' : emulmisc.exitall,
'arg_checking_func' : allow_no_args,
'return_checking_func' : allow_return_none},
# Provides an unique identifier for the current thread
'get_thread_name' :
{'target_func' : emulmisc.get_thread_name,
'arg_checking_func' : allow_no_args,
'return_checking_func' : allow_return_string},
# Provides a safe execution environment for arbitrary code
'VirtualNamespace' :
{'target_func' : virtual_namespace.get_VirtualNamespace,
'arg_checking_func' : allow_args_virtual_namespace,
'return_checking_func' : allow_all,
'return_wrapping_func' : wrap_virtual_namespace_obj}
}
def _require_emulated_file(fileobj):
if not isinstance(fileobj, emulfile.emulated_file):
raise NamespaceRequirementError("Expected emulated_file, received " + str(fileobj))
def allow_args_emulated_file(file):
_require_emulated_file(file)
def allow_args_emulated_file_and_optional_integer(*args, **kwargs):
# First arg is self, which is required.
if len(args) not in [1, 2]:
raise NamespaceRequirementError
if len(kwargs.keys()) != 0:
raise NamespaceRequirementError
_require_emulated_file(args[0])
# If the user did provide the optional single integer, make sure it's an int.
if len(args) == 2:
_require_integer(args[1])
def allow_args_emulated_file_seek(fileobj, offset, whence=0):
_require_emulated_file(fileobj)
# Note: offset can be negative. Resist the urge to require it to be
# non-negative.
_require_integer(offset)
_require_integer(whence)
def allow_args_emulated_file_write(fileobj, data):
_require_emulated_file(fileobj)
_require_string(data)
def allow_args_emulated_file_writelines(fileobj, lines):
_require_emulated_file(fileobj)
_require_list_of_strings(lines)
FILE_OBJECT_WRAPPER_INFO = {
'close' :
{'target_func' : emulfile.emulated_file.close,
'arg_checking_func' : allow_args_emulated_file,
'return_checking_func' : allow_return_none},
'flush' :
{'target_func' : emulfile.emulated_file.flush,
'arg_checking_func' : allow_args_emulated_file,
'return_checking_func' : allow_return_none},
'next' :
{'target_func' : emulfile.emulated_file.next,
'arg_checking_func' : allow_args_emulated_file,
'return_checking_func' : allow_return_string},
'read' :
{'target_func' : emulfile.emulated_file.read,
'arg_checking_func' : allow_args_emulated_file_and_optional_integer,
'return_checking_func' : allow_return_string},
'readline' :
{'target_func' : emulfile.emulated_file.readline,
'arg_checking_func' : allow_args_emulated_file_and_optional_integer,
'return_checking_func' : allow_return_string},
'readlines' :
{'target_func' : emulfile.emulated_file.readlines,
'arg_checking_func' : allow_args_emulated_file_and_optional_integer,
'return_checking_func' : allow_return_list_of_strings},
'seek' :
{'target_func' : emulfile.emulated_file.seek,
'arg_checking_func' : allow_args_emulated_file_seek,
'return_checking_func' : allow_return_none},
'write' :
{'target_func' : emulfile.emulated_file.write,
'arg_checking_func' : allow_args_emulated_file_write,
'return_checking_func' : allow_return_none},
'writelines' :
{'target_func' : emulfile.emulated_file.writelines,
'arg_checking_func' : allow_args_emulated_file_writelines,
'return_checking_func' : allow_return_none},
}
def _require_emulated_socket(socket):
if not isinstance(socket, emulcomm.emulated_socket):
raise NamespaceRequirementError("Expected emulated_socket, received " + str(socket))
def allow_args_emulated_socket(socket):
_require_emulated_socket(socket)
def allow_args_emulated_socket_send(socket, data):
_require_emulated_socket(socket)
_require_string(data)
def allow_args_emulated_socket_recv(socket, bytes):
_require_emulated_socket(socket)
_require_integer(bytes)
SOCKET_OBJECT_WRAPPER_INFO = {
'close' :
{'target_func' : emulcomm.emulated_socket.close,
'arg_checking_func' : allow_args_emulated_socket,
'return_checking_func' : allow_return_bool},
'recv' :
{'target_func' : emulcomm.emulated_socket.recv,
'arg_checking_func' : allow_args_emulated_socket_recv,
'return_checking_func' : allow_return_string},
'send' :
{'target_func' : emulcomm.emulated_socket.send,
'arg_checking_func' : allow_args_emulated_socket_send,
'return_checking_func' : allow_return_integer},
# Armon: Add the willblock() call. Takes no args, and returns a bool tuple with 2 entries.
'willblock' :
{'target_func' : emulcomm.emulated_socket.willblock,
'arg_checking_func' : allow_args_emulated_socket,
'return_checking_func' : allow_return_two_bools_tuple},
}
def _require_lock_object(lockobj):
# The type(lockobj) is thread.lock, but there is no such thing. So, we use
# 'isinstance()' here instead of 'is'.
if not isinstance(lockobj, thread.LockType):
raise NamespaceRequirementError
def allow_args_lock_acquire(lock, blocking=1):
_require_lock_object(lock)
_require_bool_or_integer(blocking)
def allow_args_lock_release(lock):
_require_lock_object(lock)
LOCK_OBJECT_WRAPPER_INFO = {
'acquire' :
# A string for the target_func indicates a function by this name on the
# instance rather is what should be wrapped.
{'target_func' : 'acquire',
'arg_checking_func' : allow_args_lock_acquire,
'return_checking_func' : allow_return_bool},
'release' :
# A string for the target_func indicates a function by this name on the
# instance rather is what should be wrapped.
{'target_func' : 'release',
'arg_checking_func' : allow_args_lock_release,
'return_checking_func' : allow_return_none},
}
def _require_virtual_namespace_object(virt):
if not isinstance(virt, virtual_namespace.VirtualNamespace):
raise NamespaceRequirementError
def allow_args_virtual_namespace_eval(virt, context):
_require_virtual_namespace_object(virt)
_require_dict_or_safedict(context)
def allow_return_safedict(context):
_require_safedict(context)
VIRTUAL_NAMESPACE_OBJECT_WRAPPER_INFO = {
# Evaluate must take a dict or SafeDict, and can
# only return a SafeDict. We must _not_ copy the
# dict since that will screw up the references in the dict.
'evaluate' :
{
'target_func' : 'evaluate',