/
transformer.py
1445 lines (1115 loc) · 45.4 KB
/
transformer.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
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
"""
transformer module:
uses Python standard library ast module and its containing classes to transform
the parsed python code to create a modified AST for a byte code generation.
"""
# This package should follow the Plone Sytleguide for Python,
# which differ from PEP8:
# http://docs.plone.org/develop/styleguide/python.html
from ._compat import IS_PY2
from ._compat import IS_PY3
from ._compat import IS_PY34_OR_GREATER
from ._compat import IS_PY35_OR_GREATER
import ast
import contextlib
import textwrap
# For AugAssign the operator must be converted to a string.
IOPERATOR_TO_STR = {
# Shared by python2 and python3
ast.Add: '+=',
ast.Sub: '-=',
ast.Mult: '*=',
ast.Div: '/=',
ast.Mod: '%=',
ast.Pow: '**=',
ast.LShift: '<<=',
ast.RShift: '>>=',
ast.BitOr: '|=',
ast.BitXor: '^=',
ast.BitAnd: '&=',
ast.FloorDiv: '//='
}
if IS_PY35_OR_GREATER:
IOPERATOR_TO_STR[ast.MatMult] = '@='
# For creation allowed magic method names. See also
# https://docs.python.org/3/reference/datamodel.html#special-method-names
ALLOWED_FUNC_NAMES = frozenset([
'__init__',
'__contains__',
'__lt__',
'__le__',
'__eq__',
'__ne__',
'__gt__',
'__ge__',
])
FORBIDDEN_FUNC_NAMES = frozenset([
'print',
'printed',
])
# When new ast nodes are generated they have no 'lineno' and 'col_offset'.
# This function copies these two fields from the incoming node
def copy_locations(new_node, old_node):
assert 'lineno' in new_node._attributes
new_node.lineno = old_node.lineno
assert 'col_offset' in new_node._attributes
new_node.col_offset = old_node.col_offset
ast.fix_missing_locations(new_node)
class PrintInfo(object):
def __init__(self):
self.print_used = False
self.printed_used = False
@contextlib.contextmanager
def new_print_scope(self):
old_print_used = self.print_used
old_printed_used = self.printed_used
self.print_used = False
self.printed_used = False
try:
yield
finally:
self.print_used = old_print_used
self.printed_used = old_printed_used
class RestrictingNodeTransformer(ast.NodeTransformer):
def __init__(self, errors=None, warnings=None, used_names=None):
super(RestrictingNodeTransformer, self).__init__()
self.errors = [] if errors is None else errors
self.warnings = [] if warnings is None else warnings
# All the variables used by the incoming source.
# Internal names/variables, like the ones from 'gen_tmp_name', don't
# have to be added.
# 'used_names' is for example needed by 'RestrictionCapableEval' to
# know wich names it has to supply when calling the final code.
self.used_names = {} if used_names is None else used_names
# Global counter to construct temporary variable names.
self._tmp_idx = 0
self.print_info = PrintInfo()
def gen_tmp_name(self):
# 'check_name' ensures that no variable is prefixed with '_'.
# => Its safe to use '_tmp..' as a temporary variable.
name = '_tmp%i' % self._tmp_idx
self._tmp_idx += 1
return name
def error(self, node, info):
"""Record a security error discovered during transformation."""
lineno = getattr(node, 'lineno', None)
self.errors.append(
'Line {lineno}: {info}'.format(lineno=lineno, info=info))
def warn(self, node, info):
"""Record a security error discovered during transformation."""
lineno = getattr(node, 'lineno', None)
self.warnings.append(
'Line {lineno}: {info}'.format(lineno=lineno, info=info))
def guard_iter(self, node):
"""
Converts:
for x in expr
to
for x in _getiter_(expr)
Also used for
* list comprehensions
* dict comprehensions
* set comprehensions
* generator expresions
"""
node = self.node_contents_visit(node)
if isinstance(node.target, ast.Tuple):
spec = self.gen_unpack_spec(node.target)
new_iter = ast.Call(
func=ast.Name('_iter_unpack_sequence_', ast.Load()),
args=[node.iter, spec, ast.Name('_getiter_', ast.Load())],
keywords=[])
else:
new_iter = ast.Call(
func=ast.Name("_getiter_", ast.Load()),
args=[node.iter],
keywords=[])
copy_locations(new_iter, node.iter)
node.iter = new_iter
return node
def is_starred(self, ob):
if IS_PY3:
return isinstance(ob, ast.Starred)
else:
return False
def gen_unpack_spec(self, tpl):
"""Generate a specification for 'guarded_unpack_sequence'.
This spec is used to protect sequence unpacking.
The primary goal of this spec is to tell which elements in a sequence
are sequences again. These 'child' sequences have to be protected
again.
For example there is a sequence like this:
(a, (b, c), (d, (e, f))) = g
On a higher level the spec says:
- There is a sequence of len 3
- The element at index 1 is a sequence again with len 2
- The element at index 2 is a sequence again with len 2
- The element at index 1 in this subsequence is a sequence again
with len 2
With this spec 'guarded_unpack_sequence' does something like this for
protection (len checks are omitted):
t = list(_getiter_(g))
t[1] = list(_getiter_(t[1]))
t[2] = list(_getiter_(t[2]))
t[2][1] = list(_getiter_(t[2][1]))
return t
The 'real' spec for the case above is then:
spec = {
'min_len': 3,
'childs': (
(1, {'min_len': 2, 'childs': ()}),
(2, {
'min_len': 2,
'childs': (
(1, {'min_len': 2, 'childs': ()})
)
}
)
)
}
So finally the assignment above is converted into:
(a, (b, c), (d, (e, f))) = guarded_unpack_sequence(g, spec)
"""
spec = ast.Dict(keys=[], values=[])
spec.keys.append(ast.Str('childs'))
spec.values.append(ast.Tuple([], ast.Load()))
# starred elements in a sequence do not contribute into the min_len.
# For example a, b, *c = g
# g must have at least 2 elements, not 3. 'c' is empyt if g has only 2.
min_len = len([ob for ob in tpl.elts if not self.is_starred(ob)])
offset = 0
for idx, val in enumerate(tpl.elts):
# After a starred element specify the child index from the back.
# Since it is unknown how many elements from the sequence are
# consumed by the starred element.
# For example a, *b, (c, d) = g
# Then (c, d) has the index '-1'
if self.is_starred(val):
offset = min_len + 1
elif isinstance(val, ast.Tuple):
el = ast.Tuple([], ast.Load())
el.elts.append(ast.Num(idx - offset))
el.elts.append(self.gen_unpack_spec(val))
spec.values[0].elts.append(el)
spec.keys.append(ast.Str('min_len'))
spec.values.append(ast.Num(min_len))
return spec
def protect_unpack_sequence(self, target, value):
spec = self.gen_unpack_spec(target)
return ast.Call(
func=ast.Name('_unpack_sequence_', ast.Load()),
args=[value, spec, ast.Name('_getiter_', ast.Load())],
keywords=[])
def gen_unpack_wrapper(self, node, target, ctx='store'):
"""Helper function to protect tuple unpacks.
node: used to copy the locations for the new nodes.
target: is the tuple which must be protected.
ctx: Defines the context of the returned temporary node.
It returns a tuple with two element.
Element 1: Is a temporary name node which must be used to
replace the target.
The context (store, param) is defined
by the 'ctx' parameter..
Element 2: Is a try .. finally where the body performs the
protected tuple unpack of the temporary variable
into the original target.
"""
# Generate a tmp name to replace the tuple with.
tmp_name = self.gen_tmp_name()
# Generates an expressions which protects the unpack.
# converter looks like 'wrapper(tmp_name)'.
# 'wrapper' takes care to protect sequence unpacking with _getiter_.
converter = self.protect_unpack_sequence(
target,
ast.Name(tmp_name, ast.Load()))
# Assign the expression to the original names.
# Cleanup the temporary variable.
# Generates:
# try:
# # converter is 'wrapper(tmp_name)'
# arg = converter
# finally:
# del tmp_arg
try_body = [ast.Assign(targets=[target], value=converter)]
finalbody = [self.gen_del_stmt(tmp_name)]
if IS_PY2:
cleanup = ast.TryFinally(body=try_body, finalbody=finalbody)
else:
cleanup = ast.Try(
body=try_body, finalbody=finalbody, handlers=[], orelse=[])
if ctx == 'store':
ctx = ast.Store()
elif ctx == 'param':
ctx = ast.Param()
else: # pragma: no cover
# Only store and param are defined ctx.
raise NotImplementedError(
'Unsupported context type: "{name}".'.format(name=type(ctx)),
)
# This node is used to catch the tuple in a tmp variable.
tmp_target = ast.Name(tmp_name, ctx)
copy_locations(tmp_target, node)
copy_locations(cleanup, node)
return (tmp_target, cleanup)
def gen_none_node(self):
if IS_PY34_OR_GREATER:
return ast.NameConstant(value=None)
else:
return ast.Name(id='None', ctx=ast.Load())
def gen_lambda(self, args, body):
return ast.Lambda(
args=ast.arguments(
args=args, vararg=None, kwarg=None, defaults=[]),
body=body)
def gen_del_stmt(self, name_to_del):
return ast.Delete(targets=[ast.Name(name_to_del, ast.Del())])
def transform_slice(self, slice_):
"""Transform slices into function parameters.
ast.Slice nodes are only allowed within a ast.Subscript node.
To use a slice as an argument of ast.Call it has to be converted.
Conversion is done by calling the 'slice' function from builtins
"""
if isinstance(slice_, ast.Index):
return slice_.value
elif isinstance(slice_, ast.Slice):
# Create a python slice object.
args = []
if slice_.lower:
args.append(slice_.lower)
else:
args.append(self.gen_none_node())
if slice_.upper:
args.append(slice_.upper)
else:
args.append(self.gen_none_node())
if slice_.step:
args.append(slice_.step)
else:
args.append(self.gen_none_node())
return ast.Call(
func=ast.Name('slice', ast.Load()),
args=args,
keywords=[])
elif isinstance(slice_, ast.ExtSlice):
dims = ast.Tuple([], ast.Load())
for item in slice_.dims:
dims.elts.append(self.transform_slice(item))
return dims
else: # pragma: no cover
# Index, Slice and ExtSlice are only defined Slice types.
raise NotImplementedError("Unknown slice type: {0}".format(slice_))
def check_name(self, node, name, allow_magic_methods=False):
"""Check names if they are allowed.
If ``allow_magic_methods is True`` names in `ALLOWED_FUNC_NAMES`
are additionally allowed although their names start with `_`.
"""
if name is None:
return
if (name.startswith('_')
and name != '_'
and not (allow_magic_methods
and name in ALLOWED_FUNC_NAMES
and node.col_offset != 0)):
self.error(
node,
'"{name}" is an invalid variable name because it '
'starts with "_"'.format(name=name))
elif name.endswith('__roles__'):
self.error(node, '"%s" is an invalid variable name because '
'it ends with "__roles__".' % name)
elif name in FORBIDDEN_FUNC_NAMES:
self.error(node, '"{name}" is a reserved name.'.format(name=name))
def check_function_argument_names(self, node):
# In python3 arguments are always identifiers.
# In python2 the 'Python.asdl' specifies expressions, but
# the python grammer allows only identifiers or a tuple of
# identifiers. If its a tuple 'tuple parameter unpacking' is used,
# which is gone in python3.
# See https://www.python.org/dev/peps/pep-3113/
if IS_PY2:
# Needed to handle nested 'tuple parameter unpacking'.
# For example 'def foo((a, b, (c, (d, e)))): pass'
to_check = list(node.args.args)
while to_check:
item = to_check.pop()
if isinstance(item, ast.Tuple):
to_check.extend(item.elts)
else:
self.check_name(node, item.id)
self.check_name(node, node.args.vararg)
self.check_name(node, node.args.kwarg)
else:
for arg in node.args.args:
self.check_name(node, arg.arg)
if node.args.vararg:
self.check_name(node, node.args.vararg.arg)
if node.args.kwarg:
self.check_name(node, node.args.kwarg.arg)
for arg in node.args.kwonlyargs:
self.check_name(node, arg.arg)
def check_import_names(self, node):
"""Check the names being imported.
This is a protection against rebinding dunder names like
_getitem_, _write_ via imports.
=> 'from _a import x' is ok, because '_a' is not added to the scope.
"""
if (isinstance(node, ast.ImportFrom)
and not node.module == '__future__'
and any([name.startswith('_') for name in node.module.split('.')])): # NOQA: E501
self.error(node, 'module name starts "_", which is forbidden.')
for name in node.names:
if '*' in name.name:
self.error(node, '"*" imports are not allowed.')
self.check_name(node, name.name)
if name.asname:
self.check_name(node, name.asname)
return self.node_contents_visit(node)
def inject_print_collector(self, node, position=0):
print_used = self.print_info.print_used
printed_used = self.print_info.printed_used
if print_used or printed_used:
# Add '_print = _print_(_getattr_)' add the top of a
# function/module.
_print = ast.Assign(
targets=[ast.Name('_print', ast.Store())],
value=ast.Call(
func=ast.Name("_print_", ast.Load()),
args=[ast.Name("_getattr_", ast.Load())],
keywords=[]))
if isinstance(node, ast.Module):
_print.lineno = position
_print.col_offset = position
ast.fix_missing_locations(_print)
else:
copy_locations(_print, node)
node.body.insert(position, _print)
if not printed_used:
self.warn(node, "Prints, but never reads 'printed' variable.")
elif not print_used:
self.warn(node, "Doesn't print, but reads 'printed' variable.")
def gen_attr_check(self, node, attr_name):
"""Check if 'attr_name' is allowed on the object in node.
It generates (_getattr_(node, attr_name) and node).
"""
call_getattr = ast.Call(
func=ast.Name('_getattr_', ast.Load()),
args=[node, ast.Str(attr_name)],
keywords=[])
return ast.BoolOp(op=ast.And(), values=[call_getattr, node])
# Special Functions for an ast.NodeTransformer
def generic_visit(self, node):
"""Reject ast nodes which do not have a corresponding `visit_` method.
This is needed to prevent new ast nodes from new Python versions to be
trusted before any security review.
To access `generic_visit` on the super class use `node_contents_visit`.
"""
self.warn(
node,
'{0.__class__.__name__}'
' statement is not known to RestrictedPython'.format(node)
)
self.not_allowed(node)
def not_allowed(self, node):
self.error(
node,
'{0.__class__.__name__} statements are not allowed.'.format(node))
def node_contents_visit(self, node):
"""Visit the contents of a node."""
return super(RestrictingNodeTransformer, self).generic_visit(node)
# ast for Literals
def visit_Num(self, node):
"""Allow integer numbers without restrictions."""
return self.node_contents_visit(node)
def visit_Str(self, node):
"""Allow string literals without restrictions."""
return self.node_contents_visit(node)
def visit_Bytes(self, node):
"""Allow bytes literals without restrictions.
Bytes is Python 3 only.
"""
return self.node_contents_visit(node)
def visit_List(self, node):
"""Allow list literals without restrictions."""
return self.node_contents_visit(node)
def visit_Tuple(self, node):
"""Allow tuple literals without restrictions."""
return self.node_contents_visit(node)
def visit_Set(self, node):
"""Allow set literals without restrictions."""
return self.node_contents_visit(node)
def visit_Dict(self, node):
"""Allow dict literals without restrictions."""
return self.node_contents_visit(node)
def visit_Ellipsis(self, node):
"""Deny using `...`.
Ellipsis is exists only in Python 3.
"""
self.not_allowed(node)
def visit_NameConstant(self, node):
"""
"""
return self.node_contents_visit(node)
# ast for Variables
def visit_Name(self, node):
"""Prevents access to protected names.
Converts use of the name 'printed' to this expression: '_print()'
"""
node = self.node_contents_visit(node)
if isinstance(node.ctx, ast.Load):
if node.id == 'printed':
self.print_info.printed_used = True
new_node = ast.Call(
func=ast.Name("_print", ast.Load()),
args=[],
keywords=[])
copy_locations(new_node, node)
return new_node
elif node.id == 'print':
self.print_info.print_used = True
new_node = ast.Attribute(
value=ast.Name('_print', ast.Load()),
attr="_call_print",
ctx=ast.Load())
copy_locations(new_node, node)
return new_node
self.used_names[node.id] = True
self.check_name(node, node.id)
return node
def visit_Load(self, node):
"""
"""
return self.node_contents_visit(node)
def visit_Store(self, node):
"""
"""
return self.node_contents_visit(node)
def visit_Del(self, node):
"""
"""
return self.node_contents_visit(node)
def visit_Starred(self, node):
"""
"""
return self.node_contents_visit(node)
# Expressions
def visit_Expression(self, node):
"""Allow Expression statements without restrictions.
They are in the AST when using the `eval` compile mode.
"""
return self.node_contents_visit(node)
def visit_Expr(self, node):
"""Allow Expr statements (any expression) without restrictions."""
return self.node_contents_visit(node)
def visit_UnaryOp(self, node):
"""
UnaryOp (Unary Operations) is the overall element for:
* Not --> which should be allowed
* UAdd --> Positive notation of variables (e.g. +var)
* USub --> Negative notation of variables (e.g. -var)
"""
return self.node_contents_visit(node)
def visit_UAdd(self, node):
"""Allow positive notation of variables. (e.g. +var)"""
return self.node_contents_visit(node)
def visit_USub(self, node):
"""Allow negative notation of variables. (e.g. -var)"""
return self.node_contents_visit(node)
def visit_Not(self, node):
"""Allow the `not` operator."""
return self.node_contents_visit(node)
def visit_Invert(self, node):
"""Allow `~` expressions."""
return self.node_contents_visit(node)
def visit_BinOp(self, node):
"""Allow binary operations."""
return self.node_contents_visit(node)
def visit_Add(self, node):
"""Allow `+` expressions."""
return self.node_contents_visit(node)
def visit_Sub(self, node):
"""Allow `-` expressions."""
return self.node_contents_visit(node)
def visit_Mult(self, node):
"""Allow `*` expressions."""
return self.node_contents_visit(node)
def visit_Div(self, node):
"""Allow `/` expressions."""
return self.node_contents_visit(node)
def visit_FloorDiv(self, node):
"""Allow `//` expressions."""
return self.node_contents_visit(node)
def visit_Mod(self, node):
"""Allow `%` expressions."""
return self.node_contents_visit(node)
def visit_Pow(self, node):
"""Allow `**` expressions."""
return self.node_contents_visit(node)
def visit_LShift(self, node):
"""Allow `<<` expressions."""
return self.node_contents_visit(node)
def visit_RShift(self, node):
"""Allow `>>` expressions."""
return self.node_contents_visit(node)
def visit_BitOr(self, node):
"""Allow `|` expressions."""
return self.node_contents_visit(node)
def visit_BitXor(self, node):
"""Allow `^` expressions."""
return self.node_contents_visit(node)
def visit_BitAnd(self, node):
"""Allow `&` expressions."""
return self.node_contents_visit(node)
def visit_MatMult(self, node):
"""Matrix multiplication (`@`) is currently not allowed.
Matrix multiplication is a Python 3.5+ feature.
"""
self.not_allowed(node)
def visit_BoolOp(self, node):
"""Allow bool operator without restrictions."""
return self.node_contents_visit(node)
def visit_And(self, node):
"""Allow bool operator `and` without restrictions."""
return self.node_contents_visit(node)
def visit_Or(self, node):
"""Allow bool operator `or` without restrictions."""
return self.node_contents_visit(node)
def visit_Compare(self, node):
"""Allow comparison expressions without restrictions."""
return self.node_contents_visit(node)
def visit_Eq(self, node):
"""Allow == expressions."""
return self.node_contents_visit(node)
def visit_NotEq(self, node):
"""Allow != expressions."""
return self.node_contents_visit(node)
def visit_Lt(self, node):
"""Allow < expressions."""
return self.node_contents_visit(node)
def visit_LtE(self, node):
"""Allow <= expressions."""
return self.node_contents_visit(node)
def visit_Gt(self, node):
"""Allow > expressions."""
return self.node_contents_visit(node)
def visit_GtE(self, node):
"""Allow >= expressions."""
return self.node_contents_visit(node)
def visit_Is(self, node):
"""Allow `is` expressions."""
return self.node_contents_visit(node)
def visit_IsNot(self, node):
"""Allow `is not` expressions."""
return self.node_contents_visit(node)
def visit_In(self, node):
"""Allow `in` expressions."""
return self.node_contents_visit(node)
def visit_NotIn(self, node):
"""Allow `not in` expressions."""
return self.node_contents_visit(node)
def visit_Call(self, node):
"""Checks calls with '*args' and '**kwargs'.
Note: The following happens only if '*args' or '**kwargs' is used.
Transfroms 'foo(<all the possible ways of args>)' into
_apply_(foo, <all the possible ways for args>)
The thing is that '_apply_' has only '*args', '**kwargs', so it gets
Python to collapse all the myriad ways to call functions
into one manageable from.
From there, '_apply_()' wraps args and kws in guarded accessors,
then calls the function, returning the value.
"""
if isinstance(node.func, ast.Name):
if node.func.id == 'exec':
self.error(node, 'Exec calls are not allowed.')
elif node.func.id == 'eval':
self.error(node, 'Eval calls are not allowed.')
needs_wrap = False
# In python2.7 till python3.4 '*args', '**kwargs' have dedicated
# attributes on the ast.Call node.
# In python 3.5 and greater this has changed due to the fact that
# multiple '*args' and '**kwargs' are possible.
# '*args' can be detected by 'ast.Starred' nodes.
# '**kwargs' can be deteced by 'keyword' nodes with 'arg=None'.
if IS_PY35_OR_GREATER:
for pos_arg in node.args:
if isinstance(pos_arg, ast.Starred):
needs_wrap = True
for keyword_arg in node.keywords:
if keyword_arg.arg is None:
needs_wrap = True
else:
if (node.starargs is not None) or (node.kwargs is not None):
needs_wrap = True
node = self.node_contents_visit(node)
if not needs_wrap:
return node
node.args.insert(0, node.func)
node.func = ast.Name('_apply_', ast.Load())
copy_locations(node.func, node.args[0])
return node
def visit_keyword(self, node):
"""
"""
return self.node_contents_visit(node)
def visit_IfExp(self, node):
"""Allow `if` expressions without restrictions."""
return self.node_contents_visit(node)
def visit_Attribute(self, node):
"""Checks and mutates attribute access/assignment.
'a.b' becomes '_getattr_(a, "b")'
'a.b = c' becomes '_write_(a).b = c'
'del a.b' becomes 'del _write_(a).b'
The _write_ function should return a security proxy.
"""
if node.attr.startswith('_') and node.attr != '_':
self.error(
node,
'"{name}" is an invalid attribute name because it starts '
'with "_".'.format(name=node.attr))
if node.attr.endswith('__roles__'):
self.error(
node,
'"{name}" is an invalid attribute name because it ends '
'with "__roles__".'.format(name=node.attr))
if isinstance(node.ctx, ast.Load):
node = self.node_contents_visit(node)
new_node = ast.Call(
func=ast.Name('_getattr_', ast.Load()),
args=[node.value, ast.Str(node.attr)],
keywords=[])
copy_locations(new_node, node)
return new_node
elif isinstance(node.ctx, (ast.Store, ast.Del)):
node = self.node_contents_visit(node)
new_value = ast.Call(
func=ast.Name('_write_', ast.Load()),
args=[node.value],
keywords=[])
copy_locations(new_value, node.value)
node.value = new_value
return node
else: # pragma: no cover
# Impossible Case only ctx Load, Store and Del are defined in ast.
raise NotImplementedError(
"Unknown ctx type: {0}".format(type(node.ctx)))
# Subscripting
def visit_Subscript(self, node):
"""Transforms all kinds of subscripts.
'foo[bar]' becomes '_getitem_(foo, bar)'
'foo[:ab]' becomes '_getitem_(foo, slice(None, ab, None))'
'foo[ab:]' becomes '_getitem_(foo, slice(ab, None, None))'
'foo[a:b]' becomes '_getitem_(foo, slice(a, b, None))'
'foo[a:b:c]' becomes '_getitem_(foo, slice(a, b, c))'
'foo[a, b:c] becomes '_getitem_(foo, (a, slice(b, c, None)))'
'foo[a] = c' becomes '_write_(foo)[a] = c'
'del foo[a]' becomes 'del _write_(foo)[a]'
The _write_ function should return a security proxy.
"""
node = self.node_contents_visit(node)
# 'AugStore' and 'AugLoad' are defined in 'Python.asdl' as possible
# 'expr_context'. However, according to Python/ast.c
# they are NOT used by the implementation => No need to worry here.
# Instead ast.c creates 'AugAssign' nodes, which can be visited.
if isinstance(node.ctx, ast.Load):
new_node = ast.Call(
func=ast.Name('_getitem_', ast.Load()),
args=[node.value, self.transform_slice(node.slice)],
keywords=[])
copy_locations(new_node, node)
return new_node
elif isinstance(node.ctx, (ast.Del, ast.Store)):
new_value = ast.Call(
func=ast.Name('_write_', ast.Load()),
args=[node.value],
keywords=[])
copy_locations(new_value, node)
node.value = new_value
return node
else: # pragma: no cover
# Impossible Case only ctx Load, Store and Del are defined in ast.
raise NotImplementedError(
"Unknown ctx type: {0}".format(type(node.ctx)))
def visit_Index(self, node):
"""
"""
return self.node_contents_visit(node)
def visit_Slice(self, node):
"""
"""
return self.node_contents_visit(node)
def visit_ExtSlice(self, node):
"""
"""
return self.node_contents_visit(node)
# Comprehensions
def visit_ListComp(self, node):
"""
"""
return self.node_contents_visit(node)
def visit_SetComp(self, node):
"""
"""
return self.node_contents_visit(node)
def visit_GeneratorExp(self, node):
"""
"""
return self.node_contents_visit(node)
def visit_DictComp(self, node):
"""
"""
return self.node_contents_visit(node)
def visit_comprehension(self, node):