Debian Codegraph @

ansible_collections/community/proxysql/plugins/module_utils/mysql.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), Jonathan Mainguy <[email protected]>, 2015
8 # Most of this was originally added by Sven Schliesing @muffl0n in the mysql_user.py module
9 #
10 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
11
12 from __future__ import (absolute_import, division, print_function)
13 __metaclass__ = type
14
15 import os
16 import configparser
17
18 from ansible.module_utils.basic import missing_required_lib
19 from hashlib import sha256
20 from os import urandom
21 from base64 import urlsafe_b64encode
22
23
24 MYSQL_IMP_ERR = None
25 try:
26 import pymysql as mysql_driver
27 _mysql_cursor_param = 'cursor'
28 HAS_MYSQL_PACKAGE = True
29 except ImportError:
30 try:
31 import MySQLdb as mysql_driver
32 _mysql_cursor_param = 'cursorclass'
33 HAS_MYSQL_PACKAGE = True
34 except ImportError:
35 MYSQL_IMP_ERR = 'Cannot find PyMySQL or mysqlclient library.'
36 HAS_MYSQL_PACKAGE = False
37 mysql_driver = None
38
39
40 def parse_from_mysql_config_file(cnf):
41 cp = configparser.ConfigParser()
42 cp.read(cnf)
43 return cp
44
45
46 def _version(cursor):
47 cursor.execute("select version();")
48 res = cursor.fetchone()
49
50 # 2.2.0-72-ge14accd
51 # 2.3.2-percona-1.1
52 raw_version = res.get('version()').split('-', 1)
53 _version = raw_version[0].split('.')
54
55 version = dict()
56 version['full'] = res.get('version()')
57 version['major'] = int(_version[0])
58 version['minor'] = int(_version[1])
59 version['release'] = int(_version[2])
60 version['suffix'] = raw_version[1] if len(raw_version) > 1 else None
61
62 return version
63
64
65 def mysql_connect(module, login_user=None, login_password=None, config_file='', ssl_cert=None,
66 ssl_key=None, ssl_ca=None, db=None, cursor_class=None,
67 connect_timeout=30, autocommit=False, config_overrides_defaults=False):
68 config = {}
69
70 if not HAS_MYSQL_PACKAGE:
71 module.fail_json(msg=missing_required_lib("pymysql or MySQLdb"), exception=MYSQL_IMP_ERR)
72
73 if module.params["login_port"] < 0 \
74 or module.params["login_port"] > 65535:
75 module.fail_json(
76 msg="login_port must be a valid unix port number (0-65535)"
77 )
78
79 if config_file and os.path.exists(config_file):
80 config['read_default_file'] = config_file
81 cp = parse_from_mysql_config_file(config_file)
82 # Override some commond defaults with values from config file if needed
83 if cp and cp.has_section('client') and config_overrides_defaults:
84 try:
85 module.params['login_host'] = cp.get('client', 'host', fallback=module.params['login_host'])
86 module.params['login_port'] = cp.getint('client', 'port', fallback=module.params['login_port'])
87 except Exception as e:
88 if "got an unexpected keyword argument 'fallback'" in e.message:
89 module.fail_json('To use config_overrides_defaults, '
90 'it needs Python 3.5+ as the default interpreter on a target host')
91
92 if ssl_ca is not None or ssl_key is not None or ssl_cert is not None:
93 config['ssl'] = {}
94
95 if module.params['login_unix_socket']:
96 config['unix_socket'] = module.params['login_unix_socket']
97 else:
98 config['host'] = module.params['login_host']
99 config['port'] = module.params['login_port']
100
101 # If login_user or login_password are given, they should override the
102 # config file
103 if login_user is not None:
104 config['user'] = login_user
105 if login_password is not None:
106 config['passwd'] = login_password
107 if ssl_cert is not None:
108 config['ssl']['cert'] = ssl_cert
109 if ssl_key is not None:
110 config['ssl']['key'] = ssl_key
111 if ssl_ca is not None:
112 config['ssl']['ca'] = ssl_ca
113 if db is not None:
114 config['db'] = db
115 if connect_timeout is not None:
116 config['connect_timeout'] = connect_timeout
117
118 if _mysql_cursor_param == 'cursor':
119 # In case of PyMySQL driver:
120 db_connection = mysql_driver.connect(autocommit=autocommit, **config)
121 else:
122 # In case of MySQLdb driver
123 db_connection = mysql_driver.connect(**config)
124 if autocommit:
125 db_connection.autocommit(True)
126
127 version = _version(db_connection.cursor(**{_mysql_cursor_param: mysql_driver.cursors.DictCursor}))
128
129 if cursor_class == 'DictCursor':
130 return (db_connection.cursor(**{_mysql_cursor_param: mysql_driver.cursors.DictCursor}),
131 db_connection,
132 version)
133 else:
134 return (db_connection.cursor(),
135 db_connection,
136 version)
137
138
139 def proxysql_common_argument_spec():
140 return dict(
141 login_user=dict(type='str', default=None),
142 login_password=dict(type='str', no_log=True),
143 login_host=dict(type='str', default='127.0.0.1'),
144 login_port=dict(type='int', default=6032),
145 login_unix_socket=dict(type='str'),
146 config_file=dict(type='path', default=''),
147 )
148
149
150 def save_config_to_disk(cursor, save_what, variable=None):
151 if variable and variable.startswith("admin"):
152 config_type = "ADMIN"
153 elif variable and variable.startswith("pgsql"):
154 config_type = "PGSQL"
155 elif save_what == "SCHEDULER":
156 config_type = ""
157 else:
158 config_type = "MYSQL"
159
160 cursor.execute("SAVE {0} {1} TO DISK".format(config_type, save_what))
161
162 return True
163
164
165 def load_config_to_runtime(cursor, save_what, variable=None):
166 if variable and variable.startswith("admin"):
167 config_type = "ADMIN"
168 elif variable and variable.startswith("pgsql"):
169 config_type = "PGSQL"
170 elif save_what == "SCHEDULER":
171 config_type = ""
172 else:
173 config_type = "MYSQL"
174
175 cursor.execute("LOAD {0} {1} TO RUNTIME".format(config_type, save_what))
176
177 return True
178
179
180 # Imported code from @Aohzan
181 # community.mysql/plugins/module_utils/implementations/mysql/hash.py
182 def _to64(v, n):
183 """Convert a 32-bit integer to a base-64 string"""
184 i64 = (
185 [".", "/"]
186 + [chr(x) for x in range(48, 58)]
187 + [chr(x) for x in range(65, 91)]
188 + [chr(x) for x in range(97, 123)]
189 )
190 result = ""
191 while n > 0:
192 n -= 1
193 result += i64[v & 0x3F]
194 v >>= 6
195 return result
196
197
198 def _hashlib_sha256(data):
199 """Return SHA-256 digest from hashlib ."""
200 return sha256(data).digest()
201
202
203 def _sha256_digest(key, salt, loops):
204 """Return a SHA-256 digest of the concatenation of the key, the salt, and the key, repeated as necessary."""
205 # https://www.akkadia.org/drepper/SHA-crypt.txt
206 num_bytes = 32
207 bytes_key = key.encode()
208 bytes_salt = salt.encode()
209 digest_b = _hashlib_sha256(bytes_key + bytes_salt + bytes_key)
210
211 tmp = bytes_key + bytes_salt
212 for i in range(len(bytes_key), 0, -num_bytes):
213 tmp += digest_b if i > num_bytes else digest_b[:i]
214
215 i = len(bytes_key)
216 while i > 0:
217 tmp += digest_b if (i & 1) != 0 else bytes_key
218 i >>= 1
219
220 digest_a = _hashlib_sha256(tmp)
221
222 tmp = b""
223 for i in range(len(bytes_key)):
224 tmp += bytes_key
225
226 digest_dp = _hashlib_sha256(tmp)
227
228 byte_sequence_p = b""
229 for i in range(len(bytes_key), 0, -num_bytes):
230 byte_sequence_p += digest_dp if i > num_bytes else digest_dp[:i]
231
232 tmp = b""
233 til = 16 + digest_a[0]
234
235 for i in range(til):
236 tmp += bytes_salt
237
238 digest_ds = _hashlib_sha256(tmp)
239
240 byte_sequence_s = b""
241 for i in range(len(bytes_salt), 0, -num_bytes):
242 byte_sequence_s += digest_ds if i > num_bytes else digest_ds[:i]
243
244 digest_c = digest_a
245
246 for i in range(loops):
247 tmp = byte_sequence_p if (i & 1) else digest_c
248 if i % 3:
249 tmp += byte_sequence_s
250 if i % 7:
251 tmp += byte_sequence_p
252 tmp += digest_c if (i & 1) else byte_sequence_p
253 digest_c = _hashlib_sha256(tmp)
254
255 inc1, inc2, mod, end = (10, 21, 30, 0)
256
257 i = 0
258 tmp = ""
259
260 while True:
261 tmp += _to64(
262 (digest_c[i] << 16)
263 | (digest_c[(i + inc1) % mod] << 8)
264 | digest_c[(i + inc1 * 2) % mod],
265 4,
266 )
267 i = (i + inc2) % mod
268 if i == end:
269 break
270
271 tmp += _to64((digest_c[31] << 8) | digest_c[30], 3)
272
273 return tmp
274
275
276 def mysql_sha256_password_hash(password, salt):
277 """Return a MySQL compatible caching_sha2_password hash in raw format."""
278 if len(salt) != 20:
279 raise ValueError("Salt must be 20 characters long.")
280
281 count = 5
282 iteration = 1000 * count
283
284 digest = _sha256_digest(password, salt, iteration)
285 return "$A${0:>03}${1}{2}".format(count, salt, digest)
286
287
288 def mysql_sha256_password_hash_hex(password, salt):
289 """Return a MySQL compatible caching_sha2_password hash in hex format."""
290 return mysql_sha256_password_hash(password, salt).encode().hex().upper()
291
292 # End Imported code from @Aohzan
293
294
295 def generate_random_salt(length=20):
296 salt = urlsafe_b64encode(urandom(length)).decode('utf-8')
297 return salt[:length]