-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecretserver.py
1368 lines (1275 loc) · 64.4 KB
/
secretserver.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
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# Copyright: (c) This module was created in 2024 by the IT-Services Office of the University of Bern
# MIT License
from __future__ import (absolute_import, division, print_function)
from typing import List, Dict, Union
__metaclass__ = type
import json
import datetime
import copy
import requests
from ansible.module_utils.common.text.converters import to_text
from ansible.module_utils.basic import AnsibleModule
DOCUMENTATION = r'''
---
module: secretserver
short_description: Reads and writes to a Thycotic Secret Server instance
version_added: "1.0.0"
description: This module allows you to interact with an Instance of a Thycotic (formerly Delinea) Secret Server
To execute this module, the host it is running on must be cleared to access the Secret Server by both the Firewall
and the ACL. This is why you see `delegate_to` used extensively in the examples.
You can test if your system can reach the Secret Server by doing
`curl -X POST "https://secretserver.example.com/SecretServer/oauth2/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Accept: */*" \
--data-urlencode "grant_type=password" \
--data-urlencode "username=$USERNAME" \
--data-urlencode "password=$PASSWORD`
options:
secretserver_password:
description: The Password you use to authenticate to the Secret Server.
You must specify either the secretserver_token or the secretserver_password.
If both are specified, the token takes precedence.
required: false
type: str
secretserver_token:
description: The Token you use to authenticate to the Secret Server.
You must specify either the secretserver_token or the secretserver_password.
If both are specified, the token takes precedence.
You can get a Token by going to the Web UI,
clicking the badge on the top right and navigating to "User Preferences".
At the bottom of the page, you have the option to "Generate API Token and Copy to Clipboard"
required: false
type: str
secretserver_username:
description: The Username you use to authenticate to the Secret Server.
required: true
type: str
secretserver_base_url:
description: The Base URL of your Secret Server Instance
If your Web UI is at `https://secretserver.example.com/SecretServer/app/#/secrets/view/all`,
your Base URL is `https://secretserver.example.com/`.
required: true
type: str
action:
description: The Action you want to take on the secret Server.
Must be one of "search", "get", "upsert", "update".
"search" performs a text search over all the secret names your user has access to.
"get" looks up a single secret by its ID.
"upsert" will look for the secret_name and folder_id you specify.
If no secret exists that match those two criteria, a new secret will be created.
If a secret already exists that matches both criteria,
the secret will be updated with the values you provided.
If more than one secret matches both criteria, no secret will be changed.
You cannot change the secret type or its name with this method.
Any other fields you set will be overwritten with that value.
If you do not specify a field that was previously set, it will not be overwritten.
If you want to explicitly clear a field of any values, specify it to `set_to_none`.
"update" updates the password of an existing secret
"get" and "search" will run in check mode,
"upsert" and "update" will return after doing the input validation
required: true
type: str
search_text:
description: The text you want to look for. Required for the "search" action
required: false
type: str
secret_id:
description: The ID of the Secret you want to target.
You can get the ID of a Secret by looking at it in the Web UI.
If the URL uf the Secret is `https://secretserver.example.com/SecretServer/app/#/secret/1234/general`,
its ID is 1324.
Required for the "get" and "update" actions.
required: false
type: int
folder_id:
description: The ID of the folder you want to target.
You can get the ID of a folder by looking at it in the Web UI.
If the URL uf the folder is `https://secretserver.example.com/SecretServer/app/#/secrets/view/folder/9876`,
its ID is 9876.
Required for the "upsert" action.
required: false
type: int
type:
description: The type of secret you want to create.
Different types have different fields, some of which are required fields.
The types and their required fields are:
"server":
- "secret_name"
- "user_name"
- "password"
"database":
- "secret_name"
- "database"
- "user_name"
- "password"
"website":
- "secret_name"
- "url"
- "user_name"
- "password"
"generic":
- "secret_name"
- "user_name"
- "password"
required: false
type: str
secret_name:
description: The name of the secret you want to create or update.
Required for the "upsert" action with all secret types.
required: false
type: str
user_name:
description: The value for the "Username" field of the Secret.
Required for the "upsert" action with all secret types.
required: false
type: str
password:
description: The value for the "Password" field.
Required for the "upsert" action with all secret types except for "x509".
Required for the "update" action.
required: false
type: str
database:
description: The value for the "Database" field.
Required for the "upsert" action with the "database" secret type.
required: false
type: str
connection_string:
description: The value for the "Connection string" field.
Optional for the "upsert" action with the "database" secret type.
required: false
type: str
url:
description: The value for the "URL" field.
Required for the "upsert" action with the "website" secret type.
required: false
type: str
fqdn:
description: The value for the "FQDN" field.
Optional for the "upsert" action with the "server" secret type.
required: false
type: str
logon_domain:
description: The value for the "Logon Domain" field.
Optional for the "upsert" action with the "server" secret type.
required: false
type: str
notes:
description:The value for the "Notes" field.
Optional for the "upsert" action with any secret type.
required: false
type: str
common_name:
description:The value for the "CN" field.
Optional for the "upsert" action with the "x509" secret type.
required: false
type: str
alt_name:
description:The value for the "SubjAltName" field.
Optional for the "upsert" action with the "x509" secret type.
required: false
type: str
location:
description:The value for the "Location" field.
Optional for the "upsert" action with the "x509" secret type.
required: false
type: str
private_key:
description:The value for the "Private key" field.
Optional for the "upsert" action with the "x509" secret type.
required: false
type: str
certificate:
description:The value for the "Certificate" field.
Optional for the "upsert" action with the "x509" secret type.
required: false
type: str
# Specify this value according to your collection
# in format of namespace.collection.doc_fragment_name
extends_documentation_fragment:
- id-unibe-ch.sys.secretserver
author:
- Matthias Studer (@studerma)
'''
EXAMPLES = r'''
- name: some acrobatics with the secret server
hosts: your_hosts
pre_tasks:
- name: Load Variables from the Vault
ansible.builtin.include_vars: "vault.yml"
run_once: true
- name: Set variables for the secretserver module
ansible.builtin.set_fact:
secretserver_base_url: "https://secretserver.example.com/SecretServer/"
tasks:
- name: Get a single Secret by its ID
secretserver:
secretserver_password: "{{ vault_secretserver_password }}"
secretserver_username: "{{ vault_secretserver_username }}"
secretserver_base_url: "{{ secretserver_base_url }}"
action: get
secret_id: 12345
register: get_secret
delegate_to: localhost
- name: dump the secret we got
debug:
var: get_secret
- name: Search trough all the secret names
secretserver:
secretserver_password: "{{ vault_secretserver_password }}"
secretserver_username: "{{ vault_secretserver_username }}"
secretserver_base_url: "{{ secretserver_base_url }}"
action: search
search_text: "login"
register: search_secret
delegate_to: localhost
- name: dump the secret result
debug:
var: search_secret
- name: If you narrow down your search enough, so only one secretname matches your search, you get the whle secret details
secretserver:
secretserver_password: "{{ vault_secretserver_password }}"
secretserver_username: "{{ vault_secretserver_username }}"
secretserver_base_url: "{{ secretserver_base_url }}"
action: search
search_text: "a really specific secret name"
register: unique_search_secret
delegate_to: localhost
- name: dump the secret result
debug:
var: unique_search_secret
- name: Read a .env file to demonstrate the usage of a token
ansible.builtin.slurp:
src: ../.env
register: env_file_content
delegate_to: localhost
- name: Parse the .env file contents
ansible.builtin.set_fact:
env_vars: "{{ ('{' + (env_file_content.content | b64decode).split('\n') | select | map('regex_replace', '([^=]*)=(.*)', '\"\\1\": \"\\2\"') | join(',') + '}') | from_json }}"
- name: make a search with a personal access token
secretserver:
secretserver_token: "{{ env_vars['SECRET_SERVER_TOKEN'] }}"
secretserver_username: "{{ vault_secretserver_username }}"
secretserver_base_url: "{{ secretserver_base_url }}"
action: get
secret_id: 12345
register: get_secret
delegate_to: localhost
- name: dump the secret we got
debug:
var: get_secret
- name: Create a generic account
secretserver:
secretserver_password: "{{ vault_secretserver_password }}"
secretserver_username: "{{ vault_secretserver_username }}"
secretserver_base_url: "{{ secretserver_base_url }}"
action: upsert
type: "generic"
folder_id: 999
secret_name: "{{ 'lookup_module_test_generic' + 9999999 | random | string }}"
user_name: "root"
password: "{{ lookup('password', '/dev/null chars=ascii_lowercase,digits length=12') }}"
notes:
key1: value1
key2: value2
register: generic_account
delegate_to: localhost
- name: dump the secret result
debug:
var: generic_account
- name: Create a website login
secretserver:
secretserver_password: "{{ vault_secretserver_password }}"
secretserver_username: "{{ vault_secretserver_username }}"
secretserver_base_url: "{{ secretserver_base_url }}"
action: upsert
type: "website"
folder_id: 999
secret_name: "{{ 'lookup_module_test_website' + 9999999 | random | string }}"
user_name: "root"
password: "{{ lookup('password', '/dev/null chars=ascii_lowercase,digits length=12') }}"
url: "https://www.example.com"
register: website_login
delegate_to: localhost
- name: dump the secret result
debug:
var: website_login
- name: Create a database account
secretserver:
secretserver_password: "{{ vault_secretserver_password }}"
secretserver_username: "{{ vault_secretserver_username }}"
secretserver_base_url: "{{ secretserver_base_url }}"
action: upsert
type: "database"
folder_id: 999
secret_name: "{{ 'lookup_module_test_database' + 9999999 | random | string }}"
user_name: "root"
password: "{{ lookup('password', '/dev/null chars=ascii_lowercase,digits length=12') }}"
database: "jdbc:www.hostedpostgres.com:5432/mydb"
register: database_account
delegate_to: localhost
- name: dump the secret result
debug:
var: database_account
- name: Create a server account
secretserver:
secretserver_password: "{{ vault_secretserver_password }}"
secretserver_username: "{{ vault_secretserver_username }}"
secretserver_base_url: "{{ secretserver_base_url }}"
action: upsert
type: "server"
folder_id: 999
secret_name: "{{ 'lookup_module_test_server' + 9999999 | random | string }}"
user_name: "root"
password: "{{ lookup('password', '/dev/null chars=ascii_lowercase,digits length=12') }}"
database: "jdbc:www.hostedpostgres.com:5432/mydb"
register: server_account
delegate_to: localhost
- name: dump the secret result
debug:
var: server_account
- name: Change the username and password of a Secret by searching for the secret
secretserver:
secretserver_password: "{{ vault_secretserver_password }}"
secretserver_username: "{{ vault_secretserver_username }}"
secretserver_base_url: "{{ secretserver_base_url }}"
action: upsert
type: "generic"
folder_id: 999
secret_name: "your secret name"
user_name: "hello"
password: "world_{{ lookup('password', '/dev/null chars=ascii_lowercase,digits length=4') }}"
register: password_change_with_search
delegate_to: localhost
- name: dump the secret result
debug:
var: password_change_with_search
- name: Change the password of a Secret by secret id
secretserver:
secretserver_password: "{{ vault_secretserver_password }}"
secretserver_username: "{{ vault_secretserver_username }}"
secretserver_base_url: "{{ secretserver_base_url }}"
action: update
secret_id: 12345
password: "{{ lookup('password', '/dev/null chars=ascii_lowercase,digits length=20') }}"
register: password_change_by_id
delegate_to: localhost
- name: dump the secret result
debug:
var: password_change_by_id
'''
RETURN = r'''
data:
description: The id of the secret that was targeted
type: dict
returned: by the "upsert" and "update" actions
sample: "data": {"secret_id": 12345 }
content:
description: The result of your search/lookup
type: dict
returned: by the "get" and "search" actions
sample: "content": {
"Notes": "Why did the functional programmer get thrown out of school? Because he refused to take classes.",
"Password": "supersecretpassword",
"Username": "my_user_name",
"folder_id": "999",
"id": "12345",
"name": "Your secret's name"
}
'''
class Auth:
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': '*/*'
}
def __init__(self,
base_url: str,
user_name: Union[str, None] = None,
password: Union[str, None] = None,
token: Union[str, None] = None
):
self._base_url = base_url
self._user_name = user_name
self._password = password
self._token_valid_until = None
self._access_token = token
self._refresh_token = None
def _get_token(self):
if self._access_token is not None or isinstance(self._token_valid_until, datetime.datetime):
return self._access_token
else:
return self._get_initial_token()
def _get_initial_token(self):
url = f"{self._base_url}oauth2/token"
data = f"grant_type=password&username={self._user_name}&password={self._password}"
response = requests.request(
"POST",
url,
headers=self.headers,
data=data
)
response_data = response.json()
self._refresh_token = response_data.get("refresh_token")
self._access_token = response_data.get("access_token")
self._token_valid_until = datetime.datetime.now() + datetime.timedelta(
seconds=(response_data.get("expires_in") - 10))
return self._access_token
def _refresh_access_token(self):
response = requests.request(
"POST",
f"{self._base_url}oauth2/token",
headers=self.headers,
data=f"grant_type=refresh_token&refresh_token={self._refresh_token}"
)
response_data = response.json()
self._refresh_token = response_data.get("refresh_token")
self._access_token = response_data.get("access_token")
self._token_valid_until = datetime.datetime.now() + datetime.timedelta(
seconds=(response_data.get("expires_in") - 10))
return self._access_token
def get_authenticated_headers(self) -> dict[str, str]:
return {
"Accept": "application/json",
"Authorization": f"Bearer {self._get_token()}"
}
def get_base_url(self) -> str:
return self._base_url
def get_secret_body(secret_name: str,
secret_type: str,
folder_id: int,
logon_domain: str,
fqdn: str,
notes: str,
password: str,
user_name: str,
database: str,
connection_string: str,
url: str,
common_name: str,
alt_name: str,
location: str,
private_key: str,
certificate: str
) -> dict:
type_mapping = {'database': {'items': [{'fieldDescription': 'The Database name or instance.',
'fieldId': 138,
'fieldName': 'Database',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': False,
'itemValue': database,
'listType': 'None',
'slug': 'database'},
{'fieldDescription': 'The Oracle Server Username.',
'fieldId': 115,
'fieldName': 'Username',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': False,
'itemValue': user_name,
'listType': 'None',
'slug': 'username'},
{'fieldDescription': 'The password of the Oracle user.',
'fieldId': 113,
'fieldName': 'Password',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': True,
'itemValue': password,
'listType': 'None',
'slug': 'password'},
{'fieldDescription': '',
'fieldId': 229,
'fieldName': 'Connection string',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': False,
'itemValue': connection_string,
'listType': 'None',
'slug': 'connection-string'},
{'fieldDescription': 'Any additional notes.',
'fieldId': 112,
'fieldName': 'Notes',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': True,
'isPassword': False,
'itemValue': notes,
'listType': 'None',
'slug': 'notes'}],
'template_id': 6008},
'generic': {'items': [{'fieldDescription': '',
'fieldId': 126,
'fieldName': 'Username',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': False,
'itemValue': user_name,
'listType': 'None',
'slug': 'username'},
{'fieldDescription': '',
'fieldId': 122,
'fieldName': 'Password',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': True,
'itemValue': password,
'listType': 'None',
'slug': 'password'},
{'fieldDescription': 'Any comments or additional '
'information for the secret.',
'fieldId': 124,
'fieldName': 'Notes',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': True,
'isPassword': False,
'itemValue': notes,
'listType': 'None',
'slug': 'notes'}],
'template_id': 6010},
'server': {'items': [{'fieldDescription': 'Used by Launcher to connect',
'fieldId': 206,
'fieldName': 'FQDN',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': False,
'itemValue': fqdn,
'listType': 'None',
'slug': 'fqdn-1'},
{'fieldDescription': '',
'fieldId': 187,
'fieldName': 'Username',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': False,
'itemValue': user_name,
'listType': 'None',
'slug': 'username'},
{'fieldDescription': '',
'fieldId': 188,
'fieldName': 'Password',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': True,
'itemValue': password,
'listType': 'None',
'slug': 'password'},
{'fieldDescription': '',
'fieldId': 204,
'fieldName': 'Logon Domain',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': False,
'itemValue': logon_domain,
'listType': 'None',
'slug': 'logon-domain'},
{'fieldDescription': '',
'fieldId': 189,
'fieldName': 'Note',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': True,
'isPassword': False,
'itemValue': notes,
'listType': 'None',
'slug': 'note'}],
'template_id': 6026},
'website': {'items': [{'fieldDescription': 'The online address where the '
'information is being secured.',
'fieldId': 38,
'fieldName': 'URL',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': False,
'itemValue': url,
'listType': 'None',
'slug': 'url'},
{'fieldDescription': 'The name associated with the web '
'password.',
'fieldId': 39,
'fieldName': 'Username',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': False,
'itemValue': user_name,
'listType': 'None',
'slug': 'username'},
{'fieldDescription': 'The password used to access the '
'URL.',
'fieldId': 40,
'fieldName': 'Password',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': True,
'itemValue': password,
'listType': 'None',
'slug': 'password'},
{'fieldDescription': 'Any comments or additional '
'information for the secret.',
'fieldId': 41,
'fieldName': 'Notes',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': True,
'isPassword': False,
'itemValue': notes,
'listType': 'None',
'slug': 'notes'}],
'template_id': 9},
'x509': {'items': [{'fieldDescription': '',
'fieldId': 242,
'fieldName': 'CN',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': False,
'itemValue': common_name,
'listType': 'None',
'slug': 'cn'},
{'fieldDescription': '',
'fieldId': 246,
'fieldName': 'SubjAltName',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': False,
'itemValue': alt_name,
'listType': 'None',
'slug': 'subjaltname'},
{'fieldDescription': 'Where is the key stored',
'fieldId': 243,
'fieldName': 'Location',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': False,
'itemValue': location,
'listType': 'None',
'slug': 'location'},
{'fieldDescription': '',
'fieldId': 244,
'fieldName': 'Password',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': False,
'isPassword': True,
'itemValue': password,
'listType': 'None',
'slug': 'password'},
{'fieldDescription': 'Base64',
'fieldId': 238,
'fieldName': 'Private key',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': True,
'isPassword': False,
'itemValue': private_key,
'listType': 'None',
'slug': 'private-key'},
{'fieldDescription': 'Base64',
'fieldId': 240,
'fieldName': 'Certificate',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': True,
'isPassword': False,
'itemValue': certificate,
'listType': 'None',
'slug': 'certificate'},
{'fieldDescription': '',
'fieldId': 245,
'fieldName': 'Notes',
'fileAttachmentId': None,
'filename': None,
'isFile': False,
'isList': False,
'isNotes': True,
'isPassword': False,
'itemValue': notes,
'listType': 'None',
'slug': 'notes'}],
'template_id': 6034}}
return {
"name": secret_name,
"secretTemplateId": type_mapping.get(secret_type).get("template_id"),
"folderId": folder_id,
"items": type_mapping.get(secret_type).get("items"),
"enableInheritPermissions": True,
"enableInheritSecretPolicy": True,
"requiresComment": False,
"secretPolicyId": 0,
"siteId": 1,
"sessionRecordingEnabled": False
}
def search_by_name(client: Auth, search_text: str) -> Union[list, dict]:
url = f"{client.get_base_url()}api/v2/secrets?filter.searchText={search_text}"
response = requests.request("GET", url, headers=client.get_authenticated_headers(), data={})
if response.status_code == 200:
json_data = json.loads(response.text)
records_list = []
if "records" in json_data:
for record in json_data.get("records"):
records_list.append({"name": to_text(record.get("name")), "id": to_text(record.get("id"))})
return {"success": True, "content": records_list} if len(records_list) > 1 or len(records_list) == 0 \
else lookup_single_secret(client=client, secret_id=records_list[0].get("id"))
else:
return {"success": False,
"status": response.status_code,
"text": response.text
}
def get_full_secret(client: Auth, secret_id: int) -> requests.Response:
return requests.request(
method="GET",
url=f"{client.get_base_url()}api/v2/secrets/{secret_id}",
headers=client.get_authenticated_headers(),
data={}
)
def lookup_single_secret(client: Auth, secret_id: int) -> dict:
type_mapping = {1: 'credit_card',
2: 'password',
3: 'pin',
9: 'website',
14: 'license_key',
6008: 'database',
6010: 'generic',
6011: 'snmp',
6013: 'firewall',
6026: 'server',
6027: 'ad_account',
6028: 'note',
6029: 'windows_server',
6032: 'service',
6033: 'id_admin',
6034: 'x509',
7037: 'ssh',
7038: 'ssh_privileged',
7039: 'zos_mainframe',
7041: 'watchguard',
8044: 'ssh_keyless',
8045: 'ssh_keyless_privileged',
8046: 'iam_key',
8047: 'ibm_mainframe',
9041: 'iam_console',
9044: 'vault_client',
9045: 'google_iam',
9047: 'sap',
10050: 'oracle_tcps',
10051: 'oracle_ver2',
10052: 'oracle_walletless',
10053: 'escapeless_password'}
response = get_full_secret(client=client, secret_id=secret_id)
if response.status_code == 200:
json_data = json.loads(response.text)
content = {}
if "id" in json_data:
content["id"] = to_text(json_data.get('id'))
content["name"] = to_text(json_data.get("name"))
content["folder_id"] = to_text(json_data.get("folderId"))
content["type"] = type_mapping.get(json_data.get("secretTemplateId"))
for item in json_data.get("items"):
if not item.get("isFile"):
content[to_text(item.get("fieldName"))] = to_text(item.get("itemValue"))
return {"success": True, "content": content}
else:
return {"success": False,
"status": response.status_code,
"text": response.text
}
def create_secret(
client: Auth,
secret_name: str,
user_name: str,
password: str,
folder_id: int,
connection_string: str,
url: str,
secret_type: str,
notes: str,
fqdn: str,
logon_domain: str,
database: str,
common_name: str,
alt_name: str,
location: str,
private_key: str,
certificate: str
) -> dict:
response = requests.request(method="POST", url=f"{client.get_base_url()}api/v1/secrets", headers={
**client.get_authenticated_headers(),
"Content-Type": "application/json"}, data=json.dumps(get_secret_body(secret_name=secret_name,
secret_type=secret_type,
folder_id=folder_id,
logon_domain=logon_domain,
fqdn=fqdn,
notes=notes,
password=password,
user_name=user_name,
database=database,
connection_string=connection_string,
url=url,
common_name=common_name,
alt_name=alt_name,
location=location,
private_key=private_key,
certificate=certificate)))
json_data = json.loads(response.text)
if response.status_code == 200:
return {"success": True,
"changed": True,
"diff": {
"before": "absent",
"after": extract_readable_secret_from_secretserver_response(json_data)
},
"data": {
"secret_id": json_data.get("id")
}
}
else:
return {"success": False, "data": {"code": response.status_code, "payload": json_data}}
def update_secret_by_id(client: Auth, secret_id: int, updated_password: str) -> dict:
full_secret_response = get_full_secret(client=client, secret_id=secret_id)
if full_secret_response.status_code == 200 and full_secret_response.json():
previous_secret = full_secret_response.json()
previous_items = previous_secret.get("items")
previous_password = ""
for item in previous_items:
if item.get("slug") == "password":
previous_password = item.get("itemValue")
item["itemValue"] = updated_password
break
previous_secret["items"] = previous_items
url = f"{client.get_base_url()}api/v1/secrets/{secret_id}"
response = requests.put(url, json=previous_secret, headers={
**client.get_authenticated_headers(),
"Content-Type": "application/json"})
if response.status_code == 200:
return {
"success": True,
"code": response.status_code,
"text": {"secret_id": response.json().get("id")},
"changed": previous_password != updated_password,
"diff": {
"before": extract_readable_secret_from_secretserver_response(previous_secret, mask_passwords=True),
"after": extract_readable_secret_from_secretserver_response(response.json())
}
}
else:
return {"success": False, "code": response.status_code, "text": response.text}
else:
return {"success": False, "reason": "Could not get secret to be modified",
"code": full_secret_response.status_code, "text": full_secret_response.text}
def compare_item_lists(former: List[Dict[str, Union[str, int]]], latter: List[Dict[str, Union[str, int]]]) -> bool:
# Made to compare lists of dicts, like the ones you have in the "items" field of a Secret
# Returns true when both lists contain all the same dicts
if len(former) != len(latter):
return False
for former_item in former:
latter_item = next(
(latter_item for latter_item in latter if latter_item.get("fieldId") == former_item.get("fieldId"))
, None)
if latter_item is None or former_item.get("itemValue") != latter_item.get("itemValue"):
return False
return True
def update_secret_by_body(client: Auth,
secret_name: str,