Debian Codegraph @

ansible_collections/community/postgresql/plugins/module_utils/database.py

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # Copyright (c) 2014, Toshio Kuratomi <[email protected]>
8 #
9 # Simplified BSD License (see simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
10
11 from __future__ import absolute_import, division, print_function
12
13 __metaclass__ = type
14
15 import re
16
17 from ansible.module_utils.common.text.converters import to_native
18
19 # Input patterns for is_input_dangerous function:
20 #
21 # 1. '"' in string and '--' in string or
22 # "'" in string and '--' in string
23 PATTERN_1 = re.compile(r'(\'|\").*--')
24
25 # 2. union \ intersect \ except + select
26 PATTERN_2 = re.compile(r'(UNION|INTERSECT|EXCEPT).*SELECT', re.IGNORECASE)
27
28 # 3. ';' and any KEY_WORDS
29 PATTERN_3 = re.compile(r';.*(SELECT|UPDATE|INSERT|DELETE|DROP|TRUNCATE|ALTER)', re.IGNORECASE)
30
31
32 class SQLParseError(Exception):
33 pass
34
35
36 class UnclosedQuoteError(SQLParseError):
37 pass
38
39
40 # maps a type of identifier to the maximum number of dot levels that are
41 # allowed to specify that identifier. For example, a database column can be
42 # specified by up to 4 levels: database.schema.table.column
43 _PG_IDENTIFIER_TO_DOT_LEVEL = dict(
44 database=1,
45 schema=2,
46 table=3,
47 column=4,
48 role=1,
49 tablespace=1,
50 sequence=3,
51 publication=1,
52 )
53 _MYSQL_IDENTIFIER_TO_DOT_LEVEL = dict(database=1, table=2, column=3, role=1, vars=1)
54
55
56 def _find_end_quote(identifier, quote_char):
57 accumulate = 0
58 while True:
59 try:
60 quote = identifier.index(quote_char)
61 except ValueError:
62 raise UnclosedQuoteError
63 accumulate = accumulate + quote
64 try:
65 next_char = identifier[quote + 1]
66 except IndexError:
67 return accumulate
68 if next_char == quote_char:
69 try:
70 identifier = identifier[quote + 2:]
71 accumulate = accumulate + 2
72 except IndexError:
73 raise UnclosedQuoteError
74 else:
75 return accumulate
76
77
78 def _identifier_parse(identifier, quote_char):
79 if not identifier:
80 raise SQLParseError('Identifier name unspecified or unquoted trailing dot')
81
82 already_quoted = False
83 if identifier.startswith(quote_char):
84 already_quoted = True
85 try:
86 end_quote = _find_end_quote(identifier[1:], quote_char=quote_char) + 1
87 except UnclosedQuoteError:
88 already_quoted = False
89 else:
90 if end_quote < len(identifier) - 1:
91 if identifier[end_quote + 1] == '.':
92 dot = end_quote + 1
93 first_identifier = identifier[:dot]
94 next_identifier = identifier[dot + 1:]
95 further_identifiers = _identifier_parse(next_identifier, quote_char)
96 further_identifiers.insert(0, first_identifier)
97 else:
98 raise SQLParseError('User escaped identifiers must escape extra quotes')
99 else:
100 further_identifiers = [identifier]
101
102 if not already_quoted:
103 try:
104 dot = identifier.index('.')
105 except ValueError:
106 identifier = identifier.replace(quote_char, quote_char * 2)
107 identifier = ''.join((quote_char, identifier, quote_char))
108 further_identifiers = [identifier]
109 else:
110 if dot == 0 or dot >= len(identifier) - 1:
111 identifier = identifier.replace(quote_char, quote_char * 2)
112 identifier = ''.join((quote_char, identifier, quote_char))
113 further_identifiers = [identifier]
114 else:
115 first_identifier = identifier[:dot]
116 next_identifier = identifier[dot + 1:]
117 further_identifiers = _identifier_parse(next_identifier, quote_char)
118 first_identifier = first_identifier.replace(quote_char, quote_char * 2)
119 first_identifier = ''.join((quote_char, first_identifier, quote_char))
120 further_identifiers.insert(0, first_identifier)
121
122 return further_identifiers
123
124
125 def pg_quote_identifier(identifier, id_type):
126 identifier_fragments = _identifier_parse(identifier, quote_char='"')
127 if len(identifier_fragments) > _PG_IDENTIFIER_TO_DOT_LEVEL[id_type]:
128 raise SQLParseError('PostgreSQL does not support %s with more than %i dots' % (id_type, _PG_IDENTIFIER_TO_DOT_LEVEL[id_type]))
129 return '.'.join(identifier_fragments)
130
131
132 def mysql_quote_identifier(identifier, id_type):
133 identifier_fragments = _identifier_parse(identifier, quote_char='`')
134 if (len(identifier_fragments) - 1) > _MYSQL_IDENTIFIER_TO_DOT_LEVEL[id_type]:
135 raise SQLParseError('MySQL does not support %s with more than %i dots' % (id_type, _MYSQL_IDENTIFIER_TO_DOT_LEVEL[id_type]))
136
137 special_cased_fragments = []
138 for fragment in identifier_fragments:
139 if fragment == '`*`':
140 special_cased_fragments.append('*')
141 else:
142 special_cased_fragments.append(fragment)
143
144 return '.'.join(special_cased_fragments)
145
146
147 def is_input_dangerous(string):
148 """Check if the passed string is potentially dangerous.
149 Can be used to prevent SQL injections.
150
151 Note: use this function only when you can't use
152 psycopg's cursor.execute method parametrized
153 (typically with DDL queries).
154 """
155 if not string:
156 return False
157
158 for pattern in (PATTERN_1, PATTERN_2, PATTERN_3):
159 if re.search(pattern, string):
160 return True
161
162 return False
163
164
165 def _check_input(module, *args):
166 """Recursively checks arguments for dangerous inputs."""
167 needs_to_check = args
168
169 dangerous_elements = []
170
171 for elem in needs_to_check:
172 try:
173 if isinstance(elem, str):
174 if is_input_dangerous(elem):
175 dangerous_elements.append(elem)
176
177 elif isinstance(elem, list) or isinstance(elem, tuple):
178 for e in elem:
179 # check recursively in case of nested lists
180 dangerous_elements += _check_input(module, e)
181
182 elif isinstance(elem, dict):
183 for k, v in elem.items():
184 if is_input_dangerous(k):
185 dangerous_elements.append(k)
186 # recursively check values, as they might be dicts, as well
187 dangerous_elements += _check_input(module, v)
188
189 elif elem is None or isinstance(elem, bool):
190 pass
191
192 else:
193 elem = str(elem)
194 if is_input_dangerous(elem):
195 dangerous_elements.append(elem)
196 except ValueError as e:
197 module.fail_json(msg=to_native(e))
198
199 return dangerous_elements
200
201
202 def check_input(module, *args):
203 """Wrapper for is_input_dangerous function."""
204
205 dangerous_elements = _check_input(module, *args)
206 if dangerous_elements:
207 module.fail_json(msg="Passed input '%s' is potentially dangerous" % ', '.join(dangerous_elements))