-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconfigurationHelper.py
222 lines (186 loc) · 6.62 KB
/
configurationHelper.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
#!/usr/bin/env python
from datetime import datetime
import argparse
from getpass import getpass
import sys
import logging
from contextlib import closing
from mysql.connector import connect
def DatabaseExists(user: str, password: str, database: str, host: str) -> None:
"""
"""
try:
with closing(
connect(
user=user,
password=password,
host=host,
database=database,
auth_plugin="mysql_native_password",
charset="utf8mb4",
collation="utf8mb4_unicode_ci",
)
) as connection:
test_db_query = "SELECT 1+1"
with closing(connection.cursor()) as cursor:
cursor.execute(test_db_query)
cursor.fetchall()
return True
except Exception as error:
if str(error) == "1049 (42000): Unknown database '%s'" % database:
return False
else:
raise error
def CreateDatabase(user: str, password: str, database: str, host: str) -> None:
"""
"""
try:
with closing(
connect(
user=user,
password=password,
host=host,
auth_plugin="mysql_native_password",
charset="utf8mb4",
collation="utf8mb4_unicode_ci",
)
) as connection:
create_db_query = "CREATE DATABASE IF NOT EXISTS %s;" % database
with closing(connection.cursor()) as cursor:
cursor.execute(create_db_query)
except Exception as error:
raise error
def CreateCredentialsTable(user: str, password: str, database: str, host: str) -> None:
"""
"""
with closing(
connect(
user=user,
password=password,
database=database,
host=host,
auth_plugin="mysql_native_password",
charset="utf8mb4",
collation="utf8mb4_unicode_ci",
)
) as connection:
create_table_query = """CREATE TABLE IF NOT EXISTS `credentials` (`id` int NOT NULL AUTO_INCREMENT, `shared_key` text NOT NULL, `hashing_salt` text NOT NULL, `createdAt` datetime DEFAULT NULL, PRIMARY KEY (`id`)) ;"""
with closing(connection.cursor()) as cursor:
cursor.execute(create_table_query)
return None
def SetKeys(user: str, password: str, database: str, host: str, key: str, salt: str) -> None:
"""
"""
with closing(
connect(
user=user,
password=password,
database=database,
host=host,
auth_plugin="mysql_native_password",
charset="utf8mb4",
collation="utf8mb4_unicode_ci",
)
) as connection:
set_keys_query = """INSERT INTO credentials(id, shared_key, hashing_salt, createdAt) VALUES(%s, %s, %s, %s) ON DUPLICATE KEY UPDATE shared_key=%s, hashing_salt=%s, createdAt=%s;"""
with closing(connection.cursor()) as cursor:
cursor.execute(set_keys_query, (1, key, salt, datetime.now(), key, salt, datetime.now(),))
connection.commit()
return None
def GetKeys(user: str, password: str, database: str, host: str) -> None:
"""
"""
with closing(
connect(
user=user,
password=password,
database=database,
host=host,
auth_plugin="mysql_native_password",
charset="utf8mb4",
collation="utf8mb4_unicode_ci",
)
) as connection:
get_keys_query = """SELECT shared_key, hashing_salt FROM credentials WHERE id = %s;"""
with closing(connection.cursor(dictionary=True)) as cursor:
cursor.execute(get_keys_query, (1,))
result = cursor.fetchall()
if len(result) < 1:
return {
"shared_key": "",
"hashing_salt": ""
}
else:
return result[0]
def main():
"""
"""
from settings import Configurations
db_name = Configurations.MYSQL_DATABASE
db_host = Configurations.MYSQL_HOST
db_user = Configurations.MYSQL_USER
parser = argparse.ArgumentParser()
parser.add_argument("--setkeys", help="Set shared-key and hashing-salt values", action="store_true")
parser.add_argument("--getkeys", help="Get shared-key and hashing-salt values", action="store_true")
args = parser.parse_args()
try:
host = input("Host [default = '%s']: " % db_host) or db_host
user = input("Username [default = '%s']: " % db_user) or db_user
database = input("Database [default = '%s']: " % db_name) or db_name
password = getpass()
if DatabaseExists(user=user, password=password, database=database, host=host):
pass
else:
decision = input("[!] Unknown database '%s'. Do you want to create database '%s'? [Y/n]: " % (database, database)) or "Y"
if str(decision) in ["Y", "y"]:
CreateDatabase(
user=user,
password=password,
database=database,
host=host
)
elif str(decision) in ["N", "n"]:
print("Ok, Bye!")
sys.exit(0)
else:
print("Unknown decision '%s'" % decision)
sys.exit(1)
CreateCredentialsTable(
user=user,
password=password,
database=database,
host=host
)
if args.setkeys:
keyPairs = GetKeys(
user=user,
password=password,
database=database,
host=host
)
key = input("Shared Key [default = '%s']:" % keyPairs["shared_key"]) or keyPairs["shared_key"]
salt = input("Hashing Salt [default = '%s']:" % keyPairs["hashing_salt"]) or keyPairs["hashing_salt"]
SetKeys(
user=user,
password=password,
database=database,
host=host,
salt=salt,
key=key
)
sys.exit(0)
elif args.getkeys:
keyPairs = GetKeys(
user=user,
password=password,
database=database,
host=host
)
print(keyPairs)
sys.exit(0)
except Exception as error:
logging.error(str(error))
sys.exit(1)
if __name__ == "__main__":
logging.basicConfig(level="INFO")
main()