-
Notifications
You must be signed in to change notification settings - Fork 25
/
pius-keyring-mgr
executable file
·881 lines (794 loc) · 26.9 KB
/
pius-keyring-mgr
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
#!/usr/bin/env python3
"""A utility to create and manage party keyrings."""
# vim:tw=80:ai:tabstop=4:expandtab:shiftwidth=4
#
# Copyright (c) 2011 - present Phil Dibowitz ([email protected])
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, version 2.
#
import email
import mailbox
import optparse
import os
import re
import shutil
import subprocess
import sys
from libpius.util import PiusUtil as util
from libpius.util import MyOption as piusopt
from libpius import mailer as pmailer
from libpius.constants import (
VERSION,
GPG_BASE_OPTS,
GPG_QUIET_OPTS,
GPG_FD_OPTS,
FP_RE,
FIXFP_RE,
)
BADKEYS_RE = re.compile(r"00000000|12345678|no pgp key")
LIST_SEP_RE = re.compile(r"\s*,\s*")
DEFAULT_KEYSERVERS = [
"pool.sks-keyservers.net",
"pgp.mit.edu",
"keys.gnupg.net",
]
DEFAULT_GPG_PATH = "/usr/bin/gpg"
DEFAULT_CSV_DELIMITER = ","
DEFAULT_CSV_NAME_FIELD = 2
DEFAULT_CSV_EMAIL_FIELD = 3
DEFAULT_CSV_FP_FIELD = 4
DEFAULT_TMP_DIR = "/tmp/pius_keyring_mgr_tmp"
DEFAULT_EMAIL_TEXT = """Dear %(name)s,
You signed up for the %(party)sPGP Keysigning Party with the following key:
%(fp)s
However, I have not been able to find your key. I have tried the following
keyservers:
%(keyservers)s
Please upload your key to one of the aforementioned keyservers. You can do
this simply with:
gpg --keyserver %(keyserver)s --send-key KEYID
Where 'KEYID' is the keyid of your PGP key. For more information see this site:
http://www.phildev.net/pgp/
Your key will be searched for again in 24-48 hours and if your key is not there,
you will receive another email.
You do not need to contact me if you upload your key. If you have questions you
may email %(from)s.
Generated by PIUS Keyring Manager (http://www.phildev.net/pius/).
"""
def print_default_email():
"""Print the default email that is sent out."""
interpolation_dict = {
"name": "<name>",
"email": "<email>",
"from": "<your_email>",
"party": "<party_name> ",
"keyserver": "<example_keyserver>",
"keyservers": "<keyserver_list>",
"fp": "<fingerprint>",
}
print("DEFAULT EMAIL TEXT:\n")
print(DEFAULT_EMAIL_TEXT % interpolation_dict)
def keyid_from_fp(fp):
"""Given a fingerprint without whitespace, returns keyid."""
return fp[24:40]
class PiusParser:
@classmethod
def parse_csv(
self,
filename,
sep,
name_field,
email_field,
fp_field,
ignore_emails,
ignore_fps,
):
"""Parse a CSV for name, email, fingerprint, and generate keyid."""
fp_field = fp_field - 1
name_field = name_field - 1
email_field = email_field - 1
ignore_email_list = LIST_SEP_RE.split(ignore_emails)
ignore_fp_list = LIST_SEP_RE.split(ignore_fps)
report = open(filename, "r")
keys = []
for line in report:
line = line.strip()
# skip empty lines
if not line:
continue
parts = line.split(sep)
if BADKEYS_RE.search(parts[fp_field]):
continue
fp = parts[fp_field].replace(" ", "")
if (
parts[fp_field] in ignore_fp_list
or parts[email_field] in ignore_email_list
):
util.debug('Ignoring "%s" at user request' % line)
continue
keyid = keyid_from_fp(fp)
keys.append(
{
"name": parts[name_field],
"email": parts[email_field],
"keyid": keyid,
"fingerprint": fp,
}
)
print("Found %s keys in file." % len(keys))
return keys
@classmethod
def parse_flatfile(self, filename):
with open(filename, "r") as fd:
contents = fd.read()
matches = FP_RE.findall(contents)
keys = []
for match in matches:
flatfp = FIXFP_RE.sub("", match)
keyid = flatfp[-8:]
keys.append(
{
"keyid": keyid,
"fingerprint": flatfp,
"name": None,
"email": None,
}
)
print("Found %s keys in file." % len(keys))
return keys
@classmethod
def parse_mbox(self, filename):
"""Parse an mbox for name, email, fingerprints and keys.
Note that in the even of a fingerprint, keyid is generated, otherwise
just the ASCII-armored key is stored."""
box = mailbox.mbox(filename)
keys = []
num_fps = num_keys = 0
for msg in box:
m = email.parser.Parser()
p = m.parsestr(msg.as_string())
uid = p.get("From")
name = None
mail = None
if uid:
match = self.UID_RE.search(uid)
if match:
name = match.group(1)
mail = match.group(2)
name = self.FIXNAME1_RE.sub("", name)
name = self.FIXNAME2_RE.sub("", name)
for part in msg.walk():
# if decoded returns None, we're in multipart messages, or other
# non-convertable-to-text data, so we can move on. If it's multipart
# then we'll get to the sub-parts on further iterations of walk()
decoded = part.get_payload(None, True)
if not decoded:
util.debug("Skipping non-decodable part")
continue
decoded = decoded.decode("utf8")
data = {"name": name, "email": mail}
matches = self.KEY_RE.findall(decoded)
if matches:
for match in matches:
num_keys = num_keys + 1
tmp = data.copy()
tmp["key"] = match
keys.append(tmp)
continue
matches = FP_RE.findall(decoded)
if matches:
for match in matches:
num_fps = num_fps + 1
fp = FIXFP_RE.sub("", match)
keyid = keyid_from_fp(fp)
tmp = data.copy()
tmp.update({"fingerprint": fp, "keyid": keyid})
keys.append(tmp)
fp = "wonk"
print(
"Found %s keys in mbox: %s fingerprints and %s full keys"
% (len(keys), num_fps, num_keys)
)
return keys
class KeyringBuilder:
"""A class for building and managing keyrings."""
AUTO_OPTS = GPG_FD_OPTS + [
"--command-fd", "0",
"--status-fd", "1",
"--no-options",
"--with-colons",
]
def __init__(self, gpg_path, keyring, keyservers, tmp_dir):
self.gpg = gpg_path
if os.path.exists(keyring):
self.keyring = keyring
self.exported_keyring = None
else:
keyring_dir, keyring_file = os.path.split(keyring)
self.keyring = os.path.join(keyring_dir, ".pius." + keyring_file)
self.exported_keyring = keyring
self.found = []
self.notfound = []
self.keyservers = keyservers
self.tmp_dir = tmp_dir
self.party = ""
self.basecmd = [self.gpg] + GPG_BASE_OPTS + ["--keyring", self.keyring]
def num_not_found(self):
return len(self.notfound)
#
# BEGIN INTERNAL FUNCTIONS
#
def _tmpfile_path(self, tfile):
"""Internal function to take a filename and put it in self.tmp_dir."""
return "%s/%s" % (self.tmp_dir, tfile)
def _remove_file(self, tfile):
if os.path.exists(tfile):
os.unlink(tfile)
def _printable_fingerprint(self, fp):
"""Given a whitespace-collapsed FP, print it in friendly format."""
return "%s %s %s %s %s %s %s %s %s %s" % (
fp[0:4],
fp[4:8],
fp[8:12],
fp[12:16],
fp[16:20],
fp[20:24],
fp[24:28],
fp[28:32],
fp[32:36],
fp[36:40],
)
def _import_key_file(self, kfile):
"""Given a keyfile, import it into our keyring."""
extra_opts = GPG_QUIET_OPTS + self.AUTO_OPTS
cmd = self.basecmd + extra_opts + ["--import", kfile]
util.logcmd(cmd)
gpg = subprocess.Popen(
cmd,
shell=False,
stdin=None,
close_fds=True,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
for line in gpg.stdout:
parts = line.strip().split(" ")
if parts[1] == "IMPORTED":
print(
"Importing %s (%s)" % (parts[2][8:16], " ".join(parts[3:]))
)
gpg.wait()
retval = gpg.returncode
if retval != 0:
return False
return True
def _write_and_import_key(self, key):
"""Write out key to a file and call _import_key_file() on it."""
# FIXME
filename = self._tmpfile_path("pius_keyring_mgr.tmp.txt")
fh = open(filename, "w")
fh.write(key["key"])
fh.close()
self._import_key_file(filename)
self._remove_file(filename)
def _print_list(self, keylist):
"""Helper function for print_report."""
for key in keylist:
print(
" %s <%s>\n %s"
% (
key["name"],
key["email"],
self._printable_fingerprint(key["fingerprint"]),
)
)
def _get_email_body(self, keyinfo, mailer):
kstext = " " + "\n ".join(self.keyservers)
interp = {
"name": keyinfo["name"],
"email": keyinfo["email"],
"from": mailer.from_addr,
"fp": self._printable_fingerprint(keyinfo["fingerprint"]),
"party": self.party,
"keyservers": kstext,
"keyserver": self.keyservers[0],
}
to = """%(name)s <%(email)s>""" % interp
subject = (
"""%(party)sPGP Keysignign Party: Can't find your key!""" % interp
)
body = ""
if mailer.mail_text():
body = open(mailer.mail_text(), "r").read() % interp
else:
body = DEFAULT_EMAIL_TEXT % interp
return (to, subject, body)
def _send_email(self, mailer, keyinfo):
to, subject, body = self._get_email_body(keyinfo, mailer)
print("Sending mail to %s" % to)
mailer.send_mail(to, subject, body)
#
# BEGIN PUBLIC FUNCTIONS
#
def have_key(self, key):
cmd = self.basecmd + GPG_QUIET_OPTS + ["--fingerprint", key]
gpg = subprocess.Popen(
cmd,
shell=False,
stdin=None,
close_fds=True,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
gpg.wait()
retval = gpg.returncode
if retval == 0:
print("Already have %s" % key)
return True
return False
def get_key(self, key):
"""Try to get key from any keyservers we know about."""
basecmd = (
self.basecmd + GPG_QUIET_OPTS + ["--keyserver-options", "timeout=2"]
)
found = False
for ks in self.keyservers:
cmd = basecmd + ["--keyserver", ks, "--recv-key", key]
util.logcmd(cmd)
gpg = subprocess.Popen(
cmd,
shell=False,
stdin=None,
close_fds=True,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
gpg.wait()
retval = gpg.returncode
if retval == 0:
found = True
print("Found %s (%s)" % (key, ks))
break
if not found:
print("NOT Found %s" % key)
return found
def get_all_keys(self, keys):
"""Wrapper to call get_key() on all keys."""
attempted_keyids = []
for key in keys:
if "keyid" in key:
if key["keyid"] == "":
print(
"%s has an old-style key (%s)"
% (key["email"], key["fingerprint"])
)
continue
if key["keyid"] in attempted_keyids:
util.debug("Skipping %s, already processed" % key["keyid"])
continue
attempted_keyids.append(key["keyid"])
# So as not to beat up the keyservers, check if we
# already have a key
if self.have_key(key["keyid"]):
continue
if self.get_key(key["keyid"]):
self.found.append(key)
else:
self.notfound.append(key)
elif "key" in key:
self._write_and_import_key(key)
def print_report(self):
"""Print small report about what was and was not found."""
print("KEYS FOUND:")
self._print_list(self.found)
print("KEYS NOT FOUND:")
self._print_list(self.notfound)
def send_emails(self, mailer, party):
self.party = ""
if party:
self.party = "%s " % party
for k in self.notfound:
self._send_email(mailer, k)
def _backup_keyring(self):
return shutil.copy(self.keyring, "%s-pius-backup" % self.keyring)
# stolen from pius
def get_all_keyids(self, sort_keyring):
"""Given a keyring, get all the KeyIDs from it."""
util.debug("extracting all keyids from keyring, sort: %s" % sort_keyring)
extra_opts = GPG_QUIET_OPTS + self.AUTO_OPTS + ["--fixed-list-mode"]
cmd = self.basecmd + extra_opts + ["--fingerprint"]
util.logcmd(cmd)
gpg = subprocess.Popen(
cmd,
shell=False,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
# We use 'pub' instead of 'fpr' to support old crufty keys too...
pub_re = re.compile("^pub:")
uid_re = re.compile("^uid:")
key_tuples = []
name = keyid = None
for line in gpg.stdout.readlines():
if pub_re.match(line):
lineparts = line.split(":")
keyid = lineparts[4][8:16]
elif keyid and uid_re.match(line):
lineparts = line.split(":")
name = lineparts[9]
util.debug("Got id %s for %s" % (keyid, name))
key_tuples.append((name, keyid))
name = keyid = None
# sort the list
if sort_keyring:
return [i[1] for i in sorted(key_tuples)]
return [i[1] for i in key_tuples]
def export_keyring(self):
"""
If we created a new keyring, it may not be in a suitable format for
sharing. So we go ahead and export it to the real filename which will
force a shareable format. Once it exists, we'll continue to use it.
"""
if self.exported_keyring is None:
util.debug("Not exporting keyring, exported_keyring is None")
return
cmd = (
self.basecmd
+ GPG_QUIET_OPTS
+ ["--export", "--output", self.exported_keyring]
)
util.logcmd(cmd)
subprocess.call(cmd)
# Remove the temp file
os.remove(self.keyring)
# And GPG's backup
backup = self.keyring + "~"
if os.path.exists(backup):
os.remove(backup)
def prune(self, sort_keyring):
self._backup_keyring()
keyids = self.get_all_keyids(sort_keyring)
basecmd = self.basecmd + ["--fingerprint"]
basedelcmd = (
self.basecmd
+ GPG_QUIET_OPTS
+ self.AUTO_OPTS
+ ["--yes", "--delete-key"]
)
for fp in keyids:
cmd = basecmd + [fp]
gpg = subprocess.Popen(
cmd, text=True, shell=False, stdout=subprocess.PIPE
)
for line in gpg.stdout:
print(line.strip())
ans = input(
"Delete this key? ('yes' to delete, 'q' to quit"
" anything to skip) "
)
if ans in ("q", "Q"):
print("Dying at user request")
sys.exit(1)
if ans in ("yes", "y"):
print("Deleting key ...")
cmd = basedelcmd + [fp]
util.logcmd(cmd)
subprocess.call(cmd)
print()
backup = "%s-pius-backup" % self.keyring
print("A backup file is in %s" % backup)
def raw(self, args):
cmd = self.basecmd + args
util.logcmd(cmd)
ret = subprocess.call(cmd, shell=False)
# END class KeyringBuilder
def check_options(parser, mode, options):
"""Check options for user error."""
if mode == "help":
parser.print_help()
sys.exit(0)
if not mode or mode not in ("build", "prune", "raw"):
parser.error("Invalid or missing mode: %s" % mode)
if options.debug:
util.DEBUG_ON = True
if not options.keyring:
parser.error("Must specify a keyring")
if mode == "build":
if (
not options.csv_file
and not options.mbox_file
and not options.flat_file
):
parser.error("Build mode needs one of --csv-file or --mbox-file")
if os.path.exists(options.tmp_dir) and not os.path.isdir(options.tmp_dir):
parser.error(
"%s exists but isn't a directory. It must not exist or be\n"
"a directory." % options.tmp_dir
)
if not os.path.exists(options.tmp_dir):
try:
os.mkdir(options.tmp_dir, 0o700)
except OSError as msg:
parser.error(
"%s was doesn't exist, and was unable to be created: %s"
% (options.tmp_dir, msg)
)
def main():
usage = "%prog <mode> [options]"
intro = """
%prog has several modes to help you manage keyrings. It is primarily designed
to help manage keysigning party rings, but can be used to manage any PGP
keyring. A mode must be the first argument. The options below are grouped by
their mode, and an explanation of modes is at the bottom.
"""
outro = (
"""
Example: %s build --csv-file /tmp/report --mbox-file /tmp/mbox --mail
"""
% sys.argv[0]
)
parser = optparse.OptionParser(
usage=usage,
description=intro,
epilog=outro,
version="%%prog %s" % VERSION,
option_class=piusopt,
)
parser.set_defaults(
delimiter=DEFAULT_CSV_DELIMITER,
name_field=DEFAULT_CSV_NAME_FIELD,
email_field=DEFAULT_CSV_EMAIL_FIELD,
fp_field=DEFAULT_CSV_FP_FIELD,
gpg_path=DEFAULT_GPG_PATH,
party="",
ignore_emails="",
ignore_fps="",
tmp_dir=DEFAULT_TMP_DIR,
)
common = optparse.OptionGroup(parser, "Options common to all modes")
common.add_option(
"-d", "--debug", dest="debug", action="store_true", help="Debug output"
)
common.add_option(
"-g",
"--gpg-path",
dest="gpg_path",
metavar="PATH",
help="Path to gpg binary. [default; %default]",
)
common.add_option(
"-r",
"--keyring",
dest="keyring",
metavar="KEYRING",
nargs=1,
help="Keyring file.",
)
common.add_option(
"-v",
"--verbose",
dest="verbose",
action="store_true",
help="Print summaries",
)
parser.add_option_group(common)
build_intro = """
The "build" mode is the most common mode. It's primary functionality is parsing
a CSV file, attempting to find all the keys, and then emailing anyone whose key
could not be found. For completness sake, it can also import keys from a file.
Options for 'build' mode"""
build = optparse.OptionGroup(parser, build_intro)
build.add_option(
"-b",
"--mbox-file",
dest="mbox_file",
metavar="FILE",
help="Parse mbox FILE, examining each message for"
" fingerprints or ascii-armored keys. Tries to be as"
" intelligent as possible here, including decoding"
" messages as necessary.",
)
build.add_option(
"-c",
"--csv-file",
dest="csv_file",
metavar="FILE",
help="Parse FILE as a CSV and import keys. You will almost"
" want -D, -E, -F, and -N to control CSV parsing.",
)
build.add_option(
"--delimiter",
dest="delimiter",
metavar="DELIMITER",
help="Only meaningful with -c. Field delimiter to use when"
" parsing the CSV. [default: %default]",
)
build.add_option(
"-E",
"--email-field",
dest="email_field",
metavar="FIELD",
type="int",
help="Only meaningful with -c. The field number of the CSV"
" where the email is. [default: %default]",
)
build.add_option(
"-f",
"--flat-file",
dest="flat_file",
metavar="FILE",
help="Parse flat file FILE for fingerprints.",
)
build.add_option(
"-F",
"--fp-field",
dest="fp_field",
metavar="FIELD",
type="int",
help="Only meaningful with -c. The field number of the CSV"
" where the fingerprint is. [default: %default]",
)
build.add_option(
"-m",
"--mail",
dest="mail",
metavar="EMAIL",
help="Email people whos keys were not found, using EMAIL",
)
build.add_option(
"-N",
"--name-field",
dest="name_field",
metavar="FIELD",
type="int",
help="Only meaningful with -c. The field number of the CSV"
" where the name is. [default: %default]",
)
build.add_option(
"-p",
"--party",
dest="party",
metavar="NAME",
nargs=1,
help="The name of the party. This will be printed in the"
" emails sent out. Only useful with -m.",
)
build.add_option(
"-s",
"--keyservers",
dest="keyservers",
metavar="KEYSERVER",
action="append",
help=(
"Keyservers to try. Specify this option once for each"
"server (-s foo -s bar). [default: %s]"
% ", ".join(DEFAULT_KEYSERVERS)
),
)
build.add_option(
"-t",
"--tmp-dir",
dest="tmp_dir",
help="Directory to put temporary stuff in. [default:" " %default]",
)
build.add_option(
"-T",
"--print-default-email",
dest="print_default_email",
action="store_true",
help="Print the default email.",
)
build.add_option(
"--ignore-emails",
dest="ignore_emails",
help="Comma-separated list of emails to ignore.",
)
build.add_option(
"--ignore-fingerprints",
dest="ignore_fps",
help="Comma-separated list of fingerprints to ignore - no" " spaces.",
)
pmailer.PiusMailer.add_options(parser, build)
parser.add_option_group(build)
prune_intro = """
The "prune" mode asks about each key on a keyring and removes one you specify.
This is useful for trimming a keyring of people who didn't show after a party
before distributing they keyring.
Options for 'prune' mode"""
prune = optparse.OptionGroup(parser, prune_intro)
prune.add_option(
"--no-sort-keyring",
dest="sort_keyring",
default=True,
action="store_false",
help="Do not sort the keyring by name.",
)
parser.add_option_group(prune)
raw_intro = """
The "raw" mode allows you pass gpg options which will be run for you. The
options will be added to the options necessary to operate on the keyring safely
(to load only the party keyring, not your keyring). This is primary useful for
adding keys manually. All such options should be passed after a '--' to prevent
pius-keyring-manager interpreting them as options to itself. Example:
pius-keyring-manager raw -r path/to/keyring.gpg -- --recv-key <keyid>
There are no options"""
raw = optparse.OptionGroup(parser, raw_intro)
parser.add_option_group(raw)
all_opts = util.parse_dotfile(parser)
all_opts.extend(sys.argv[1:])
(options, args) = parser.parse_args(all_opts)
mode = None
if args:
mode = args.pop(0)
if options.print_default_email:
print_default_email()
sys.exit(0)
check_options(parser, mode, options)
# We can't set this as a default above because 'append' will not allow
# users to completely override the list
if not options.keyservers:
options.keyservers = DEFAULT_KEYSERVERS
kb = KeyringBuilder(
options.gpg_path, options.keyring, options.keyservers, options.tmp_dir
)
if mode == "prune":
kb.prune(options.sort_keyring)
elif mode == "raw":
kb.raw(args)
elif mode == "build":
keys = []
if options.mbox_file:
keys = PiusParser.parse_mbox(options.mbox_file)
if options.csv_file:
keys.extend(
PiusParser.parse_csv(
options.csv_file,
options.delimiter,
options.name_field,
options.email_field,
options.fp_field,
options.ignore_emails,
options.ignore_fps,
)
)
if options.flat_file:
keys.extend(PiusParser.parse_flatfile(options.flat_file))
if not keys:
print("No keys IDs extract from CSV/mbox")
sys.exit(0)
if keys:
kb.get_all_keys(keys)
if options.verbose:
kb.print_report()
if options.mail and kb.num_not_found() > 0:
print(
"Preparing to send out emails to those whose keys were not found"
)
mailer = pmailer.PiusMailer(
options.mail,
options.display_name,
options.mail_host,
options.mail_port,
options.mail_user,
options.mail_tls,
options.mail_ssl,
options.mail_no_pgp_mime,
options.mail_override,
options.mail_text,
options.tmp_dir,
)
kb.send_emails(mailer, options.party)
else:
print("Unrecognized mode %s" % mode)
sys.exit(1)
# No matter what, we need to export into a common format
kb.export_keyring()
if __name__ == "__main__":
main()