forked from oravirt/ansible-oracle-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oracle_grants
executable file
·646 lines (516 loc) · 23.1 KB
/
oracle_grants
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
#!/usr/bin/python
# -*- coding: utf-8 -*-
DOCUMENTATION = '''
---
module: oracle_grants
short_description: Manage users/schemas in an Oracle database
description:
- Manage grants/privileges in an Oracle database
- Handles role/sys privileges at the moment.
- It is possible to add object privileges as well, but they are not considered when removing privs at the moment.
version_added: "1.9.1"
options:
hostname:
description:
- The Oracle database host
required: false
default: localhost
port:
description:
- The listener port number on the host
required: false
default: 1521
service_name:
description:
- The database service name to connect to
required: true
user:
description:
- The Oracle user name to connect to the database
required: true
password:
description:
- The Oracle user password for 'user'
required: true
mode:
description:
- The mode with which to connect to the database
required: true
default: normal
choices: ['normal','sysdba']
schema:
description:
- The schema that should get grants added/removed
required: false
default: null
grants:
description:
- The privileges granted to the new schema. Can be a string or a list
required: false
default: null
object_privs:
description:
- The privileges granted to specific objects
- format: 'priv1,priv2,priv3:owner.object_name'
e.g:
- select,update,insert,delete:sys.dba_tablespaces
- select:sys.v_$session
required: false
default: null
state:
description:
- The intended state of the priv (present=added to the user, absent=removed from the user). REMOVEALL will remove ALL role/sys privileges
default: present
choices: ['present','absent','REMOVEALL']
notes:
- cx_Oracle needs to be installed
requirements: [ "cx_Oracle" ]
author: Mikael Sandström, oravirt@gmail.com, @oravirt
'''
EXAMPLES = '''
# Add grants to the user
oracle_grants: hostname=remote-db-server service_name=orcl user=system password=manager schema=myschema state=present grants='create session','create any table',connect,resource
# Revoke the 'create any table' grant
oracle_grants: hostname=localhost service_name=orcl user=system password=manager schema=myschema state=absent grants='create any table'
# Remove all grants from a user
oracle_grants: hostname=localhost service_name=orcl user=system password=manager schema=myschema state=REMOVEALL grants=
'''
try:
import cx_Oracle
except ImportError:
cx_oracle_exists = False
else:
cx_oracle_exists = True
def clean_string(item):
item = item.replace("'","").replace(", ",",").lstrip(" ").rstrip(",").replace("[","").replace("]","")
return item
def clean_list(item):
item = [p.replace("'","").replace(", ",",").lstrip(" ").rstrip(",").replace("[","").replace("]","") for p in item]
return item
# Check if the user/schema exists
def check_user_exists(module, msg, cursor, schema):
if not(schema):
module.fail_json(msg='Error: Missing schema name (User)', changed=False)
return False
schema = clean_string(schema)
sql = 'select count(*) from dba_users where username = upper(\'%s\')' % schema
try:
cursor.execute(sql)
result = cursor.fetchone()[0]
except cx_Oracle.DatabaseError, exc:
error, = exc.args
msg = error.message+ 'sql: ' + sql
return False
if result > 0:
return True
else:
msg = 'User doesn\'t exist'
return False
# Check if the user/role exists
def check_role_exists(module, msg, cursor, role):
if not(role):
module.fail_json(msg='Error: Missing role name', changed=False)
return False
role = clean_string(role)
sql = 'select role from dba_roles where role = upper(\'%s\')' % role
try:
cursor.execute(sql)
result = (cursor.fetchone())
except cx_Oracle.DatabaseError, exc:
error, = exc.args
msg = error.message+ 'sql: ' + sql
return False
if result > 0:
#module.exit_json(msg='(role) sql %s'% sql, changed=False)
return True
else:
msg = 'Role doesn\'t exist'
return False
def get_dir_privs(module, msg, cursor, schema, directory_privs):
total_sql_dir = []
# Directory Privs
# module.exit_json(msg=directory_privs)
wanted_dirprivs_list = directory_privs
w_object_name_l = [w.split(':')[1].lower() for w in wanted_dirprivs_list]
w_object_priv_l = [w.split(':')[0].lower() for w in wanted_dirprivs_list]
currdsql_all="""
select lower(listagg(p.privilege,',') within group (order by p.privilege) ||':'||p.owner||'.'||p.table_name)
from dba_tab_privs p, dba_objects o
where p.grantee = upper(\'%s\')
and p.table_name = o.object_name
and o.object_type = 'DIRECTORY'
group by p.owner,p.table_name
""" % (schema)
result = execute_sql_get(module, msg, cursor, currdsql_all)
grant_list_dir = []
revoke_list_dir = []
current_privs_l = [a[0] for a in result] # Turn list of tuples into list from resultset
c_dir_name_l = [ o.split(':')[1].lower() for o in current_privs_l]
c_dir_priv_l = [ o.split(':')[0].lower() for o in current_privs_l]
remove_completely_dir = set(c_dir_name_l).difference(w_object_name_l)
if len(list(remove_completely_dir)) > 0:
for remove in list(remove_completely_dir):
rdsql = 'revoke all on directory %s from %s' % (remove,schema)
revoke_list_dir.append(rdsql)
newstuff = set(w_object_name_l).difference(c_dir_name_l)
if len(list(newstuff)) > 0:
for index,value in enumerate(w_object_name_l):
if value in list(newstuff):
nsql = "grant %s on directory %s to %s" % (wanted_dirprivs_list[index].split(':')[0], value, schema)
grant_list_dir.append(nsql)
if len(current_privs_l) > 0 and len(wanted_dirprivs_list) > 0:
for cp in current_privs_l:
object_owner = cp.split(':').pop().split('.')[0]
object_name = cp.split(':').pop().split('.')[1]
cp_privs = cp.split(':')[0].lower()
for wp in wanted_dirprivs_list:
wp_object = wp.split(':')[1].lower()
if wp.split(':')[1].lower() == cp.split(':')[1].lower(): # Compare object_names
cp_privs = cp.split(':')[0].lower().split(',')
wp_privs = wp.split(':')[0].lower().split(',')
priv_add = set(wp_privs).difference(cp_privs)
priv_revoke = set(cp_privs).difference(wp_privs)
if len(list(priv_add)) > 0:
adsql = "grant %s on directory %s to %s" % (','.join(a for a in priv_add),wp_object,schema)
grant_list_dir.append(adsql)
if len(list(priv_revoke)) > 0:
rdsql = "revoke %s on directory %s from %s" % (','.join(a for a in priv_revoke),wp_object,schema)
revoke_list_dir.append(rdsql)
if len(grant_list_dir) > 0:
for a in grant_list_dir:
total_sql_dir.append(a)
if len(revoke_list_dir) > 0:
for a in revoke_list_dir:
total_sql_dir.append(a)
return total_sql_dir
def get_obj_privs (module, msg, cursor, schema, object_privs):
total_sql_obj = []
# OBJECT PRIVS
wanted_privs_list = object_privs
w_object_name_l = [w.split(':')[1].lower() for w in wanted_privs_list]
w_object_priv_l = [w.split(':')[0].lower() for w in wanted_privs_list]
currsql_all="""
select lower(listagg(p.privilege,',') within group (order by p.privilege) ||':'||p.owner||'.'||p.table_name)
from dba_tab_privs p, dba_objects o
where p.grantee = upper(\'%s\')
and p.table_name = o.object_name
and o.object_type != 'DIRECTORY'
group by p.owner,p.table_name
""" % (schema)
result = execute_sql_get(module, msg, cursor, currsql_all)
grant_list = []
revoke_list = []
current_privs_l = [a[0] for a in result] # Turn list of tuples into list from resultset
c_object_name_l = [ o.split(':')[1].lower() for o in current_privs_l]
c_object_priv_l = [ o.split(':')[0].lower() for o in current_privs_l]
remove_completely = set(c_object_name_l).difference(w_object_name_l)
if len(list(remove_completely)) > 0:
for remove in list(remove_completely):
rsql = 'revoke all on %s from %s' % (remove,schema)
revoke_list.append(rsql)
newstuff = set(w_object_name_l).difference(c_object_name_l)
if len(list(newstuff)) > 0:
for index,value in enumerate(w_object_name_l):
if value in list(newstuff):
nsql = "grant %s on %s to %s" % (wanted_privs_list[index].split(':')[0], value, schema)
grant_list.append(nsql)
if len(current_privs_l) > 0 and len(wanted_privs_list) > 0:
for cp in current_privs_l:
object_owner = cp.split(':').pop().split('.')[0]
object_name = cp.split(':').pop().split('.')[1]
cp_privs = cp.split(':')[0].lower()
for wp in wanted_privs_list:
wp_object = wp.split(':')[1].lower()
if wp.split(':')[1].lower() == cp.split(':')[1].lower(): # Compare object_names
cp_privs = cp.split(':')[0].lower().split(',')
wp_privs = wp.split(':')[0].lower().split(',')
priv_add = set(wp_privs).difference(cp_privs)
priv_revoke = set(cp_privs).difference(wp_privs)
if len(list(priv_add)) > 0:
asql = "grant %s on %s to %s" % (','.join(a for a in priv_add),wp_object,schema)
grant_list.append(asql)
if len(list(priv_revoke)) > 0:
rsql = "revoke %s on %s from %s" % (','.join(a for a in priv_revoke),wp_object,schema)
revoke_list.append(rsql)
if len(grant_list) > 0:
for a in grant_list:
total_sql_obj.append(a)
if len(revoke_list) > 0:
for a in revoke_list:
total_sql_obj.append(a)
return total_sql_obj
# Add grants to the schema/role
def ensure_grants(module, msg, cursor, schema, wanted_grants_list, object_privs, directory_privs):
add_sql = ''
remove_sql = ''
# If no privs are added, we set the 'wanted' lists to be empty.
if wanted_grants_list is None or wanted_grants_list == ['']:
wanted_grants_list = []
if object_privs is None or object_privs == ['']:
object_privs = []
if directory_privs is None or directory_privs == ['']:
directory_privs = []
# This list will hold all grants the user currently has
dir_privs = []
obj_privs = []
total_sql=[]
total_current=[]
dir_privs = get_dir_privs(module, msg, cursor, schema, directory_privs)
if len(dir_privs)>0:
for d in dir_privs:
total_sql.append(d)
obj_privs = get_obj_privs(module, msg, cursor, schema, object_privs)
if len(obj_privs)>0:
for o in obj_privs:
total_sql.append(o)
#module.exit_json(msg=total_sql)
exceptions_list=['DBA','RESOURCE','CONNECT']
if not(schema): # or not(wanted_grants_list):
module.fail_json(msg='Error: Missing schema/role name or grants', changed=False)
return False
# Strip the list of unnecessary quotes etc
wanted_grants_list = clean_list(wanted_grants_list)
wanted_grants_list_upper = [x.upper() for x in wanted_grants_list]
schema = clean_string(schema)
# Get the current role grants for the schema. If any are present, add them to the total
curr_role_grants=get_current_role_grants(module, msg, cursor, schema)
if any(curr_role_grants):
total_current.extend(curr_role_grants)
# Get the current sys privs for the schema. If any are present, add them to the total
# Special case: If DBA,CONNECT,RESOURCE roles are in the wanted_grants_list,
# we do not check for system_privileges.
if not any(x in exceptions_list for x in wanted_grants_list_upper):
curr_sys_grants=get_current_sys_grants(module, msg, cursor, schema)
if any(curr_sys_grants):
total_current.extend(curr_sys_grants)
# Get the difference between current grants and wanted grants
grants_to_add=set(wanted_grants_list).difference(total_current)
grants_to_remove=set(total_current).difference(wanted_grants_list)
# if there are differences, they will be added.
if not any(grants_to_add) and not any(grants_to_remove):
pass
#module.exit_json(msg="Nothing to do", changed=False)
else:
# Convert the list of grants to a string
if any(grants_to_add):
grants_to_add = ','.join(grants_to_add)
grants_to_add = clean_string(grants_to_add)
add_sql += 'grant %s to %s' % (grants_to_add, schema)
total_sql.append(add_sql)
if any(grants_to_remove):
grants_to_remove = ','.join(grants_to_remove)
grants_to_remove = clean_string(grants_to_remove)
remove_sql += 'revoke %s from %s' % (grants_to_remove, schema)
total_sql.append(remove_sql)
#module.exit_json(msg=total_sql)
if len(total_sql) > 0:
if ensure_grants_state_sql(module,msg,cursor,total_sql):
module.exit_json(msg=total_sql, changed=True)
else:
msg = 'Nothing to do'
module.exit_json(msg=msg, changed=False)
# return False
#return True
def ensure_grants_state_sql(module,msg,cursor,total_sql):
for a in total_sql:
execute_sql(module, msg, cursor, a)
return True
def execute_sql(module, msg, cursor, sql):
try:
cursor.execute(sql)
except cx_Oracle.DatabaseError, exc:
error, = exc.args
msg = 'Something went wrong while executing sql - %s sql: %s' % (error.message, sql)
module.fail_json(msg=msg, changed=False)
return False
return True
# Remove grants to the schema
def remove_grants(module, msg, cursor, schema, remove_grants_list, object_privs, state):
sql = ''
# This list will hold all grants/privs the user currently has
total_current=[]
if not(schema) or not(remove_grants_list):
module.fail_json(msg='Error: Missing schema name or grants', changed=False)
return False
# Strip the list of unnecessary quotes etc
remove_grants_list = clean_list(remove_grants_list)
schema = clean_string(schema)
# Get the current role grants for the schema.
# If any are present, add them to the total
curr_role_grants=get_current_role_grants(module, msg, cursor, schema)
if any(curr_role_grants):
total_current.extend(curr_role_grants)
# Get the current sys privs for the schema
# If any are present, add them to the total
curr_sys_grants=get_current_sys_grants(module, msg, cursor, schema)
if any(curr_sys_grants):
total_current.extend(curr_sys_grants)
# Get the difference between current grants and wanted grants
grants_to_remove=set(remove_grants_list).intersection(total_current)
# If state=REMOVEALL is used, all grants/privs will be removed
if state == 'REMOVEALL' and any(total_current):
remove_all = ','.join(total_current)
sql += 'revoke %s from %s' % (remove_all, schema)
msg = 'All privileges/grants (%s) are removed from schema/role %s' % (remove_all, schema)
try:
cursor.execute(sql)
except cx_Oracle.DatabaseError, exc:
error, = exc.args
msg = 'Something went wrong while removing all grants from the schema/role - %s sql: %s' % (error.message, sql)
return False
# if there are differences, they will be removed.
elif not any(grants_to_remove):
module.exit_json(msg="The schema/role (%s) doesn\'t have the grant(s) you want to remove" % schema, changed=False)
else:
# Convert the list of grants to a string & clean it
grants_to_remove = ','.join(grants_to_remove)
grants_to_remove = clean_string(grants_to_remove)
sql += 'revoke %s from %s' % (grants_to_remove, schema)
msg = 'The grant(s) (%s) successfully removed from the schema/role %s' % (grants_to_remove, schema)
try:
cursor.execute(sql)
except cx_Oracle.DatabaseError, exc:
error, = exc.args
msg = 'Blergh, something went wrong while removing grants from the schema/role - %s sql: %s' % (error.message, sql)
return False
return True
# Get the current role/sys grants
def get_current_role_grants(module, msg, cursor, schema):
curr_role_grants=[]
sql = 'select granted_role from dba_role_privs where grantee = upper(\'%s\') '% schema
try:
cursor.execute(sql)
result = cursor.fetchall()
except cx_Oracle.DatabaseError, exc:
error, = exc.args
msg = error.message+ 'sql: ' + sql
return False
#if result > 0:
for item in result:
curr_role_grants.append(item[0].lower())
return curr_role_grants
# Get the current sys grants
def get_current_sys_grants(module, msg, cursor, schema):
curr_sys_grants=[]
sql = 'select privilege from dba_sys_privs where grantee = upper(\'%s\') '% schema
try:
cursor.execute(sql)
result = cursor.fetchall()
except cx_Oracle.DatabaseError, exc:
error, = exc.args
msg = error.message+ 'sql: ' + sql
return False
#if result > 0:
for item in result:
curr_sys_grants.append(item[0].lower())
return curr_sys_grants
def execute_sql_get(module, msg, cursor, sql):
try:
cursor.execute(sql)
result = (cursor.fetchall())
except cx_Oracle.DatabaseError, exc:
error, = exc.args
msg = 'Something went wrong while executing sql_get - %s sql: %s' % (error.message, sql)
module.fail_json(msg=msg, changed=False)
return False
return result
def main():
msg = ['']
module = AnsibleModule(
argument_spec = dict(
hostname = dict(default='localhost'),
port = dict(default=1521),
service_name = dict(required=True),
user = dict(required=False),
password = dict(required=False, no_log=True),
mode = dict(default='normal', choices=["normal","sysdba"]),
schema = dict(default=None),
role = dict(default=None),
grants = dict(default=None, type="list"),
object_privs = dict(default=None, type="list",aliases=['objprivs']),
directory_privs = dict(default=None, type="list",aliases=['dirprivs']),
state = dict(default="present", choices=["present", "absent", "REMOVEALL"])
),
mutually_exclusive=[['schema', 'role']]
)
hostname = module.params["hostname"]
port = module.params["port"]
service_name = module.params["service_name"]
user = module.params["user"]
password = module.params["password"]
mode = module.params["mode"]
schema = module.params["schema"]
role = module.params["role"]
grants = module.params["grants"]
object_privs = module.params["object_privs"]
directory_privs = module.params["directory_privs"]
state = module.params["state"]
if not cx_oracle_exists:
module.fail_json(msg="The cx_Oracle module is required. 'pip install cx_Oracle' should do the trick. If cx_Oracle is installed, make sure ORACLE_HOME & LD_LIBRARY_PATH is set")
wallet_connect = '/@%s' % service_name
try:
if (not user and not password ): # If neither user or password is supplied, the use of an oracle wallet is assumed
if mode == 'sysdba':
connect = wallet_connect
conn = cx_Oracle.connect(wallet_connect, mode=cx_Oracle.SYSDBA)
else:
connect = wallet_connect
conn = cx_Oracle.connect(wallet_connect)
elif (user and password ):
if mode == 'sysdba':
dsn = cx_Oracle.makedsn(host=hostname, port=port, service_name=service_name)
connect = dsn
conn = cx_Oracle.connect(user, password, dsn, mode=cx_Oracle.SYSDBA)
else:
dsn = cx_Oracle.makedsn(host=hostname, port=port, service_name=service_name)
connect = dsn
conn = cx_Oracle.connect(user, password, dsn)
elif (not(user) or not(password)):
module.fail_json(msg='Missing username or password for cx_Oracle')
except cx_Oracle.DatabaseError, exc:
error, = exc.args
msg = 'Could not connect to database - %s, connect descriptor: %s' % (error.message, connect)
module.fail_json(msg=msg, changed=False)
cursor = conn.cursor()
if state == 'present' and schema:
if check_user_exists(module, msg, cursor, schema):
if ensure_grants(module, msg, cursor, schema, grants, object_privs, directory_privs):
#msg = 'The grant(s) (%s) have been added to %s successfully' % (grants, schema)
module.exit_json(msg=msg, changed=True)
else:
module.fail_json(msg=msg, changed=False)
else:
msg = 'Schema %s doesn\'t exist' % (schema)
module.fail_json(msg=msg, changed=False)
elif state == 'present' and role:
if check_role_exists(module, msg, cursor, role):
ensure_grants(module, msg, cursor, role, grants, object_privs,directory_privs)
#msg = 'The grant(s) (%s) have been added to %s successfully' % (grants, schema)
module.exit_json(msg=msg, changed=False)
# else:
# module.fail_json(msg=msg, changed=False)
else:
msg = 'Role %s doesn\'t exist' % (role)
module.fail_json(msg=msg, changed=False)
elif (state == 'absent' or state == 'REMOVEALL') and schema:
#module.exit_json(msg='absent & schema', changed=False)
if check_user_exists(module, msg, cursor, schema):
if remove_grants(module, msg, cursor, schema, grants, state):
#msg = 'The schema %s has been dropped successfully' % schema
module.exit_json(msg=msg, changed=True)
else:
module.exit_json(msg='The schema (%s) doesn\'t exist' % schema, changed=False)
elif (state == 'absent' or state == 'REMOVEALL') and role:
#module.exit_json(msg='absent & role', changed=False)
if check_role_exists(module, msg, cursor, role):
if remove_grants(module, msg, cursor, role, grants, state):
#msg = 'The schema %s has been dropped successfully' % schema
module.exit_json(msg=msg, changed=True)
else:
module.exit_json(msg='The role (%s) doesn\'t exist' % role, changed=False)
else:
module.fail_json(msg='Missing schema or role', changed=False)
module.fail_json(msg='Unknown object', changed=False)
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()