-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathgpg_key.py
1572 lines (1292 loc) · 53.6 KB
/
gpg_key.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) 2019, Rinck H. Sonnenberg - Netson <[email protected]>
# License: MIT
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: gpg_key
short_description: Module to install and trust GPG keys
version_added: "2.7"
description: |
Module to install and trust GPG keys from files and keyservers.
I shouldn't have to tell you that it is a BAD idea to store your
secret keys inside a playbook or role! Please take approriate measures
to protect your sensitive information from falling into the wrong hands!
options:
fpr:
description: |
Key Fingerprint to install from keyserver, to delete from target
machine, or to get info on. To get info on all installed keys,
use * as the value for fpr. Using any shorter ID than the full
fingerprint will fail. Using the short ID's isn't recommended
anyways, due to possible collisions.
required: false
type: str
keyserver:
description: Keyserver to download key from
default: keyserver.ubuntu.com
type: str
file:
description: |
File on target machine containing the key(s) to install;
be aware that a file can contain more than 1 key; if this
is the case, all keys will be imported and all keys will
receive the same trust level. The module auto-detects if
the given key is a public or secret key.
required: false
type: path
content:
description: |
Contents of keyfile to install on target machine
just like the file, the contents can contain more than 1 key
and all keys will receive the same trust level. The module
auto-detects if the given key is a public or secret key.
The content parameter simply creates a temporary file on the
target host and then performs the same actions as the file
parameter. It is just an easy method to not have to create
a keyfile on the target machine first.
required: false
type: str
manage_trust:
description: |
Setting controls wether or not the module controls the trust levels
of the (imported) keys. If set to false, no changes will be made to
the trust level regardless of the 'trust' setting.
default: true
type: bool
trust:
description: |
Trust level to apply to newly imported keys or existing keys;
please keep in mind that keys with a trust level other than 5
need to be signed by a fully trusted key in order to effectively
set the trust level. If your key is not signed by a fully trusted
key and the trust level is 2, 3 or 4, the module will report a
changed state on each run due to the fact that GnuPG will report
an 'Unknown' trust level.
choices:
- 1
- 2
- 3
- 4
- 5
default: 1
type: str
state:
description: |
Key should be present, absent, latest (keyserver only) or info.
Info only shows info for key given via fpr. Alternatively, you
can use the special value * for the fpr to get a list of all
installed keys and their relevant info.
default: present
type: str
choices:
- present
- absent
- latest
- info
gpgbin:
description: Full path to GnuPG binary on target host
default: uses get_bin_path method to find gpg
type: path
homedir:
description: |
Full path to the gpg homedir you wish to use; If none is provided,
gpg will use the default homedir of ~/.gnupg
Please be aware that this will be the user executing the module
on the target host! So there will likely be a difference between
running the module with and without become:yes! If you don't want to
be surprised, set the path to the homedir with the variable. For more
information on the GnuPG homedir, check
https://www.gnupg.org/gph/en/manual/r1616.html
default: None
type: path
keyring:
description: |
Full path to the gpg keyring you wish to use; If none is provided,
gpg will use the default
For more information on the GnuPG keyring, check
https://www.gnupg.org/gph/en/manual/r1574.html
default: None
type: path
author:
- Rinck H. Sonnenberg ([email protected])
'''
EXAMPLES = '''
# install key from keyfile on target host and set trust level to 5
- name: add key(s) from file and set trust
gpg_key:
file: "/tmp/testkey.asc"
trust: '5'
# make sure all keys in a file are NOT present on the keychain
- name: remove keys inside file from the keychain
gpg_key:
file: "/tmp/testkey.asc"
state: absent
# install keys on the target host from a keyfile on the ansible master
- name: install keys on the target host from a keyfile on the ansible master
gpg_key:
content: "{{ lookup('file', '/my/tmp/file/on/host') }}"
# alternatively, you can simply provide the key contents directly
- name: install keys from key contents
content: "-----BEGIN PGP PUBLIC KEY BLOCK-----........."
# install key from keyserver on target machine
- name: install key from default keyserver on target machine
gpg_key:
fpr: 0D69E11F12BDBA077B3726AB4E1F799AA4FF2279
# install key from keyserver on target machine and set trust level
- name: install key from alternate keyserver on target machine and set trust level 5
gpg_key:
fpr: 0D69E11F12BDBA077B3726AB4E1F799AA4FF2279
keyserver: eu.pool.sks-keyservers.net
trust: '5'
# delete a key from the target machine
- name: remove a key from the target machine
gpg_key:
fpr: 0D69E11F12BDBA077B3726AB4E1F799AA4FF2279
state: absent
# get keyinfo for a specific key; will also return success if key not installed
- name: get keyinfo
gpg_key:
fpr: 0D69E11F12BDBA077B3726AB4E1F799AA4FF2279
state: info
# get keyinfo for all installed keys, public and secret
- name: get keyinfo for all keys
gpg_key:
fpr: '*'
state: info
'''
RETURN = '''
keys:
description: |
list of keys touched by the module;
list contains dicts of fingerprint, keytype, capabilities and trust level for each key
an exmaple output would looke like:
A0880EC90DD07F5968CEE3B6C6B3D8E7A7CD2528:
changed: false
creationdate: '1576698396'
curve_name: ed25519
expirationdate: ''
fingerprint: A0880EC90DD07F5968CEE3B6C6B3D8E7A7CD2528
hash_algorithm: ''
key_capabilities: cSC
key_length: '256'
keyid: C6B3D8E7A7CD2528
pubkey_algorithm: Ed25519
state: present
trust_level: u
trust_level_desc: The key is ultimately trusted
type: pub
userid: 'somekey <[email protected]>'
If you set the state to absent, and the key was already absent, obviously
not all info will be available; it would look similar to:
A0880EC90DD07F5968CEE3B6C6B3D8E7A7CD2528:
changed: false
fingerprint: A0880EC90DD07F5968CEE3B6C6B3D8E7A7CD2528
state: absent
type: list
returned: always
debug:
description: contains debug information
type: list
returned: when verbosity >= 2
'''
import re
import os
import time
from ansible.module_utils.basic import AnsibleModule
from packaging import version
# class to import GPG keys
class GpgKey(object):
def __init__(self, module):
"""
init method
"""
# set ansible module
self.module = module
self.debugmsg = []
self.installed_keys = {}
self.changed = False
# seed the result dict in the object
# we primarily care about changed and state
# change is if this module effectively modified the target
# state will include any data that you want your module to pass back
# for consumption, for example, in a subsequent task
self.result = dict(
changed=False,
keys={},
msg="",
)
# set gpg binary none was provided
if not self.module.params["gpgbin"] or self.module.params["gpgbin"] is None:
self.module.params["gpgbin"] = self.module.get_bin_path('gpg')
def _vv(self, msg):
"""
debug info
"""
# add debug message
self.debugmsg.append("{}".format(msg))
def has_method(self, name):
"""
method to check if other methods exist
"""
return callable(getattr(self, name, None))
def run(self):
"""
run module with given parameters
"""
# check versions of gnupg and libgcrypt
# check homedir
self.check_versions()
self.check_homedir()
# determine and run action
if self.module.params["file"]:
run_action = "file"
elif self.module.params["fpr"]:
run_action = "fpr"
elif self.module.params["content"]:
run_action = "content"
else:
self.module.fail_json(msg="You shouldn't be here; no valid action could be determined")
# determine action and method
run_state = self.module.params["state"]
run_method = "run_{}_{}".format(run_action, run_state)
self._vv("determined action [{}] with state [{}]".format(run_action, run_state))
# always check installed keys first
self.check_installed_keys()
#self.result["installed_keys"] = self.installed_keys
# check if run method exists, and if not fail with an error
if self.has_method(run_method):
getattr(self, run_method)()
else:
self.module.fail_json(msg="Action [{}] is not supported with state [{}]".format(run_action, run_state))
# check verbosity and add debug messages
if self.module._verbosity >= 2:
self.result['debug'] = "\n".join(self.debugmsg)
# return result
return self.result
def run_file_present(self):
"""
import key from file
"""
# first, check if the file is OK
keyinfo = self.check_file()
self._vv("import new keys from file")
# import count
impcnt = 0
trucnt = 0
# then see if the key is already installed
# fk = file key
# ik = installed key
for index, fk in enumerate(keyinfo["keys"]):
# check expiration by checking trust
if fk["trust_level"] in ['i','d','r','e']:
self.module.fail_json(msg="key is either expired or invalid [trust={}] [expiration={}]".format(fk["trust_level"], fk["expirationdate"]))
# check if key is installed
installed = False
for ik in self.installed_keys["keys"]:
if (fk["fingerprint"].upper() == ik["fingerprint"].upper() and
fk["type"] == ik["type"] and
fk["key_capabilities"] == ik["key_capabilities"]
):
self._vv("fingerprint [{}] already installed".format(fk["fingerprint"]))
keyinfo["keys"][index]["state"] = "present"
keyinfo["keys"][index]["changed"] = False
installed = True
# check trust
if not self.compare_trust(fk["trust_level"], self.module.params["trust"]):
# update trust level
self.set_trust(fk["fingerprint"], self.module.params["trust"])
trucnt += 1
# get trust level as displayed by gpg
tru_level, tru_desc = self.get_trust(self.module.params["trust"])
keyinfo["keys"][index]["changed"] = True
keyinfo["keys"][index]["trust_level"] = tru_level
keyinfo["keys"][index]["trust_level_desc"] = tru_desc
continue
if not installed:
self._vv("fingerprint [{}] not yet installed".format(fk["fingerprint"]))
# import file
cmd = self.prepare_command("file", "present")
# run subprocess
rc, stdout, stderr = self.module.run_command(args=cmd, check_rc=True)
self._vv("fingerprint [{}] successfully imported".format(fk["fingerprint"]))
keyinfo["keys"][index]["state"] = "present"
keyinfo["keys"][index]["changed"] = True
impcnt += 1
# check trust
if not self.compare_trust(fk["trust_level"], self.module.params["trust"]):
# update trust level
self.set_trust(fk["fingerprint"], self.module.params["trust"])
trucnt += 1
# get trust level as displayed by gpg
tru_level, tru_desc = self.get_trust(self.module.params["trust"])
keyinfo["keys"][index]["changed"] = True
keyinfo["keys"][index]["trust_level"] = tru_level
keyinfo["keys"][index]["trust_level_desc"] = tru_desc
# set keyinfo
self.set_keyinfo(keyinfo)
# check import count
if impcnt > 0 or trucnt > 0:
self.result["changed"] = True
# set message and return
self.result["msg"] = "[{}] keys were imported; [{}] trust levels updated".format(impcnt, trucnt)
return True
def run_file_absent(self):
"""
remove key(s) present in file
"""
# first, check if the file is OK
keyinfo = self.check_file()
self._vv("remove keys identified in file")
# key count
keycnt = 0
# then see if the key is installed or not
# fk = file key
# ik = installed key
for index, fk in enumerate(keyinfo["keys"]):
installed = False
for ik in self.installed_keys["keys"]:
if (fk["fingerprint"].upper() == ik["fingerprint"].upper() and
fk["type"] == ik["type"] and
fk["key_capabilities"] == ik["key_capabilities"]
):
installed = True
continue
if not installed:
self._vv("fingerprint [{}] not installed; nothing to remove".format(fk["fingerprint"]))
keyinfo["keys"][index]["state"] = "absent"
keyinfo["keys"][index]["changed"] = False
else:
self._vv("fingerprint [{}] installed; will be removed".format(fk["fingerprint"]))
# remove file
cmd = self.prepare_command("file", "absent")
# add fingerprint as argument
cmd += [fk["fingerprint"]]
# run subprocess
rc, stdout, stderr = self.module.run_command(args=cmd, check_rc=True)
self._vv("fingerprint [{}] successfully removed".format(fk["fingerprint"]))
keyinfo["keys"][index]["state"] = "absent"
keyinfo["keys"][index]["changed"] = True
keycnt += 1
# re-run check installed command to prevent attempting to remove same
# fingerprint again (for example after removing pub/sec counterpart
# with the same fpr
self.check_installed_keys()
# set keyinfo
self.set_keyinfo(keyinfo)
# check import count
if keycnt > 0:
self.result["changed"] = True
# return
self.result["msg"] = "[{}] keys were removed".format(keycnt)
return True
def run_file_info(self):
"""
method to only retrive current status of keys
wether from file, content or fpr
"""
# first, check if the file is OK
keyinfo = self.check_file()
self._vv("showing key info from file")
# then see if the key is already installed
# fk = file key
# ik = installed key
for index, fk in enumerate(keyinfo["keys"]):
# check if key is installed
installed = False
for ik in self.installed_keys["keys"]:
if (fk["fingerprint"].upper() == ik["fingerprint"].upper() and
fk["type"] == ik["type"] and
fk["key_capabilities"] == ik["key_capabilities"]
):
self._vv("fingerprint [{}] installed".format(fk["fingerprint"]))
keyinfo["keys"][index]["state"] = "present"
keyinfo["keys"][index]["changed"] = False
installed = True
continue
if not installed:
# set state
self._vv("fingerprint [{}] not installed".format(fk["fingerprint"]))
keyinfo["keys"][index]["state"] = "absent"
keyinfo["keys"][index]["changed"] = False
# set keyinfo
self.set_keyinfo(keyinfo)
# set message and return
return True
def run_content_present(self):
"""
import keys from content
"""
# prepare content
filename = self.prepare_content(self.module.params["content"])
# set file parameter and run file present
self.module.params["file"] = filename
self.run_file_present()
# delete content
self.delete_content(filename)
def run_content_absent(self):
"""
remove keys from content
"""
# prepare content
filename = self.prepare_content(self.module.params["content"])
# set file parameter and run file present
self.module.params["file"] = filename
self.run_file_absent()
# delete content
self.delete_content(filename)
def run_content_info(self):
"""
get key info from content
"""
# prepare content
filename = self.prepare_content(self.module.params["content"])
# set file parameter and run file present
self.module.params["file"] = filename
self.run_file_info()
# delete content
self.delete_content(filename)
def run_fpr_present(self):
"""
import key from keyserver
"""
self._vv("import new keys from keyserver")
# set fpr shorthand
fpr = self.module.params["fpr"]
# set base values
installed = False
impcnt = 0
trucnt = 0
keyinfo = {
'fprs': [],
'keys': [],
}
# check if key is installed
for ik in self.installed_keys["keys"]:
if (fpr.upper() == ik["fingerprint"].upper()):
# set keyinfo
self._vv("fingerprint [{}] already installed".format(fpr))
keyinfo["fprs"].append(fpr)
keyinfo["keys"].append(ik)
keyinfo["keys"][0]["state"] = "present"
keyinfo["keys"][0]["changed"] = False
installed = True
# check trust
if not self.compare_trust(ik["trust_level"], self.module.params["trust"]):
# update trust level
self.set_trust(fpr, self.module.params["trust"])
trucnt += 1
# get trust level as displayed by gpg
tru_level, tru_desc = self.get_trust(self.module.params["trust"])
keyinfo["keys"][0]["changed"] = True
keyinfo["keys"][0]["trust_level"] = tru_level
keyinfo["keys"][0]["trust_level_desc"] = tru_desc
continue
if not installed:
self._vv("fingerprint [{}] not yet installed".format(fpr))
# import file
cmd = self.prepare_command("fpr", "present")
cmd += [fpr]
# run subprocess
rc, stdout, stderr = self.module.run_command(args=cmd, check_rc=True)
self._vv("fingerprint [{}] successfully imported from keyserver".format(fpr))
# get info from specific key; keyservers only contain public keys
# so no point in checking the secret keys
cmd = self.prepare_command("check", "installed_public")
cmd += [fpr]
rc, stdout, stderr = self.module.run_command(args=cmd, check_rc=True)
keyinfo = self.process_colons(stdout)
# check expiration by checking trust
if keyinfo["keys"][0]["trust_level"] in ['i','d','r','e']:
# deleted the expired key and fail
cmd = self.prepare_command("fpr", "absent")
cmd += [fpr]
rc, stdout, stderr = self.module.run_command(args=cmd, check_rc=True)
self.module.fail_json(msg="key is either expired or invalid [trust={}] [expiration={}]".format(keyinfo["keys"][0]["trust_level"], keyinfo["keys"][0]["expirationdate"]))
# update key info
keyinfo["keys"][0]["state"] = "present"
keyinfo["keys"][0]["changed"] = True
impcnt += 1
# check trust
if not self.compare_trust(keyinfo["keys"][0]["trust_level"], self.module.params["trust"]):
# update trust level
self.set_trust(fpr, self.module.params["trust"])
trucnt += 1
# get trust level as displayed by gpg
tru_level, tru_desc = self.get_trust(self.module.params["trust"])
keyinfo["keys"][0]["changed"] = True
keyinfo["keys"][0]["trust_level"] = tru_level
keyinfo["keys"][0]["trust_level_desc"] = tru_desc
# set keyinfo
self.set_keyinfo(keyinfo)
# check import count
if impcnt > 0 or trucnt > 0:
self.result["changed"] = True
# set message and return
self.result["msg"] = "[{}] keys were imported; [{}] trust levels updated".format(impcnt, trucnt)
return True
def run_fpr_absent(self):
"""
remove key(s)
"""
self._vv("delete keys based on fingerprint")
# set fpr shorthand
fpr = self.module.params["fpr"]
# set base values
installed = False
keycnt = 0
keyinfo = {
'fprs': [],
'keys': [],
}
# see if the key is installed or not
# ik = installed key
for ik in self.installed_keys["keys"]:
if fpr.upper() == ik["fingerprint"].upper():
if ("state" in ik and ik["state"] != "absent") or ("state" not in ik):
keyinfo["fprs"].append(fpr)
keyinfo["keys"].append(ik)
installed = True
continue
if not installed:
self._vv("fingerprint [{}] not installed; nothing to remove".format(fpr))
key = {}
key[fpr] = {
"state" : "absent",
"changed" : False,
"fingerprint" : fpr,
}
keyinfo["fprs"].append(fpr)
keyinfo["keys"].append(key)
else:
self._vv("fingerprint [{}] installed; will be removed".format(fpr))
# remove file
cmd = self.prepare_command("fpr", "absent")
# add fingerprint as argument
cmd += [fpr]
# run subprocess
rc, stdout, stderr = self.module.run_command(args=cmd, check_rc=True)
self._vv("fingerprint [{}] successfully removed".format(fpr))
keyinfo["keys"][0]["state"] = "absent"
keyinfo["keys"][0]["changed"] = True
keycnt += 1
# re-run check installed command to prevent attempting to remove same
# fingerprint again (for example after removing pub/sec counterpart
# with the same fpr
self.check_installed_keys()
# set keyinfo
self.set_keyinfo(keyinfo)
# check import count
if keycnt > 0:
self.result["changed"] = True
# return
self.result["msg"] = "[{}] keys were removed".format(keycnt)
return True
def run_fpr_latest(self):
"""
get the latest key from the keyserver
"""
self._vv("get latest key from keyserver")
# set fpr shorthand
fpr = self.module.params["fpr"]
# set base values
installed = False
updated = False
updcnt = 0
trucnt = 0
keyinfo = {
'fprs': [],
'keys': [],
}
# check if key is installed
for ik in self.installed_keys["keys"]:
if (fpr == ik["fingerprint"]):
# set keyinfo
self._vv("fingerprint [{}] installed; updating from server".format(fpr))
keyinfo["fprs"].append(fpr)
keyinfo["keys"].append(ik)
keyinfo["keys"][0]["state"] = "present"
keyinfo["keys"][0]["changed"] = False
installed = True
continue
if not installed:
self._vv("fingerprint [{}] not yet installed; install first".format(fpr))
# import from keyserver
self.run_fpr_present()
return True
else:
self._vv("fetching updates from keyserver")
# get updates from keyserver
cmd = self.prepare_command("fpr", "latest")
cmd += [fpr]
rc, stdout, stderr = self.module.run_command(args=cmd, check_rc=True)
# see if any updates were downloaded or not
# for some reason, gpg outputs these messages to stderr
updated = re.search(r'gpg:\s+unchanged: 1\n', stderr) is None
if updated:
updcnt += 1
# if key was updated, refresh info
if updated:
self._vv("key was updated on server")
# get info from specific key; keyservers only contain public keys
# so no point in checking the secret keys
cmd = self.prepare_command("check", "installed_public")
cmd += [fpr]
rc, stdout, stderr = self.module.run_command(args=cmd, check_rc=True)
keyinfo = self.process_colons(stdout)
# check expiration by checking trust
if keyinfo["keys"][0]["trust_level"] in ['i','d','r','e']:
# deleted the expired key and fail
cmd = self.prepare_command("fpr", "absent")
cmd += [fpr]
rc, stdout, stderr = self.module.run_command(args=cmd, check_rc=True)
self.module.fail_json(msg="key is either expired or invalid [trust={}] [expiration={}]".format(keyinfo["keys"][0]["trust_level"], keyinfo["keys"][0]["expirationdate"]))
# update key info
keyinfo["keys"][0]["state"] = "present"
keyinfo["keys"][0]["changed"] = True
# check trust
if not self.compare_trust(keyinfo["keys"][0]["trust_level"], self.module.params["trust"]):
# update trust level
self.set_trust(fpr, self.module.params["trust"])
# get trust level as displayed by gpg
tru_level, tru_desc = self.get_trust(self.module.params["trust"])
keyinfo["keys"][0]["changed"] = True
keyinfo["keys"][0]["trust_level"] = tru_level
keyinfo["keys"][0]["trust_level_desc"] = tru_desc
trucnt += 1
# set keyinfo
self.set_keyinfo(keyinfo)
# check import count
if updcnt > 0 or trucnt > 0:
self.result["changed"] = True
# set message and return
self.result["msg"] = "[{}] keys were updated; [{}] trust levels updated".format(updcnt, trucnt)
return True
def run_fpr_info(self):
"""
method to only return current key info
will never report changed as it doesn't change anything on the target
"""
# frp shorthand
fpr = self.module.params["fpr"]
keycount = 0
# check if the request is for a single key or all
if fpr == "*":
keyinfo = self.installed_keys
keycount = len(self.installed_keys["keys"])
else:
# then see if the key is already installed
# ik = installed key
installed = False
keycount = 1
keyinfo = {
"fprs": [],
"keys": [{}], # Initialize keys list with an empty dictionary
}
for ik in self.installed_keys["keys"]:
if fpr.upper() == ik["fingerprint"].upper():
self._vv("Fingerprint [{}] installed".format(fpr))
keyinfo["fprs"].append(fpr)
keyinfo["keys"].append(ik)
keyinfo["keys"][0]["state"] = "present"
keyinfo["keys"][0]["changed"] = False
installed = True
break
if not installed:
# set state
self._vv("fingerprint [{}] not installed".format(fpr))
keyinfo["fprs"].append(fpr)
keyinfo["keys"].append({})
keyinfo["keys"][0]["fingerprint"] = fpr
keyinfo["keys"][0]["state"] = "absent"
keyinfo["keys"][0]["changed"] = False
# set keyinfo
self.set_keyinfo(keyinfo)
self.result["msg"] = "listing info for [{}] key(s)".format(keycount)
def prepare_content(self, content):
"""
prepare content
"""
# create temporary file and write contents
filename = "tmp-gpg-{}.asc".format(time.time())
self._vv("writing content to temporary file [{}]".format(filename))
tmpfile = open("{}".format(filename),"w+")
tmpfile.write(content)
tmpfile.close()
# return filename
return filename
def delete_content(self, filename):
"""
delete temporary content
"""
# cleanup
self._vv("deleting temporary file [{}]".format(filename))
os.remove(filename)
def prepare_command(self, action, state):
"""
prepare any gpg command
"""
# set base command
cmd = [self.module.params["gpgbin"]]
# determine dry run / check mode
if self.module.check_mode:
cmd.append("--dry-run")
# determine if homedir was set
if self.module.params["homedir"]:
cmd.append("--homedir")
cmd.append(self.module.params["homedir"])
# determine if keyring was set
if self.module.params["keyring"]:
cmd.append("--keyring")
cmd.append(self.module.params["keyring"])
# check versions
if action == "check" and state == "versions":
args = ["--version"]
# check installed public keys
if action == "check" and state == "installed_public":
args = [
"--with-colons",
"--list-keys",
]
# check installed secret keys
if action == "check" and state == "installed_secret":
args = [
"--with-colons",
"--list-secret-keys",
]
# check file
if action == "check" and state == "file":
args = [
"--with-colons",
"--dry-run",
"--import-options",
"import-show",
"--import",
self.module.params["file"],
]
# file present
if action == "file" and state == "present":
args = [
"--batch",
"--import",
self.module.params["file"],
]
# file absent
if action == "file" and state == "absent":
args = [
"--batch",
"--yes",
"--delete-secret-and-public-key",
]
# set ownertrust
if action == "set" and state == "trust":
args = ["--import-ownertrust"]
# fpr present
if action == "fpr" and state == "present":
args = ["--recv-keys"]
# determine if keyserver
if self.module.params["keyserver"]:
cmd.append("--keyserver")
cmd.append(self.module.params["keyserver"])
# fpr absent
if action == "fpr" and state == "absent":
args = [
"--batch",
"--yes",
"--delete-secret-and-public-key",
]
# fpr latest
if action == "fpr" and state == "latest":
args = ["--refresh-keys"]
# determine if keyserver
if self.module.params["keyserver"]:
cmd.append("--keyserver")
cmd.append(self.module.params["keyserver"])
# merge cmd and args and return
cmd += args
self._vv("running command [{}]".format(" ".join(cmd)))
return cmd
def check_versions(self):
"""
function to verify we have the right gnupg2 version