Debian Codegraph @

wxgeometrie/pylib/securite.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 # -*- coding: utf-8 -*-
2
3 ##########################################################################
4 #
5 # Gestion de la securite
6 #
7 ##########################################################################
8 # WxGeometrie
9 # Dynamic geometry, graph plotter, and more for french mathematic teachers.
10 # Copyright (C) 2005-2013 Nicolas Pourcelot
11 #
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2 of the License, or
15 # (at your option) any later version.
16 #
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # GNU General Public License for more details.
21 #
22 # You should have received a copy of the GNU General Public License
23 # along with this program; if not, write to the Free Software
24 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26 import keyword, re, types
27 import math # pour avoir droit aux fonctions mathematiques dans eval_restricted par defaut.
28 import random as module_random# idem
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 #fonctions_interdites = ["eval", "compile", "execfile", "file", "open", "write", "getattr", "setattr"]
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 ##keywords = ('and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield')
69
70 ### mots clés qui peuvent être utilisés
71 ##keywords_autorises = set('and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'if', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield')
72
73 keywords = set(keyword.kwlist)
74
75 # mots clés dont il faut s'assurer qu'ils ne puissent PAS être utilisés
76 keywords_interdits = set(('exec', 'global', 'import')) # attention à global !
77
78 # mots clés qui peuvent être utilisés
79 keywords_autorises = keywords.difference(keywords_interdits)
80
81 ### ici, il s'agit de mots clés qui doivent rester en début de ligne
82 ### (plus précisément, il est impossible de rajouter devant une affectation, style 'variable = ').
83 ##keywords_debut_ligne = ('break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'pass', 'for', 'if', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield')
84
85 # Mots clés devant lesquels il est possible de rajouter une affectation, style 'variable = ...'.
86 keywords_affectables = set(('lambda', 'not'))
87 # Mots clés qui ne sont jamais en début de ligne.
88 keywords_milieu = set(('or', 'and', 'as', 'in'))
89 # Les autres, qui doivent rester en tête de ligne.
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 # Exemple d'usage :
100 # dico = {"pi":3.1415926535897931, "e":2.7182818284590451} # dictionnaire local
101 # dico.update(securite.dictionnaire_builtins)
102 # exec(string, dico)
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) # supprime certaines fonctions par defaut (en les redefinissant)
115 dico.update(ajouts_math) # ajoute les fonctions mathematiques usuelles
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": # entier
148 return int(s)
149
150 if filtre(s, "-+.e0-9"): # flottant
151 return float(s)
152
153 if len(s) > 1 and s[0] == s[-1] and s[0] in ("'", '"'): # chaine
154 # s est évalué dans un contexte parfaitement vierge.
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 ("'", '"'): #unicode
158 return eval(s, {"__builtins__": {}}, {"__builtins__": {}}) # idem
159
160 if s == "None":
161 return None
162
163 if s == "True":
164 # Eviter return eval(s), car True peut etre redefini. Exemple : True = False (!)
165 return True
166
167 if s == "False":
168 return False
169
170 if s[0] in ("(", "["): # tuple ou liste
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] == "{": # dictionnaire
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))