| 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 |
import keyword, re, types |
| 27 |
import math |
| 28 |
import random as module_random |
| 29 |
|
| 30 |
from ..pylib import advanced_split |
| 31 |
from .. import param |
| 32 |
|
| 33 |
|
| 34 |
def _avertissement(*arg, **kw): |
| 35 |
print("Instruction interdite en mode securisé.") |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
liste_blanche = set(('False', 'None', 'True', 'abs', 'all', 'any', 'bool', 'callable', 'chr', 'close', \ |
| 40 |
'coerce', 'complex', 'dict', 'divmod', 'enumerate', 'filter', 'float', 'frozenset', 'globals', 'hash', 'hex', \ |
| 41 |
'id', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct', \ |
| 42 |
'ord', 'pow', 'range', 'repr', 'reversed', 'round', 'set', 'slice', 'sorted', 'str', 'sum', \ |
| 43 |
'tuple', 'type', 'zip'\ |
| 44 |
'IndexError', 'SyntaxError', 'NameError', 'StandardError', 'UnicodeDecodeError', 'RuntimeWarning', \ |
| 45 |
'Warning', 'FloatingPointError', 'FutureWarning', 'ImportWarning', 'TypeError', 'KeyboardInterrupt', \ |
| 46 |
'UserWarning', 'SystemError', 'BaseException', 'RuntimeError', 'GeneratorExit', 'StopIteration', \ |
| 47 |
'LookupError', 'UnicodeError', 'IndentationError', 'Exception', 'UnicodeTranslateError', 'UnicodeEncodeError', \ |
| 48 |
'PendingDeprecationWarning', 'ArithmeticError', 'MemoryError', 'ImportError', 'KeyError', 'SyntaxWarning', \ |
| 49 |
'EnvironmentError', 'OSError', 'DeprecationWarning', 'UnicodeWarning', 'ValueError', 'NotImplemented', \ |
| 50 |
'TabError', 'ZeroDivisionError', 'ReferenceError', 'AssertionError', 'UnboundLocalError', 'NotImplementedError', \ |
| 51 |
'AttributeError', 'OverflowError', 'WindowsError')) |
| 52 |
|
| 53 |
liste_noire = set(__builtins__.keys()) |
| 54 |
liste_noire.difference_update(liste_blanche) |
| 55 |
|
| 56 |
dictionnaire_builtins = {}.fromkeys(list(liste_noire), _avertissement) |
| 57 |
dictionnaire_modules = {}.fromkeys([key for key, objet in globals().items() if type(objet) == types.ModuleType]) |
| 58 |
|
| 59 |
ajouts_math = {"pi": math.pi, "e": math.e, "i": 1j} |
| 60 |
for key, obj in math.__dict__.items(): |
| 61 |
if type(obj) == types.BuiltinFunctionType: |
| 62 |
ajouts_math[key] = obj |
| 63 |
|
| 64 |
for key, obj in module_random.__dict__.items(): |
| 65 |
if type(obj) == types.BuiltinFunctionType: |
| 66 |
ajouts_math[key] = obj |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
és |
| 71 |
|
| 72 |
|
| 73 |
keywords = set(keyword.kwlist) |
| 74 |
|
| 75 |
és |
| 76 |
keywords_interdits = set(('exec', 'global', 'import')) ! |
| 77 |
|
| 78 |
és |
| 79 |
keywords_autorises = keywords.difference(keywords_interdits) |
| 80 |
|
| 81 |
ne |
| 82 |
). |
| 83 |
|
| 84 |
|
| 85 |
. |
| 86 |
keywords_affectables = set(('lambda', 'not')) |
| 87 |
e. |
| 88 |
keywords_milieu = set(('or', 'and', 'as', 'in')) |
| 89 |
. |
| 90 |
keywords_non_affectables = keywords.difference(keywords_affectables).difference(keywords_milieu) |
| 91 |
|
| 92 |
def keywords_interdits_presents(chaine): |
| •93 |
return bool(re.search(r'(?<!\w)(' + '|'.join(keywords_interdits) + r')(?!\w)', chaine)) |
| 94 |
|
| 95 |
def expression_affectable(chaine): |
| •96 |
return not bool(re.match('[ ]*(' + '|'.join(keywords_non_affectables) + r')(?!\w)', chaine)) |
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
def eval_restricted(s, dico_perso = None): |
| 105 |
"""eval_restricted(s) évalue s dans un contexte vierge et légèrement sécurisé. |
| 106 |
|
| 107 |
Toutes les fonctions disponibles par défaut sont filtrées. |
| 108 |
|
| 109 |
Note: eval_restricted est le plus securisée possible, mais contrairement |
| 110 |
à eval_safe, il utilise la fonction eval ; il existe donc forcément des |
| 111 |
failles de sécurité. |
| 112 |
""" |
| 113 |
dico = {"rand": module_random.random} |
| 114 |
dico.update(dictionnaire_builtins) |
| 115 |
dico.update(ajouts_math) |
| 116 |
if dico_perso is not None: |
| 117 |
dico.update(dico_perso) |
| 118 |
for module in ("os", "sys", "securite"): |
| 119 |
dico.pop(module, None) |
| 120 |
return eval(s, dico) |
| 121 |
|
| 122 |
|
| 123 |
def eval_safe(s): |
| 124 |
"""eval_safe(repr(x)) retourne x pour les types les plus usuels |
| 125 |
(int, str, float, bool, None, list, tuple, dict.) |
| 126 |
Mais aucune évaluation n'est faite, ce qui évite d'éxécuter un code dangereux. |
| 127 |
Le type de s est detecté, et la transformation appropriée appliquée. |
| 128 |
|
| 129 |
NB1: eval_safe n'est pas destiné à remplacer eval : |
| 130 |
- il est relativement lent, |
| 131 |
- le nombre de types supportés est volontairement réduit, |
| 132 |
- il n'est pas souple (eval_safe("2-3") renvoie une erreur). |
| 133 |
La fonction eval_safe est orientée uniquement securité. |
| 134 |
|
| 135 |
NB2: eval_safe est récursif (il peut lire des listes de tuples de ...). |
| 136 |
|
| 137 |
NB3: eval_safe est parfaitement securisé, car il ne fait (presque) jamais appel à une instruction eval. |
| 138 |
Contrairement à la fonction eval_restricted, qui est 'légèrement' securisée.""" |
| 139 |
|
| 140 |
s = s.strip() |
| 141 |
|
| 142 |
def filtre(chaine, caracteres): |
| 143 |
return re.match("^[%s]*$" %caracteres, chaine) is not None |
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
if filtre(s, "-0-9") or s[-1] == "L": |
| 148 |
return int(s) |
| 149 |
|
| 150 |
if filtre(s, "-+.e0-9"): |
| 151 |
return float(s) |
| 152 |
|
| 153 |
if len(s) > 1 and s[0] == s[-1] and s[0] in ("'", '"'): |
| 154 |
e. |
| 155 |
return eval(s, {"__builtins__": {}}, {"__builtins__": {}}) |
| 156 |
|
| 157 |
if len(s) > 2 and s[0] == "u" and s[1] == s[-1] and s[1] in ("'", '"'): |
| 158 |
return eval(s, {"__builtins__": {}}, {"__builtins__": {}}) |
| 159 |
|
| 160 |
if s == "None": |
| 161 |
return None |
| 162 |
|
| 163 |
if s == "True": |
| 164 |
|
| 165 |
return True |
| 166 |
|
| 167 |
if s == "False": |
| 168 |
return False |
| 169 |
|
| 170 |
if s[0] in ("(", "["): |
| 171 |
liste = [eval_safe(t) for t in advanced_split(s[1:-1], ",") if t] |
| 172 |
if s[0] == "(": |
| 173 |
liste = tuple(liste) |
| 174 |
return liste |
| 175 |
|
| 176 |
if s[0] == "{": |
| 177 |
dict = {} |
| 178 |
liste = [advanced_split(t, ":") for t in advanced_split(s[1:-1], ",") if t] |
| 179 |
for key, val in liste: |
| 180 |
dict[eval_safe(key)] = eval_safe(val) |
| 181 |
return dict |
| 182 |
|
| 183 |
|
| 184 |
raise TypeError("%s: types int, str, float, bool, ou None requis (ou liste ou tuple de ces types)" % repr(s)) |