added helpful comment
[edward.git] / edward
CommitLineData
0bec96d6 1#! /usr/bin/env python3
ff4136c7 2# -*- coding: utf-8 -*-
0bec96d6
AE
3"""*********************************************************************
4* Edward is free software: you can redistribute it and/or modify *
5* it under the terms of the GNU Affero Public License as published by *
6* the Free Software Foundation, either version 3 of the License, or *
7* (at your option) any later version. *
8* *
9* Edward is distributed in the hope that it will be useful, *
10* but WITHOUT ANY WARRANTY; without even the implied warranty of *
11* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12* GNU Affero Public License for more details. *
13* *
14* You should have received a copy of the GNU Affero Public License *
15* along with Edward. If not, see <http://www.gnu.org/licenses/>. *
16* *
17* Copyright (C) 2014-2015 Andrew Engelbrecht (AGPLv3+) *
18* Copyright (C) 2014 Josh Drake (AGPLv3+) *
19* Copyright (C) 2014 Lisa Marie Maginnis (AGPLv3+) *
8bdfb6d4
AE
20* Copyright (C) 2009-2015 Tails developers <tails@boum.org> ( GPLv3+) *
21* Copyright (C) 2009 W. Trevor King <wking@drexel.edu> ( GPLv2+) *
0bec96d6
AE
22* *
23* Special thanks to Josh Drake for writing the original edward bot! :) *
24* *
25************************************************************************
26
a5385c04 27Code sourced from these projects:
0bec96d6 28
dfe75896 29 * http://agpl.fsf.org/emailselfdefense.fsf.org/edward/PREVIOUS-20150530/edward.tar.gz
8bdfb6d4
AE
30 * https://git-tails.immerda.ch/whisperback/tree/whisperBack/encryption.py?h=feature/python3
31 * http://www.physics.drexel.edu/~wking/code/python/send_pgp_mime
0bec96d6
AE
32"""
33
0bec96d6
AE
34import re
35import io
40c37ab3 36import os
2f4ce2b2 37import sys
0fd3389f 38import enum
2f4ce2b2 39import gpgme
a9eaa792 40import smtplib
adcef2f7 41import importlib
0bec96d6 42
8bdfb6d4
AE
43import email.parser
44import email.message
45import email.encoders
46
e5dd6f23 47from email.mime.text import MIMEText
8bdfb6d4
AE
48from email.mime.multipart import MIMEMultipart
49from email.mime.application import MIMEApplication
50from email.mime.nonmultipart import MIMENonMultipart
51
40c37ab3 52import edward_config
c96f3837 53
01ceaec3 54langs = ["de", "el", "en", "es", "fr", "it", "ja", "pt-br", "ro", "ru", "tr"]
adcef2f7 55
def9196c
AE
56"""This list contains the abbreviated names of reply languages available to
57edward."""
58
0fd3389f
AE
59class TxtType (enum.Enum):
60 text = 0
61 message = 1
62 pubkey = 2
63 detachedsig = 3
64 signature = 4
def9196c 65
0fd3389f 66
2f4102b9 67match_pairs = [(TxtType.message,
56578eaf 68 '-----BEGIN PGP MESSAGE-----.*?-----END PGP MESSAGE-----'),
0fd3389f 69 (TxtType.pubkey,
56578eaf 70 '-----BEGIN PGP PUBLIC KEY BLOCK-----.*?-----END PGP PUBLIC KEY BLOCK-----'),
0fd3389f 71 (TxtType.detachedsig,
38738401 72 '-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----')]
56578eaf 73
def9196c
AE
74"""This list of tuples matches query names with re.search() queries used
75to find GPG data for edward to process."""
76
56578eaf
AE
77
78class EddyMsg (object):
def9196c
AE
79 """
80 The EddyMsg class represents relevant parts of a mime message.
81
82 The represented message can be single-part or multi-part.
83
84 'multipart' is set to True if there are multiple mime parts.
85
86 'subparts' points to a list of mime sub-parts if it is a multi-part
87 message. Otherwise it points to an empty list.
88
6d8faaa7
AE
89 'payload_bytes' is a binary representation of the mime part before header
90 removal and message decoding.
def9196c
AE
91
92 'payload_pieces' is a list of objects containing strings that when strung
93 together form the fully-decoded string representation of the mime part.
94
c00930e9
AE
95 The 'filename', 'content_type', 'content_disposition' and
96 'description_list' come from the mime part parameters.
97
def9196c
AE
98 """
99
7d0b91d2
AE
100 multipart = False
101 subparts = []
56578eaf 102
7d0b91d2
AE
103 payload_bytes = None
104 payload_pieces = []
56578eaf 105
7d0b91d2
AE
106 filename = None
107 content_type = None
c00930e9 108 content_disposition = None
7d0b91d2 109 description_list = None
56578eaf
AE
110
111
112class PayloadPiece (object):
def9196c
AE
113 """
114 PayloadPiece represents a complte or sub-section of a mime part.
115
116 Instances of this class are often strung together within one or more arrays
117 pointed to by each instance of the EddyMsg class.
118
0fd3389f
AE
119 'piece_type' refers to an enum whose value describes the content of
120 'string'. Examples include TxtType.pubkey, for public keys, and
121 TxtType.message, for encrypted data (or armored signatures until they are
122 known to be such.) Some of the names derive from the header and footer of
123 each of these ascii-encoded gpg blocks.
def9196c
AE
124
125 'string' contains some string of text, such as non-GPG text, an encrypted
126 block of text, a signature, or a public key.
127
128 'gpg_data' points to any instances of GPGData that have been created based
129 on the contents of 'string'.
130 """
131
7d0b91d2
AE
132 piece_type = None
133 string = None
134 gpg_data = None
56578eaf
AE
135
136
38738401 137class GPGData (object):
def9196c
AE
138 """
139 GPGData holds info from decryption, sig. verification, and/or pub. keys.
140
141 Instances of this class contain decrypted information, signature
142 fingerprints and/or fingerprints of processed and imported public keys.
143
144 'decrypted' is set to True if 'plainobj' was created from encrypted data.
145
146 'plainobj' points to any decrypted, or signed part of, a GPG signature. It
147 is intended to be an instance of the EddyMsg class.
148
149 'sigs' is a list of fingerprints of keys used to sign the data in plainobj.
150
b4c116d5
AE
151 'sigkey_missing' is set to True if edward doesn't have the key it needs to
152 verify the signature on a block of text.
9af26cb8 153
c035a008 154 'key_cannot_encrypt' is set to True if pubkeys or sigs' keys in the payload
e6d33a68 155 piece are not capable of encryption, are revoked or expired, for instance.
c035a008 156
def9196c
AE
157 'keys' is a list of fingerprints of keys obtained in public key blocks.
158 """
159
7d0b91d2
AE
160 decrypted = False
161
162 plainobj = None
163 sigs = []
b4c116d5 164 sigkey_missing = False
c035a008 165 key_cannot_encrypt = False
7d0b91d2 166 keys = []
38738401 167
38738401 168
d873ff48 169class ReplyInfo (object):
def9196c
AE
170 """
171 ReplyInfo contains details that edward uses in generating its reply.
172
173 Instances of this class contain information about whether a message was
174 successfully encrypted or signed, and whether a public key was attached, or
175 retrievable, from the local GPG store. It stores the fingerprints of
176 potential encryption key candidates and the message (if any at all) to
177 quote in edward's reply.
178
179 'replies' points one of the dictionaries of translated replies.
180
181 'target_key' refers to the fingerprint of a key used to sign encrypted
182 data. This is the preferred key, if it is set, and if is available.
183
184 'fallback_target_key' referst to the fingerprint of a key used to sign
185 unencrypted data; alternatively it may be a public key attached to the
186 message.
187
ca37d0cb
AE
188 'encrypt_to_key' the key object to use when encrypting edward's reply
189
def9196c
AE
190 'msg_to_quote' refers to the part of a message which edward should quote in
191 his reply. This should remain as None if there was no encrypted and singed
192 part. This is to avoid making edward a service for decrypting other
193 people's messages to edward.
194
b4c116d5 195 'decrypt_success' is set to True if edward could decrypt part of the
def9196c
AE
196 message.
197
def9196c
AE
198 'sig_success' is set to True if edward could to some extent verify the
199 signature of a signed part of the message to edward.
200
c035a008
AE
201 'key_can_encrypt' is set to True if a key which can be encrypted to has
202 been found.
203
32a8996f
AE
204 'sig_failure' is set to True if edward could not verify a siganture.
205
b4c116d5
AE
206 'pubkey_success' is set to True if edward successfully imported a public
207 key.
208
209 'sigkey_missing' is set to True if edward doesn't have the public key
210 needed for signature verification.
211
c035a008
AE
212 'key_cannot_encrypt' is set to True if pubkeys or sig's keys in a payload
213 piece of the message are not capable of encryption.
214
b4c116d5
AE
215 'have_repy_key' is set to True if edward has a public key to encrypt its
216 reply to.
def9196c
AE
217 """
218
7d0b91d2 219 replies = None
6906d46d 220
7d0b91d2
AE
221 target_key = None
222 fallback_target_key = None
ca37d0cb 223 encrypt_to_key = None
7d0b91d2 224 msg_to_quote = ""
d873ff48 225
b4c116d5 226 decrypt_success = False
7d0b91d2 227 sig_success = False
b4c116d5 228 pubkey_success = False
c035a008 229 key_can_encrypt = False
b4c116d5 230
4e2c66f7 231 decrypt_failure = False
32a8996f 232 sig_failure = False
b4c116d5 233 sigkey_missing = False
c035a008 234 key_cannot_encrypt = False
371911ad 235
b4c116d5 236 have_reply_key = False
d873ff48 237
38738401 238
0bec96d6
AE
239def main ():
240
def9196c
AE
241 """
242 This is the main function for edward, a GPG reply bot.
243
244 Edward responds to GPG-encrypted and signed mail, encrypting and signing
245 the response if the user's public key is, or was, included in the message.
246
247 Args:
248 None
249
250 Returns:
a3d6aff8 251 Nothing
def9196c
AE
252
253 Pre:
254 Mime or plaintext email passing in through standard input. Portions of
255 the email may be encrypted. If the To: address contains the text
256 "edward-ja", then the reply will contain a reply written in the
257 Japanese language. There are other languages as well. The default
258 language is English.
259
260 Post:
261 A reply email will be printed to standard output. The contents of the
262 reply email depends on whether the original email was encrypted or not,
263 has or doesn't have a signature, whether a public key used in the
264 original message is provided or locally stored, and the language
265 implied by the To: address in the original email.
266 """
267
60ccbaf4 268 print_reply_only = handle_args()
0bec96d6 269
0a064403
AE
270 gpgme_ctx = get_gpg_context(edward_config.gnupghome,
271 edward_config.sign_with_key)
272
85a829fc 273 email_bytes = sys.stdin.buffer.read()
b93c3c29 274
70da0811 275 # do this twice so sigs can be verified with newly imported keys
b93c3c29 276 parse_pgp_mime(email_bytes, gpgme_ctx)
85a829fc 277 email_struct = parse_pgp_mime(email_bytes, gpgme_ctx)
adcef2f7 278
140c47ca 279 email_to, email_reply_to, email_subject = email_to_reply_to_subject(email_bytes)
60ccbaf4 280 lang, reply_from = import_lang_pick_address(email_to, edward_config.hostname)
fafa21c3 281
d873ff48
AE
282 replyinfo_obj = ReplyInfo()
283 replyinfo_obj.replies = lang.replies
284
285 prepare_for_reply(email_struct, replyinfo_obj)
ca37d0cb 286 get_key_from_fp(replyinfo_obj, gpgme_ctx)
d873ff48 287 reply_plaintext = write_reply(replyinfo_obj)
adcef2f7 288
140c47ca 289 reply_mime = generate_encrypted_mime(reply_plaintext, email_reply_to, \
ca37d0cb 290 email_subject, replyinfo_obj.encrypt_to_key,
2007103e 291 gpgme_ctx)
1fccb295 292
60ccbaf4
AE
293 if print_reply_only == True:
294 print(reply_mime)
295 else:
140c47ca 296 send_reply(reply_mime, email_reply_to, reply_from)
c96f3837 297
0bec96d6 298
0a064403 299def get_gpg_context (gnupghome, sign_with_key_fp):
a3d6aff8
AE
300 """
301 This function returns the GPG context needed for encryption and signing.
302
303 The context is needed by other functions which use GPG functionality.
304
305 Args:
306 gnupghome: The path to "~/.gnupg/" or its alternative.
307 sign_with_key: The fingerprint of the key to sign with
308
309 Returns:
310 A gpgme context to be used for GPG functions.
311
312 Post:
313 the 'armor' flag is set to True and the list of signing keys contains
314 the single specified key
315 """
0a064403
AE
316
317 os.environ['GNUPGHOME'] = gnupghome
318
319 gpgme_ctx = gpgme.Context()
320 gpgme_ctx.armor = True
321
322 try:
323 sign_with_key = gpgme_ctx.get_key(sign_with_key_fp)
5f6f32b1 324 except gpgme.GpgmeError:
0a064403
AE
325 error("unable to load signing key. is the gnupghome "
326 + "and signing key properly set in the edward_config.py?")
327 exit(1)
328
329 gpgme_ctx.signers = [sign_with_key]
330
331 return gpgme_ctx
332
333
85a829fc 334def parse_pgp_mime (email_bytes, gpgme_ctx):
a3d6aff8
AE
335 """Parses the email for mime payloads and decrypts/verfies signatures.
336
337 This function creates a representation of a mime or plaintext email with
338 the EddyMsg class. It then splits each mime payload into one or more pieces
339 which may be plain text or GPG data. It then decrypts encrypted parts and
340 does some very basic signature verification on those parts.
341
342 Args:
85a829fc 343 email_bytes: an email message in byte string format
a3d6aff8
AE
344 gpgme_ctx: a gpgme context
345
346 Returns:
347 A message as an instance of EddyMsg
348
349 Post:
350 the returned EddyMsg instance has split, decrypted, verified and pubkey
351 imported payloads
352 """
394a1476 353
85a829fc 354 email_struct = email.parser.BytesParser().parsebytes(email_bytes)
394a1476 355
928e3819
AE
356 eddymsg_obj = parse_mime(email_struct)
357 split_payloads(eddymsg_obj)
358 gpg_on_payloads(eddymsg_obj, gpgme_ctx)
8bb4b0d5 359
928e3819 360 return eddymsg_obj
0bec96d6 361
0bec96d6 362
56578eaf 363def parse_mime(msg_struct):
a3d6aff8
AE
364 """Translates python's email.parser format into an EddyMsg format
365
366 If the message is multi-part, then a recursive object is created, where
367 each sub-part is also a EddyMsg instance.
368
369 Args:
3dad6a92 370 msg_struct: an email parsed with email.parser.BytesParser(), which can be
a3d6aff8
AE
371 multi-part
372
373 Returns:
374 an instance of EddyMsg, potentially a recursive one.
375 """
0bec96d6 376
158ddbca 377 eddymsg_obj = get_subpart_data(msg_struct)
8bb4b0d5 378
56578eaf
AE
379 if msg_struct.is_multipart() == True:
380 payloads = msg_struct.get_payload()
0bec96d6 381
928e3819
AE
382 eddymsg_obj.multipart = True
383 eddymsg_obj.subparts = list(map(parse_mime, payloads))
dd11a483 384
928e3819 385 return eddymsg_obj
c267c233 386
80119cab 387
2f4102b9 388def scan_and_split (payload_piece, match_name, pattern):
a3d6aff8
AE
389 """This splits the payloads of an EddyMsg object into GPG and text parts.
390
391 An EddyMsg object's payload_pieces starts off as a list containing a single
392 PayloadPiece object. This function returns a list of these objects which
393 have been split into GPG data and regular text, if such splits need to be/
394 can be made.
395
396 Args:
397 payload_piece: a single payload or a split part of a payload
2f4102b9 398 match_name: the type of data to try to spit out from the payload piece
a3d6aff8
AE
399 pattern: the search pattern to be used for finding that type of data
400
401 Returns:
402 a list of objects of the PayloadPiece class, in the order that the
403 string part of payload_piece originally was, broken up according to
404 matches specified by 'pattern'.
405 """
cf75de65 406
a5d37d44 407 # don't try to re-split pieces containing gpg data
0fd3389f 408 if payload_piece.piece_type != TxtType.text:
a5d37d44
AE
409 return [payload_piece]
410
56578eaf 411 flags = re.DOTALL | re.MULTILINE
b8a80a18 412 matches = re.search(pattern, payload_piece.string, flags=flags)
86663388 413
56578eaf
AE
414 if matches == None:
415 pieces = [payload_piece]
c96f3837 416
56578eaf 417 else:
d437f8b2 418
56578eaf 419 beginning = PayloadPiece()
b8a80a18 420 beginning.string = payload_piece.string[:matches.start()]
56578eaf 421 beginning.piece_type = payload_piece.piece_type
d437f8b2 422
56578eaf 423 match = PayloadPiece()
b8a80a18 424 match.string = payload_piece.string[matches.start():matches.end()]
2f4102b9 425 match.piece_type = match_name
d437f8b2 426
56578eaf 427 rest = PayloadPiece()
b8a80a18 428 rest.string = payload_piece.string[matches.end():]
56578eaf 429 rest.piece_type = payload_piece.piece_type
d437f8b2 430
2f4102b9 431 more_pieces = scan_and_split(rest, match_name, pattern)
4615b156 432 pieces = [beginning, match ] + more_pieces
d437f8b2 433
56578eaf 434 return pieces
d437f8b2 435
d437f8b2 436
56578eaf 437def get_subpart_data (part):
a32a1e11 438 """This function grabs information from a mime part.
a3d6aff8 439
3dad6a92 440 It copies needed data from an email.parser.BytesParser() object over to an
a32a1e11 441 EddyMsg object.
a3d6aff8
AE
442
443 Args:
3dad6a92 444 part: an email.parser.BytesParser() object
a3d6aff8
AE
445
446 Returns:
a32a1e11 447 an EddyMsg() object
a3d6aff8 448 """
0bec96d6 449
6d8faaa7 450 obj = EddyMsg()
56578eaf 451
84ff9773
AE
452 mime_decoded_bytes = part.get_payload(decode=True)
453 charset = part.get_content_charset()
56578eaf
AE
454
455 # your guess is as good as a-myy-ee-ine...
6d8faaa7
AE
456 if charset == None:
457 charset = 'utf-8'
56578eaf 458
84ff9773
AE
459 payload_string = part.as_string()
460 if payload_string != None:
9c348860
AE
461 # convert each isolated carriage return or line feed to carriage return + line feed
462 payload_string_crlf = re.sub(r'\n', '\r\n', re.sub(r'\r', '\n', re.sub(r'\r\n', '\n', payload_string)))
463 obj.payload_bytes = payload_string_crlf.encode(charset)
84ff9773
AE
464
465 obj.filename = part.get_filename()
466 obj.content_type = part.get_content_type()
c00930e9 467 obj.content_disposition = part['content-disposition']
84ff9773
AE
468 obj.description_list = part['content-description']
469
6d8faaa7 470 if mime_decoded_bytes != None:
0eb75d9c
AE
471 try:
472 payload = PayloadPiece()
6d8faaa7 473 payload.string = mime_decoded_bytes.decode(charset)
0fd3389f 474 payload.piece_type = TxtType.text
0eb75d9c
AE
475
476 obj.payload_pieces = [payload]
477 except UnicodeDecodeError:
478 pass
56578eaf
AE
479
480 return obj
481
482
928e3819 483def do_to_eddys_pieces (function_to_do, eddymsg_obj, data):
a3d6aff8
AE
484 """A function which maps another function onto a message's subparts.
485
486 This is a higer-order function which recursively performs a specified
487 function on each subpart of a multi-part message. Each single-part sub-part
488 has the function applied to it. This function also works if the part passed
489 in is single-part.
490
491 Args:
492 function_to_do: function to perform on sub-parts
493 eddymsg_obj: a single part or multi-part EddyMsg object
494 data: a second argument to pass to 'function_to_do'
495
496 Returns:
497 Nothing
498
499 Post:
500 The passed-in EddyMsg object is transformed recursively on its
501 sub-parts according to 'function_to_do'.
502 """
56578eaf 503
928e3819
AE
504 if eddymsg_obj.multipart == True:
505 for sub in eddymsg_obj.subparts:
d873ff48 506 do_to_eddys_pieces(function_to_do, sub, data)
394a1476 507 else:
928e3819 508 function_to_do(eddymsg_obj, data)
dd11a483
AE
509
510
928e3819 511def split_payloads (eddymsg_obj):
a3d6aff8
AE
512 """Splits all (sub-)payloads of a message into GPG data and regular text.
513
514 Recursively performs payload splitting on all sub-parts of an EddyMsg
515 object into the various GPG data types, such as GPG messages, public key
516 blocks and signed text.
517
518 Args:
519 eddymsg_obj: an instance of EddyMsg
520
521 Returns:
522 Nothing
523
524 Pre:
525 The EddyMsg object has payloads that are unsplit (by may be split)..
526
527 Post:
528 The EddyMsg object's payloads are all split into GPG and non-GPG parts.
529 """
a5d37d44 530
2f4102b9
AE
531 for match_pair in match_pairs:
532 do_to_eddys_pieces(split_payload_pieces, eddymsg_obj, match_pair)
a5d37d44 533
a5d37d44 534
2f4102b9 535def split_payload_pieces (eddymsg_obj, match_pair):
a3d6aff8
AE
536 """A helper function for split_payloads(); works on PayloadPiece objects.
537
538 This function splits up PayloadPiece objects into multipe PayloadPiece
539 objects and replaces the EddyMsg object's previous list of payload pieces
540 with the new split up one.
541
542 Args:
543 eddymsg_obj: a single-part EddyMsg object.
2f4102b9 544 match_pair: a tuple from the match_pairs list, which specifies a match
a3d6aff8
AE
545 name and a match pattern.
546
547 Returns:
548 Nothing
549
550 Pre:
551 The payload piece(s) of an EddyMsg object may be already split or
552 unsplit.
553
554 Post:
555 The EddyMsg object's payload piece(s) are split into a list of pieces
2f4102b9 556 if matches of the match_pair are found.
a3d6aff8 557 """
a5d37d44 558
2f4102b9 559 (match_name, pattern) = match_pair
a5d37d44
AE
560
561 new_pieces_list = []
928e3819 562 for piece in eddymsg_obj.payload_pieces:
a5d37d44
AE
563 new_pieces_list += scan_and_split(piece, match_name, pattern)
564
928e3819 565 eddymsg_obj.payload_pieces = new_pieces_list
a5d37d44
AE
566
567
928e3819 568def gpg_on_payloads (eddymsg_obj, gpgme_ctx, prev_parts=[]):
a3d6aff8
AE
569 """Performs GPG operations on the GPG parts of the message
570
571 This function decrypts text, verifies signatures, and imports public keys
572 included in an email.
573
574 Args:
575 eddymsg_obj: an EddyMsg object with its payload_pieces split into GPG
576 and non-GPG sections by split_payloads()
577 gpgme_ctx: a gpgme context
578
579 prev_parts: a list of mime parts that occur before the eddymsg_obj
580 part, under the same multi-part mime part. This is used for
581 verifying detached signatures. For the root mime part, this should
582 be an empty list, which is the default value if this paramater is
583 omitted.
584
585 Return:
586 Nothing
587
588 Pre:
589 eddymsg_obj should have its payloads split into gpg and non-gpg pieces.
590
591 Post:
c035a008
AE
592 Decryption, verification and key imports occur. the gpg_data members of
593 PayloadPiece objects get filled in with GPGData objects with some of
594 their attributes set.
a3d6aff8 595 """
38738401 596
928e3819 597 if eddymsg_obj.multipart == True:
101d54a8 598 prev_parts=[]
928e3819 599 for sub in eddymsg_obj.subparts:
101d54a8
AE
600 gpg_on_payloads (sub, gpgme_ctx, prev_parts)
601 prev_parts += [sub]
38738401 602
d873ff48 603 return
38738401 604
928e3819 605 for piece in eddymsg_obj.payload_pieces:
38738401 606
0fd3389f 607 if piece.piece_type == TxtType.text:
38738401
AE
608 # don't transform the plaintext.
609 pass
610
0fd3389f 611 elif piece.piece_type == TxtType.message:
b4c116d5
AE
612 piece.gpg_data = GPGData()
613
c035a008 614 (plaintext_b, sigs, sigkey_missing, key_cannot_encrypt) = decrypt_block(piece.string, gpgme_ctx)
b4c116d5
AE
615
616 piece.gpg_data.sigkey_missing = sigkey_missing
c035a008 617 piece.gpg_data.key_cannot_encrypt = key_cannot_encrypt
38738401 618
85a829fc 619 if plaintext_b:
b23e171d 620 piece.gpg_data.decrypted = True
38738401
AE
621 piece.gpg_data.sigs = sigs
622 # recurse!
85a829fc 623 piece.gpg_data.plainobj = parse_pgp_mime(plaintext_b, gpgme_ctx)
3a753fd0
AE
624 continue
625
626 # if not encrypted, check to see if this is an armored signature.
c035a008 627 (plaintext_b, sigs, sigkey_missing, key_cannot_encrypt) = verify_sig_message(piece.string, gpgme_ctx)
b4c116d5
AE
628
629 piece.gpg_data.sigkey_missing = sigkey_missing
c035a008 630 piece.gpg_data.key_cannot_encrypt = key_cannot_encrypt
3a753fd0 631
85a829fc 632 if plaintext_b:
0fd3389f 633 piece.piece_type = TxtType.signature
3a753fd0
AE
634 piece.gpg_data.sigs = sigs
635 # recurse!
85a829fc 636 piece.gpg_data.plainobj = parse_pgp_mime(plaintext_b, gpgme_ctx)
129543c3 637
0fd3389f 638 elif piece.piece_type == TxtType.pubkey:
c035a008
AE
639 piece.gpg_data = GPGData()
640
641 (key_fps, key_cannot_encrypt) = add_gpg_key(piece.string, gpgme_ctx)
642
643 piece.gpg_data.key_cannot_encrypt = key_cannot_encrypt
8f61c66a 644
f8ee6bd3 645 if key_fps != []:
f8ee6bd3 646 piece.gpg_data.keys = key_fps
129543c3 647
0fd3389f 648 elif piece.piece_type == TxtType.detachedsig:
b4c116d5
AE
649 piece.gpg_data = GPGData()
650
101d54a8 651 for prev in prev_parts:
c035a008 652 (sig_fps, sigkey_missing, key_cannot_encrypt) = verify_detached_signature(piece.string, prev.payload_bytes, gpgme_ctx)
b4c116d5
AE
653
654 piece.gpg_data.sigkey_missing = sigkey_missing
c035a008 655 piece.gpg_data.key_cannot_encrypt = key_cannot_encrypt
101d54a8 656
6d240f68 657 if sig_fps != []:
6d240f68
AE
658 piece.gpg_data.sigs = sig_fps
659 piece.gpg_data.plainobj = prev
660 break
7e18f14d 661
38738401
AE
662 else:
663 pass
664
665
928e3819 666def prepare_for_reply (eddymsg_obj, replyinfo_obj):
67691346
AE
667 """Updates replyinfo_obj with info on the message's GPG success/failures
668
669 This function marks replyinfo_obj with information about whether encrypted
670 text in eddymsg_obj was successfully decrypted, signatures were verified
671 and whether a public key was found or not.
672
673 Args:
674 eddymsg_obj: a message in the EddyMsg format
675 replyinfo_obj: an instance of ReplyInfo
676
677 Returns:
678 Nothing
679
680 Pre:
681 eddymsg_obj has had its gpg_data created by gpg_on_payloads
682
683 Post:
684 replyinfo_obj has been updated with info about decryption/sig
685 verififcation status, etc. However the desired key isn't imported until
686 later, so the success or failure of that updates the values set here.
687 """
dd11a483 688
928e3819 689 do_to_eddys_pieces(prepare_for_reply_pieces, eddymsg_obj, replyinfo_obj)
56578eaf 690
928e3819 691def prepare_for_reply_pieces (eddymsg_obj, replyinfo_obj):
67691346
AE
692 """A helper function for prepare_for_reply
693
694 It updates replyinfo_obj with GPG success/failure information, when
695 supplied a single-part EddyMsg object.
696
697 Args:
698 eddymsg_obj: a single-part message in the EddyMsg format
699 replyinfo_obj: an object which holds information about the message's
700 GPG status
701
702 Returns:
703 Nothing
704
705 Pre:
706 eddymsg_obj is a single-part message. (it may be a part of a multi-part
707 message.) It has had its gpg_data created by gpg_on_payloads if it has
708 gpg data.
709
710 Post:
711 replyinfo_obj has been updated with gpg success/failure information
712 """
56578eaf 713
928e3819 714 for piece in eddymsg_obj.payload_pieces:
0fd3389f 715 if piece.piece_type == TxtType.text:
d873ff48
AE
716 # don't quote the plaintext part.
717 pass
718
0fd3389f 719 elif piece.piece_type == TxtType.message:
05683768 720 prepare_for_reply_message(piece, replyinfo_obj)
d873ff48 721
0fd3389f 722 elif piece.piece_type == TxtType.pubkey:
05683768 723 prepare_for_reply_pubkey(piece, replyinfo_obj)
6906d46d 724
0fd3389f
AE
725 elif (piece.piece_type == TxtType.detachedsig) \
726 or (piece.piece_type == TxtType.signature):
05683768 727 prepare_for_reply_sig(piece, replyinfo_obj)
d873ff48 728
d873ff48 729
05683768 730def prepare_for_reply_message (piece, replyinfo_obj):
67691346
AE
731 """Helper function for prepare_for_reply()
732
733 This function is called when the piece_type of a payload piece is
9af26cb8
AE
734 TxtType.message, or GPG Message block. This should be encrypted text. If
735 the encryted block is correclty signed, a sig will be attached to
736 .target_key unless there is already one there.
67691346
AE
737
738 Args:
739 piece: a PayloadPiece object.
740 replyinfo_obj: object which gets updated with decryption status, etc.
741
67691346
AE
742 Returns:
743 Nothing
744
745 Pre:
0fd3389f 746 the piece.payload_piece value should be TxtType.message.
67691346
AE
747
748 Post:
b4c116d5 749 replyinfo_obj gets updated with decryption status, signing status, a
c035a008
AE
750 potential signing key, posession status of the public key for the
751 signature and encryption capability status if that key is missing.
67691346 752 """
44fe39b7 753
c035a008 754 if piece.gpg_data.plainobj == None:
4e2c66f7 755 replyinfo_obj.decrypt_failure = True
05683768
AE
756 return
757
b4c116d5 758 replyinfo_obj.decrypt_success = True
05683768
AE
759
760 # we already have a key (and a message)
761 if replyinfo_obj.target_key != None:
762 return
763
c035a008 764 if piece.gpg_data.sigs == []:
b4c116d5
AE
765 if piece.gpg_data.sigkey_missing == True:
766 replyinfo_obj.sigkey_missing = True
9af26cb8 767
c035a008
AE
768 if piece.gpg_data.key_cannot_encrypt == True:
769 replyinfo_obj.key_cannot_encrypt = True
770
05683768
AE
771 # only include a signed message in the reply.
772 get_signed_part = True
773
c035a008
AE
774 else:
775 replyinfo_obj.target_key = piece.gpg_data.sigs[0]
776 replyinfo_obj.sig_success = True
777 get_signed_part = False
778
8c3e5397 779 flatten_decrypted_payloads(piece.gpg_data.plainobj, replyinfo_obj, get_signed_part)
05683768
AE
780
781 # to catch public keys in encrypted blocks
782 prepare_for_reply(piece.gpg_data.plainobj, replyinfo_obj)
783
784
785def prepare_for_reply_pubkey (piece, replyinfo_obj):
67691346
AE
786 """Helper function for prepare_for_reply(). Marks pubkey import status.
787
788 Marks replyinfo_obj with pub key import status.
789
790 Args:
791 piece: a PayloadPiece object
792 replyinfo_obj: a ReplyInfo object
793
794 Pre:
0fd3389f 795 piece.piece_type should be set to TxtType.pubkey .
67691346
AE
796
797 Post:
798 replyinfo_obj has its fields updated.
799 """
05683768 800
c035a008
AE
801 if piece.gpg_data.keys == []:
802 if piece.gpg_data.key_cannot_encrypt == True:
803 replyinfo_obj.key_cannot_encrypt = True
05683768 804 else:
b4c116d5 805 replyinfo_obj.pubkey_success = True
05683768 806
3ceb92e5
AE
807 # prefer public key as a fallback for the encrypted reply
808 replyinfo_obj.fallback_target_key = piece.gpg_data.keys[0]
05683768
AE
809
810
811def prepare_for_reply_sig (piece, replyinfo_obj):
67691346
AE
812 """Helper function for prepare_for_reply(). Marks sig verification status.
813
814 Marks replyinfo_obj with signature verification status.
815
816 Args:
817 piece: a PayloadPiece object
818 replyinfo_obj: a ReplyInfo object
819
820 Pre:
0fd3389f
AE
821 piece.piece_type should be set to TxtType.signature, or
822 TxtType.detachedsig .
67691346
AE
823
824 Post:
825 replyinfo_obj has its fields updated.
826 """
05683768 827
c035a008 828 if piece.gpg_data.sigs == []:
32a8996f 829 replyinfo_obj.sig_failure = True
b4c116d5
AE
830
831 if piece.gpg_data.sigkey_missing == True:
832 replyinfo_obj.sigkey_missing = True
833
c035a008
AE
834 if piece.gpg_data.key_cannot_encrypt == True:
835 replyinfo_obj.key_cannot_encrypt = True
836
05683768
AE
837 else:
838 replyinfo_obj.sig_success = True
839
840 if replyinfo_obj.fallback_target_key == None:
841 replyinfo_obj.fallback_target_key = piece.gpg_data.sigs[0]
6906d46d 842
c230113e
AE
843 if (piece.piece_type == TxtType.signature):
844 # to catch public keys in signature blocks
845 prepare_for_reply(piece.gpg_data.plainobj, replyinfo_obj)
846
6906d46d 847
8c3e5397
AE
848def flatten_decrypted_payloads (eddymsg_obj, replyinfo_obj, get_signed_part):
849 """For creating a string representation of a signed, encrypted part.
39e2c525 850
8c3e5397
AE
851 When given a decrypted payload, it will add either the plaintext or signed
852 plaintext to the reply message, depeding on 'get_signed_part'. This is
853 useful for ensuring that the reply message only comes from a signed and
854 ecrypted GPG message. It also sets the target_key for encrypting the reply
855 if it's told to get signed text only.
39e2c525
AE
856
857 Args:
858 eddymsg_obj: the message in EddyMsg format created by decrypting GPG
859 text
8c3e5397
AE
860 replyinfo_obj: a ReplyInfo object for holding the message to quote and
861 the target_key to encrypt to.
39e2c525
AE
862 get_signed_part: True if we should only include text that contains a
863 further signature. If False, then include plain text.
864
865 Returns:
8c3e5397 866 Nothing
39e2c525
AE
867
868 Pre:
869 The EddyMsg instance passed in should be a piece.gpg_data.plainobj
870 which represents decrypted text. It may or may not be signed on that
871 level.
d873ff48 872
8c3e5397
AE
873 Post:
874 the ReplyInfo instance may have a new 'target_key' set and its
875 'msg_to_quote' will be updated with (possibly signed) plaintext, if any
876 could be found.
877 """
d873ff48 878
0aa88c27 879 if eddymsg_obj == None:
8c3e5397 880 return
0aa88c27 881
0402995a 882 # recurse on multi-part mime
928e3819
AE
883 if eddymsg_obj.multipart == True:
884 for sub in eddymsg_obj.subparts:
8c3e5397 885 flatten_decrypted_payloads(sub, replyinfo_obj, get_signed_part)
d873ff48 886
928e3819 887 for piece in eddymsg_obj.payload_pieces:
0402995a 888 if (get_signed_part):
0fd3389f
AE
889 if ((piece.piece_type == TxtType.detachedsig) \
890 or (piece.piece_type == TxtType.signature)) \
b4c116d5
AE
891 and (piece.gpg_data != None) \
892 and (piece.gpg_data.plainobj != None):
8c3e5397
AE
893 flatten_decrypted_payloads(piece.gpg_data.plainobj, replyinfo_obj, False)
894 replyinfo_obj.target_key = piece.gpg_data.sigs[0]
c3d417bf
AE
895 break
896 else:
c00930e9
AE
897 if (eddymsg_obj.content_disposition == None \
898 or not eddymsg_obj.content_disposition.startswith("attachment")) \
899 and piece.piece_type == TxtType.text:
8c3e5397 900 replyinfo_obj.msg_to_quote += piece.string
d873ff48
AE
901
902
013f7cb8 903def get_key_from_fp (replyinfo_obj, gpgme_ctx):
39e2c525
AE
904 """Obtains a public key object from a key fingerprint
905
ca37d0cb
AE
906 If the .target_key is not set, then we use .fallback_target_key, if
907 available.
39e2c525
AE
908
909 Args:
910 replyinfo_obj: ReplyInfo instance
911 gpgme_ctx: the gpgme context
912
913 Return:
c035a008 914 Nothing
39e2c525
AE
915
916 Pre:
917 Loading a key requires that we have the public key imported. This
918 requires that they email contains the pub key block, or that it was
919 previously sent to edward.
920
921 Post:
ca37d0cb
AE
922 If the key can be loaded, then replyinfo_obj.reply_to_key points to the
923 public key object. If the key cannot be loaded, then the replyinfo_obj
c035a008
AE
924 is marked as having no public key available. If the key is not capable
925 of encryption, it will not be used, and replyinfo_obj will be marked
926 accordingly.
39e2c525 927 """
013f7cb8 928
ca37d0cb
AE
929 for key in (replyinfo_obj.target_key, replyinfo_obj.fallback_target_key):
930 if key != None:
931 try:
932 encrypt_to_key = gpgme_ctx.get_key(key)
c035a008
AE
933
934 except gpgme.GpgmeError:
935 continue
936
c5492aa9 937 if is_key_usable(encrypt_to_key):
ca37d0cb 938 replyinfo_obj.encrypt_to_key = encrypt_to_key
b4c116d5 939 replyinfo_obj.have_reply_key = True
c035a008 940 replyinfo_obj.key_can_encrypt = True
ca37d0cb 941 return
013f7cb8 942
c035a008
AE
943 else:
944 replyinfo_obj.key_cannot_encrypt = True
945
013f7cb8 946
013f7cb8 947
d873ff48 948def write_reply (replyinfo_obj):
39e2c525
AE
949 """Write the reply email body about the GPG successes/failures.
950
951 The reply is about whether decryption, sig verification and key
952 import/loading was successful or failed. If text was successfully decrypted
953 and verified, then the first instance of such text will be included in
954 quoted form.
955
956 Args:
957 replyinfo_obj: contains details of GPG processing status
958
959 Returns:
960 the plaintext message to be sent to the user
961
962 Pre:
963 replyinfo_obj should be populated with info about GPG processing status.
964 """
d873ff48
AE
965
966 reply_plain = ""
967
cfcc211c
AE
968 if (replyinfo_obj.pubkey_success == True):
969 reply_plain += replyinfo_obj.replies['greeting']
970 reply_plain += "\n\n"
971
371911ad 972
b4c116d5 973 if replyinfo_obj.decrypt_success == True:
234f607b 974 debug('decrypt success')
d873ff48 975 reply_plain += replyinfo_obj.replies['success_decrypt']
cfcc211c 976 reply_plain += "\n\n"
d873ff48 977
4e2c66f7 978 elif replyinfo_obj.decrypt_failure == True:
234f607b 979 debug('decrypt failure')
d873ff48 980 reply_plain += replyinfo_obj.replies['failed_decrypt']
b4c116d5 981 reply_plain += "\n\n"
d873ff48 982
371911ad 983
d873ff48 984 if replyinfo_obj.sig_success == True:
234f607b 985 debug('signature success')
d873ff48 986 reply_plain += replyinfo_obj.replies['sig_success']
b4c116d5 987 reply_plain += "\n\n"
d873ff48 988
32a8996f 989 elif replyinfo_obj.sig_failure == True:
234f607b 990 debug('signature failure')
d873ff48 991 reply_plain += replyinfo_obj.replies['sig_failure']
b4c116d5 992 reply_plain += "\n\n"
d873ff48 993
371911ad 994
b4c116d5 995 if (replyinfo_obj.pubkey_success == True):
234f607b 996 debug('public key received')
b4c116d5 997 reply_plain += replyinfo_obj.replies['public_key_received']
d873ff48 998 reply_plain += "\n\n"
d873ff48 999
b4c116d5 1000 elif (replyinfo_obj.sigkey_missing == True):
234f607b 1001 debug('no public key')
b4c116d5 1002 reply_plain += replyinfo_obj.replies['no_public_key']
d873ff48 1003 reply_plain += "\n\n"
d873ff48 1004
c035a008
AE
1005 elif (replyinfo_obj.key_can_encrypt == False) \
1006 and (replyinfo_obj.key_cannot_encrypt == True):
1007 debug('bad public key')
1008 reply_plain += replyinfo_obj.replies['no_public_key']
1009 reply_plain += "\n\n"
1010
d873ff48 1011
0be09cca
AE
1012 if (replyinfo_obj.decrypt_success == True) \
1013 and (replyinfo_obj.sig_success == True) \
1014 and (replyinfo_obj.have_reply_key == True):
1015 debug('message quoted')
1016 reply_plain += replyinfo_obj.replies['quote_follows']
1017 reply_plain += "\n\n"
1018 quoted_text = email_quote_text(replyinfo_obj.msg_to_quote)
1019 reply_plain += quoted_text
1020 reply_plain += "\n\n"
1021
1022
4e2c66f7
AE
1023 if (reply_plain == ""):
1024 debug('plaintext message')
1025 reply_plain += replyinfo_obj.replies['failed_decrypt']
1026 reply_plain += "\n\n"
1027
1028
d873ff48 1029 reply_plain += replyinfo_obj.replies['signature']
b4c116d5 1030 reply_plain += "\n\n"
56578eaf 1031
d873ff48 1032 return reply_plain
56578eaf
AE
1033
1034
8f61c66a 1035def add_gpg_key (key_block, gpgme_ctx):
39e2c525
AE
1036 """Adds a GPG pubkey to the local keystore
1037
1038 This adds keys received through email into the key store so they can be
1039 used later.
1040
1041 Args:
1042 key_block: the string form of the ascii-armored public key block
1043 gpgme_ctx: the gpgme context
1044
1045 Returns:
c035a008
AE
1046 the fingerprint(s) of the imported key(s) which can be used for
1047 encryption, and a boolean marking whether none of the keys are capable
1048 of encryption.
39e2c525 1049 """
c267c233 1050
8f61c66a 1051 fp = io.BytesIO(key_block.encode('ascii'))
c267c233 1052
89c08329
AE
1053 try:
1054 result = gpgme_ctx.import_(fp)
1055 imports = result.imports
1056 except gpgme.GpgmeError:
1057 imports = []
c267c233 1058
f8ee6bd3 1059 key_fingerprints = []
c035a008
AE
1060 key_cannot_encrypt = False
1061
1062 for import_res in imports:
1063 fingerprint = import_res[0]
1064
1065 try:
1066 key_obj = gpgme_ctx.get_key(fingerprint)
1067 except:
494c6e50 1068 key_obj = None
c267c233 1069
494c6e50 1070 if key_obj != None and is_key_usable(key_obj):
f8ee6bd3 1071 key_fingerprints += [fingerprint]
c035a008 1072 key_cannot_encrypt = False
c267c233 1073
e49673aa 1074 debug("added gpg key: " + fingerprint)
ec1e779a 1075
c035a008
AE
1076 elif key_fingerprints == []:
1077 key_cannot_encrypt = True
1078
1079 return (key_fingerprints, key_cannot_encrypt)
ec1e779a
AE
1080
1081
3a753fd0 1082def verify_sig_message (msg_block, gpgme_ctx):
39e2c525
AE
1083 """Verifies the signature of a signed, ascii-armored block of text.
1084
1085 It encodes the string into ascii, since binary GPG files are currently
1086 unsupported, and alternative, the ascii-armored format is encodable into
1087 ascii.
1088
1089 Args:
1090 msg_block: a GPG Message block in string form. It may be encrypted or
1091 not. If it is encrypted, it will return empty results.
1092 gpgme_ctx: the gpgme context
1093
1094 Returns:
85a829fc 1095 A tuple containing the plaintext bytes of the signed part, the list of
c035a008
AE
1096 fingerprints of encryption-capable keys signing the data, a boolean
1097 marking whether edward is missing all public keys for validating any of
1098 the signatures, and a boolean marking whether all sigs' keys are
1099 incapable of encryption. If verification failed, perhaps because the
1100 message was also encrypted, sensible default values are returned.
39e2c525 1101 """
3a753fd0
AE
1102
1103 block_b = io.BytesIO(msg_block.encode('ascii'))
1104 plain_b = io.BytesIO()
1105
1106 try:
1107 sigs = gpgme_ctx.verify(block_b, None, plain_b)
5f6f32b1 1108 except gpgme.GpgmeError:
c035a008 1109 return ("",[],False,False)
3a753fd0 1110
85a829fc 1111 plaintext_b = plain_b.getvalue()
3a753fd0 1112
c035a008 1113 (fingerprints, sigkey_missing, key_cannot_encrypt) = get_signature_fp(sigs, gpgme_ctx)
9af26cb8 1114
c035a008 1115 return (plaintext_b, fingerprints, sigkey_missing, key_cannot_encrypt)
3a753fd0
AE
1116
1117
101d54a8 1118def verify_detached_signature (detached_sig, plaintext_bytes, gpgme_ctx):
39e2c525
AE
1119 """Verifies the signature of a detached signature.
1120
1121 This requires the signature part and the signed part as separate arguments.
1122
1123 Args:
1124 detached_sig: the signature part of the detached signature
1125 plaintext_bytes: the byte form of the message being signed.
1126 gpgme_ctx: the gpgme context
1127
1128 Returns:
c035a008
AE
1129 A tuple containging a list of encryption capable signing fingerprints
1130 if the signature verification was sucessful, a boolean marking whether
1131 edward is missing all public keys for validating any of the signatures,
1132 and a boolean marking whether all signing keys are incapable of
1133 encryption. Otherwise, a tuple containing an empty list and True are
1134 returned.
39e2c525 1135 """
101d54a8
AE
1136
1137 detached_sig_fp = io.BytesIO(detached_sig.encode('ascii'))
1138 plaintext_fp = io.BytesIO(plaintext_bytes)
101d54a8 1139
ff7aeb3d 1140 try:
c035a008 1141 sigs = gpgme_ctx.verify(detached_sig_fp, plaintext_fp, None)
ff7aeb3d 1142 except gpgme.GpgmeError:
c035a008 1143 return ([],False,False)
101d54a8 1144
c035a008 1145 (fingerprints, sigkey_missing, key_cannot_encrypt) = get_signature_fp(sigs, gpgme_ctx)
101d54a8 1146
c035a008 1147 return (fingerprints, sigkey_missing, key_cannot_encrypt)
101d54a8
AE
1148
1149
5b3053c1 1150def decrypt_block (msg_block, gpgme_ctx):
9af26cb8 1151 """Decrypts a block of GPG text and verifies any included sigatures.
39e2c525
AE
1152
1153 Some encypted messages have embeded signatures, so those are verified too.
1154
1155 Args:
1156 msg_block: the encrypted(/signed) text
1157 gpgme_ctx: the gpgme context
1158
1159 Returns:
c035a008
AE
1160 A tuple containing plaintext bytes, encryption-capable signatures (if
1161 decryption and signature verification were successful, respectively), a
1162 boolean marking whether edward is missing all public keys for
1163 validating any of the signatures, and a boolean marking whether all
1164 signature keys are incapable of encryption.
39e2c525 1165 """
0bec96d6 1166
5b3053c1 1167 block_b = io.BytesIO(msg_block.encode('ascii'))
0bec96d6
AE
1168 plain_b = io.BytesIO()
1169
afc1f64c
AE
1170 try:
1171 sigs = gpgme_ctx.decrypt_verify(block_b, plain_b)
5f6f32b1 1172 except gpgme.GpgmeError:
c035a008 1173 return ("",[],False,False)
0bec96d6 1174
85a829fc 1175 plaintext_b = plain_b.getvalue()
cbdf22c1 1176
c035a008
AE
1177 (fingerprints, sigkey_missing, key_cannot_encrypt) = get_signature_fp(sigs, gpgme_ctx)
1178
1179 return (plaintext_b, fingerprints, sigkey_missing, key_cannot_encrypt)
1180
1181
1182def get_signature_fp (sigs, gpgme_ctx):
1183 """Selects valid signatures from output of gpgme signature verifying functions
1184
1185 get_signature_fp returns a list of valid signature fingerprints if those
1186 fingerprints are associated with available keys capable of encryption.
1187
1188 Args:
1189 sigs: a signature verification result object list
1190 gpgme_ctx: a gpgme context
1191
1192 Returns:
1193 fingerprints: a list of fingerprints
1194 sigkey_missing: a boolean marking whether public keys are missing for
1195 all available signatures.
1196 key_cannot_encrypt: a boolearn marking whether available public keys are
1197 incapable of encryption.
1198 """
1199
b4c116d5 1200 sigkey_missing = False
c035a008 1201 key_cannot_encrypt = False
cbdf22c1 1202 fingerprints = []
c035a008 1203
cbdf22c1 1204 for sig in sigs:
8f011cc9 1205 if (sig.summary == 0) or (sig.summary & gpgme.SIGSUM_VALID != 0) or (sig.summary & gpgme.SIGSUM_GREEN != 0):
c035a008
AE
1206 try:
1207 key_obj = gpgme_ctx.get_key(sig.fpr)
1208 except:
1209 if fingerprints == []:
1210 sigkey_missing = True
1211 continue
1212
c5492aa9 1213 if is_key_usable(key_obj):
c035a008
AE
1214 fingerprints += [sig.fpr]
1215 key_cannot_encrypt = False
1216 sigkey_missing = False
1217
1218 elif fingerprints == []:
1219 key_cannot_encrypt = True
1220
1221 elif fingerprints == []:
b4c116d5
AE
1222 if (sig.summary & gpgme.SIGSUM_KEY_MISSING != 0):
1223 sigkey_missing = True
9af26cb8 1224
c035a008 1225 return (fingerprints, sigkey_missing, key_cannot_encrypt)
0bec96d6
AE
1226
1227
c5492aa9
AE
1228def is_key_usable (key_obj):
1229 """Returns boolean representing key usability regarding encryption
1230
1231 Tests various feature of key and returns usability
1232
1233 Args:
1234 key_obj: a gpgme key object
1235
1236 Returns:
1237 A boolean representing key usability
1238 """
1239 if key_obj.can_encrypt and not key_obj.invalid and not key_obj.expired \
1240 and not key_obj.revoked and not key_obj.disabled:
1241 return True
1242 else:
1243 return False
1244
1245
140c47ca
AE
1246def email_to_reply_to_subject (email_bytes):
1247 """Returns the email's To:, Reply-To: (or From:), and Subject: fields
fafa21c3 1248
dd2b62d7 1249 Returns this information from an email.
fafa21c3 1250
dd2b62d7 1251 Args:
85a829fc 1252 email_bytes: the byte string form of the email
fafa21c3 1253
dd2b62d7 1254 Returns:
140c47ca 1255 the email To:, Reply-To: (or From:), and Subject: fields as strings
dd2b62d7 1256 """
d65993b8 1257
4f468fcd 1258 email_struct = email.parser.BytesHeaderParser().parsebytes(email_bytes)
d65993b8
AE
1259
1260 email_to = email_struct['To']
1261 email_from = email_struct['From']
140c47ca
AE
1262 email_reply_to = email_struct['Reply-To']
1263
d65993b8
AE
1264 email_subject = email_struct['Subject']
1265
140c47ca
AE
1266 if email_reply_to == None:
1267 email_reply_to = email_from
1268
1269 return email_to, email_reply_to, email_subject
d65993b8
AE
1270
1271
bb27d257
AE
1272def import_lang_pick_address(email_to, hostname):
1273 """Imports language file for i18n support; makes reply from address
dd2b62d7
AE
1274
1275 The language imported depends on the To: address of the email received by
1276 edward. an -en ending implies the English language, whereas a -ja ending
1277 implies Japanese. The list of supported languages is listed in the 'langs'
bb27d257
AE
1278 list at the beginning of the program. This function also chooses the
1279 language-dependent address which can be used as the From address in the
1280 reply email.
dd2b62d7
AE
1281
1282 Args:
1283 email_to: the string containing the email address that the mail was
bb27d257
AE
1284 sent to.
1285 hostname: the hostname part of the reply email's from address
dd2b62d7
AE
1286
1287 Returns:
1288 the reference to the imported language module. The only variable in
1289 this file is the 'replies' dictionary.
1290 """
adcef2f7 1291
bb27d257
AE
1292 # default
1293 use_lang = "en"
daed5f10 1294
5250b3b8
AE
1295 if email_to != None:
1296 for lang in langs:
1297 if "edward-" + lang in email_to:
bb27d257
AE
1298 use_lang = lang
1299 break
adcef2f7 1300
bb27d257
AE
1301 lang_mod_name = "lang." + re.sub('-', '_', use_lang)
1302 lang_module = importlib.import_module(lang_mod_name)
1303
60ccbaf4 1304 reply_from = "edward-" + use_lang + "@" + hostname
bb27d257 1305
60ccbaf4 1306 return lang_module, reply_from
adcef2f7
AE
1307
1308
cfb03389 1309def generate_encrypted_mime (plaintext, email_to, email_subject, encrypt_to_key,
0a064403 1310 gpgme_ctx):
dd2b62d7
AE
1311 """This function creates the mime email reply. It can encrypt the email.
1312
1313 If the encrypt_key is included, then the email is encrypted and signed.
1314 Otherwise it is unencrypted.
1315
1316 Args:
1317 plaintext: the plaintext body of the message to create.
cfb03389 1318 email_to: the email address to reply to
dd2b62d7
AE
1319 email_subject: the subject to use in reply
1320 encrypt_to_key: the key object to use for encrypting the email. (or
1321 None)
1322 gpgme_ctx: the gpgme context
1323
1324 Returns
1325 A string version of the mime message, possibly encrypted and signed.
1326 """
1da9b527 1327
59bc3fac
AE
1328 plaintext_mime = MIMEText(plaintext)
1329 plaintext_mime.set_charset('utf-8')
8bdfb6d4 1330
59bc3fac 1331 if (encrypt_to_key != None):
8bdfb6d4
AE
1332
1333 encrypted_text = encrypt_sign_message(plaintext_mime.as_string(),
1334 encrypt_to_key,
40c37ab3 1335 gpgme_ctx)
8bdfb6d4 1336
e5dd6f23
AE
1337 control_mime = MIMEApplication("Version: 1",
1338 _subtype='pgp-encrypted',
1339 _encoder=email.encoders.encode_7or8bit)
1340 control_mime['Content-Description'] = 'PGP/MIME version identification'
1341 control_mime.set_charset('us-ascii')
8bdfb6d4 1342
e5dd6f23
AE
1343 encoded_mime = MIMEApplication(encrypted_text,
1344 _subtype='octet-stream; name="encrypted.asc"',
1345 _encoder=email.encoders.encode_7or8bit)
1346 encoded_mime['Content-Description'] = 'OpenPGP encrypted message'
1347 encoded_mime['Content-Disposition'] = 'inline; filename="encrypted.asc"'
1348 encoded_mime.set_charset('us-ascii')
8bdfb6d4 1349
e5dd6f23
AE
1350 message_mime = MIMEMultipart(_subtype="encrypted", protocol="application/pgp-encrypted")
1351 message_mime.attach(control_mime)
1352 message_mime.attach(encoded_mime)
1353 message_mime['Content-Disposition'] = 'inline'
216708e9 1354
e5dd6f23 1355 else:
59bc3fac 1356 message_mime = plaintext_mime
2007103e 1357
cfb03389 1358 message_mime['To'] = email_to
2007103e
AE
1359 message_mime['Subject'] = email_subject
1360
1361 reply = message_mime.as_string()
1da9b527
AE
1362
1363 return reply
1364
1365
ba34a33c
AE
1366def send_reply(email_txt, reply_to, reply_from):
1367 """Sends reply email
1368
1369 Sent to original sender
1370
1371 Args:
1372 email_txt: message as a string
1373 reply_to: recipient of reply
1374 reply_from: edward's specific email address
1375
1376 Post:
1377 Email is sent
1378 """
1379
8ad5c922
AE
1380 if reply_to == None:
1381 error("*** ERROR: No one to send email to.")
1382 exit(1)
60ccbaf4 1383
a9eaa792
AE
1384 s = smtplib.SMTP('localhost')
1385 s.sendmail(reply_from, reply_to, email_txt)
1386 s.quit()
60ccbaf4
AE
1387
1388
f87041f8 1389def email_quote_text (text):
dd2b62d7
AE
1390 """Quotes input text by inserting "> "s
1391
1392 This is useful for quoting a text for the reply message. It inserts "> "
1393 strings at the beginning of lines.
1394
1395 Args:
1396 text: plain text to quote
1397
1398 Returns:
1399 Quoted text
1400 """
f87041f8
AE
1401
1402 quoted_message = re.sub(r'^', r'> ', text, flags=re.MULTILINE)
1403
1404 return quoted_message
1405
1406
0a064403 1407def encrypt_sign_message (plaintext, encrypt_to_key, gpgme_ctx):
dd2b62d7
AE
1408 """Encrypts and signs plaintext
1409
1410 This encrypts and signs a message.
1411
1412 Args:
1413 plaintext: text to sign and ecrypt
1414 encrypt_to_key: the key object to encrypt to
1415 gpgme_ctx: the gpgme context
1416
1417 Returns:
1418 An encrypted and signed string of text
1419 """
897cbaf6 1420
b33f601b 1421 # the plaintext should be mime encoded in an ascii-compatible form
6aa41372 1422 plaintext_bytes = io.BytesIO(plaintext.encode('ascii'))
1da9b527
AE
1423 encrypted_bytes = io.BytesIO()
1424
897cbaf6 1425 gpgme_ctx.encrypt_sign([encrypt_to_key], gpgme.ENCRYPT_ALWAYS_TRUST,
1da9b527
AE
1426 plaintext_bytes, encrypted_bytes)
1427
6aa41372 1428 encrypted_txt = encrypted_bytes.getvalue().decode('ascii')
1da9b527
AE
1429 return encrypted_txt
1430
1431
0a064403 1432def error (error_msg):
dd2b62d7
AE
1433 """Write an error message to stdout
1434
1435 The error message includes the program name.
1436
1437 Args:
1438 error_msg: the message to print
1439
1440 Returns:
1441 Nothing
1442
1443 Post:
1444 An error message is printed to stdout
1445 """
0a064403 1446
e4fb2ab2 1447 sys.stderr.write(progname + ": " + str(error_msg) + "\n")
0a064403
AE
1448
1449
5e8f9094 1450def debug (debug_msg):
dd2b62d7
AE
1451 """Writes a debug message to stdout if debug == True
1452
1453 If the debug option is set in edward_config.py, then the passed message
1454 gets printed to stdout.
1455
1456 Args:
1457 debug_msg: the message to print to stdout
1458
1459 Returns:
1460 Nothing
1461
1462 Post:
1463 A debug message is printed to stdout
1464 """
5e8f9094
AE
1465
1466 if edward_config.debug == True:
0a064403 1467 error(debug_msg)
5e8f9094
AE
1468
1469
20f6e7c5 1470def handle_args ():
60ccbaf4 1471 """Sets the progname variable and processes optional argument
dd2b62d7 1472
60ccbaf4
AE
1473 If there are more than two arguments then edward complains and quits. An
1474 single "-p" argument sets the print_reply_only option, which makes edward
1475 print email replies instead of mailing them.
dd2b62d7
AE
1476
1477 Args:
1478 None
1479
1480 Returns:
60ccbaf4
AE
1481 True if edward should print arguments instead of mailing them,
1482 otherwise it returns False.
dd2b62d7
AE
1483
1484 Post:
60ccbaf4
AE
1485 Exits with error 1 if there are more than two arguments, otherwise
1486 returns the print_reply_only option.
dd2b62d7 1487 """
20f6e7c5 1488
a51cdb72
AE
1489 global progname
1490 progname = sys.argv[0]
1491
60ccbaf4
AE
1492 print_reply_only = False
1493
1494 if len(sys.argv) > 2:
1495 print(progname + " usage: " + progname + " [-p]\n\n" \
1496 + " -p print reply message to stdout, do not mail it\n", \
1497 file=sys.stderr)
a51cdb72 1498 exit(1)
20f6e7c5 1499
60ccbaf4
AE
1500 elif (len(sys.argv) == 2) and (sys.argv[1] == "-p"):
1501 print_reply_only = True
1502
1503 return print_reply_only
1504
20f6e7c5 1505
a51cdb72 1506if __name__ == "__main__":
dd2b62d7 1507 """Executes main if this file is not loaded interactively"""
20f6e7c5 1508
a51cdb72 1509 main()
0bec96d6 1510