1 #! /usr/bin/env python3
2 # -*- coding: utf-8 -*-
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. *
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. *
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/>. *
17 * Copyright (C) 2014-2015 Andrew Engelbrecht (AGPLv3+) *
18 * Copyright (C) 2014 Josh Drake (AGPLv3+) *
19 * Copyright (C) 2014 Lisa Marie Maginnis (AGPLv3+) *
20 * Copyright (C) 2009-2015 Tails developers <tails@boum.org> ( GPLv3+) *
21 * Copyright (C) 2009 W. Trevor King <wking@drexel.edu> ( GPLv2+) *
23 * Special thanks to Josh Drake for writing the original edward bot! :) *
25 ************************************************************************
27 Code sourced from these projects:
29 * http://agpl.fsf.org/emailselfdefense.fsf.org/edward/CURRENT/edward.tar.gz
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
44 from email
.mime
.multipart
import MIMEMultipart
45 from email
.mime
.application
import MIMEApplication
46 from email
.mime
.nonmultipart
import MIMENonMultipart
50 match_types
= [('clearsign',
51 '-----BEGIN PGP SIGNED MESSAGE-----.*?-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----'),
53 '-----BEGIN PGP MESSAGE-----.*?-----END PGP MESSAGE-----'),
55 '-----BEGIN PGP PUBLIC KEY BLOCK-----.*?-----END PGP PUBLIC KEY BLOCK-----'),
57 '-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----')]
60 class EddyMsg (object):
62 self
.multipart
= False
66 self
.payload_bytes
= None
67 self
.payload_pieces
= []
70 self
.content_type
= None
71 self
.description_list
= None
74 class PayloadPiece (object):
76 self
.piece_type
= None
81 class GPGData (object):
83 self
.decrypted
= False
94 gpgme_ctx
= get_gpg_context(edward_config
.gnupghome
,
95 edward_config
.sign_with_key
)
97 email_text
= sys
.stdin
.read()
98 result
= parse_pgp_mime(email_text
, gpgme_ctx
)
100 email_from
, email_subject
= email_from_subject(email_text
)
102 # plaintext, fingerprints = email_decode_flatten(email_text, gpgme_ctx, False)
103 # encrypt_to_key = choose_reply_encryption_key(gpgme_ctx, fingerprints)
105 # reply_message = generate_reply(plaintext, email_from, \
106 # email_subject, encrypt_to_key,
109 print(flatten_eddy(result
))
112 def get_gpg_context (gnupghome
, sign_with_key_fp
):
114 os
.environ
['GNUPGHOME'] = gnupghome
116 gpgme_ctx
= gpgme
.Context()
117 gpgme_ctx
.armor
= True
120 sign_with_key
= gpgme_ctx
.get_key(sign_with_key_fp
)
122 error("unable to load signing key. is the gnupghome "
123 + "and signing key properly set in the edward_config.py?")
126 gpgme_ctx
.signers
= [sign_with_key
]
131 def parse_pgp_mime (email_text
, gpgme_ctx
):
133 email_struct
= email
.parser
.Parser().parsestr(email_text
)
135 eddy_obj
= parse_mime(email_struct
)
136 eddy_obj
= split_payloads(eddy_obj
)
137 eddy_obj
= decrypt_payloads(eddy_obj
, gpgme_ctx
)
142 def parse_mime(msg_struct
):
146 if msg_struct
.is_multipart() == True:
147 payloads
= msg_struct
.get_payload()
149 eddy_obj
.multipart
= True
150 eddy_obj
.subparts
= list(map(parse_mime
, payloads
))
153 eddy_obj
= get_subpart_data(msg_struct
)
158 def split_payloads (eddy_obj
):
160 if eddy_obj
.multipart
== True:
161 eddy_obj
.subparts
= list(map(split_payloads
, eddy_obj
.subparts
))
164 for (match_type
, pattern
) in match_types
:
167 for payload_piece
in eddy_obj
.payload_pieces
:
168 new_pieces_list
+= scan_and_split(payload_piece
,
170 eddy_obj
.payload_pieces
= new_pieces_list
175 def scan_and_split (payload_piece
, match_type
, pattern
):
177 flags
= re
.DOTALL | re
.MULTILINE
178 matches
= re
.search("(?P<beginning>.*?)(?P<match>" + pattern
+
179 ")(?P<rest>.*)", payload_piece
.string
, flags
=flags
)
182 pieces
= [payload_piece
]
186 beginning
= PayloadPiece()
187 beginning
.string
= matches
.group('beginning')
188 beginning
.piece_type
= payload_piece
.piece_type
190 match
= PayloadPiece()
191 match
.string
= matches
.group('match')
192 match
.piece_type
= match_type
194 rest
= PayloadPiece()
195 rest
.string
= matches
.group('rest')
196 rest
.piece_type
= payload_piece
.piece_type
198 more_pieces
= scan_and_split(rest
, match_type
, pattern
)
199 pieces
= [beginning
, match
] + more_pieces
204 def get_subpart_data (part
):
208 obj
.charset
= part
.get_content_charset()
209 obj
.payload_bytes
= part
.get_payload(decode
=True)
211 obj
.filename
= part
.get_filename()
212 obj
.content_type
= part
.get_content_type()
213 obj
.description_list
= part
['content-description']
215 # your guess is as good as a-myy-ee-ine...
216 if obj
.charset
== None:
217 obj
.charset
= 'utf-8'
219 if obj
.payload_bytes
!= None:
221 payload
= PayloadPiece()
222 payload
.string
= obj
.payload_bytes
.decode(obj
.charset
)
223 payload
.piece_type
= 'text'
225 obj
.payload_pieces
= [payload
]
226 except UnicodeDecodeError:
232 def do_to_eddys_pieces (function_to_do
, eddy_obj
, data
):
234 if eddy_obj
.multipart
== True:
236 for sub
in eddy_obj
.subparts
:
237 result_list
+= do_to_eddys_pieces(function_to_do
, sub
, data
)
239 result_list
= [function_to_do(eddy_obj
.payload_pieces
, data
)]
244 def decrypt_payloads (eddy_obj
, gpgme_ctx
):
246 do_to_eddys_pieces(decrypt_payload_pieces
, eddy_obj
, gpgme_ctx
)
251 def decrypt_payload_pieces (payload_pieces
, gpgme_ctx
):
253 for piece
in payload_pieces
:
255 if piece
.piece_type
== "text":
256 # don't transform the plaintext.
259 elif piece
.piece_type
== "message":
260 (plaintext
, sigs
) = decrypt_block (piece
.string
, gpgme_ctx
)
263 piece
.gpg_data
= GPGData()
264 piece
.gpg_data
.sigs
= sigs
266 piece
.gpg_data
.plainobj
= parse_pgp_mime(plaintext
, gpgme_ctx
)
271 def flatten_eddy (eddy_obj
):
273 string
= "\n".join(do_to_eddys_pieces(flatten_payload_pieces
, eddy_obj
, None))
278 def flatten_payload_pieces (payload_pieces
, _ignore
):
281 for piece
in payload_pieces
:
282 if piece
.piece_type
== "text":
283 string
+= piece
.string
284 elif piece
.piece_type
== "message":
286 string
+= flatten_eddy(piece
.gpg_data
.plainobj
)
291 def email_from_subject (email_text
):
293 email_struct
= email
.parser
.Parser().parsestr(email_text
)
295 email_from
= email_struct
['From']
296 email_subject
= email_struct
['Subject']
298 return email_from
, email_subject
301 def add_gpg_keys (text
, gpgme_ctx
):
303 key_blocks
= scan_and_grab(text
,
304 '-----BEGIN PGP PUBLIC KEY BLOCK-----',
305 '-----END PGP PUBLIC KEY BLOCK-----')
308 for key_block
in key_blocks
:
309 fp
= io
.BytesIO(key_block
.encode('ascii'))
311 result
= gpgme_ctx
.import_(fp
)
312 imports
= result
.imports
315 fingerprint
= imports
[0][0]
316 fingerprints
+= [fingerprint
]
318 debug("added gpg key: " + fingerprint
)
323 def decrypt_text (gpg_text
, gpgme_ctx
):
328 msg_blocks
= scan_and_grab(gpg_text
,
329 '-----BEGIN PGP MESSAGE-----',
330 '-----END PGP MESSAGE-----')
332 plaintexts_and_sigs
= decrypt_blocks(msg_blocks
, gpgme_ctx
)
334 for pair
in plaintexts_and_sigs
:
339 fingerprints
+= [sig
.fpr
]
341 # recursive for nested layers of mime and/or gpg
342 plaintext
, more_fps
= email_decode_flatten(plaintext
, gpgme_ctx
, True)
345 fingerprints
+= more_fps
347 return body
, fingerprints
350 def verify_clear_signature (text
, gpgme_ctx
):
352 sig_blocks
= scan_and_grab(text
,
353 '-----BEGIN PGP SIGNED MESSAGE-----',
354 '-----END PGP SIGNATURE-----')
359 for sig_block
in sig_blocks
:
360 msg_fp
= io
.BytesIO(sig_block
.encode('utf-8'))
361 ptxt_fp
= io
.BytesIO()
363 result
= gpgme_ctx
.verify(msg_fp
, None, ptxt_fp
)
365 plaintext
+= ptxt_fp
.getvalue().decode('utf-8')
366 fingerprint
= result
[0].fpr
368 fingerprints
+= [fingerprint
]
370 return plaintext
, fingerprints
373 def scan_and_grab (text
, start_text
, end_text
):
375 matches
= re
.search('(' + start_text
+ '.*' + end_text
+ ')',
376 text
, flags
=re
.DOTALL
)
379 match_tuple
= matches
.groups()
386 def decrypt_blocks (msg_blocks
, gpgme_ctx
):
388 return [decrypt_block(block
, gpgme_ctx
) for block
in msg_blocks
]
391 def decrypt_block (msg_block
, gpgme_ctx
):
393 block_b
= io
.BytesIO(msg_block
.encode('ascii'))
394 plain_b
= io
.BytesIO()
397 sigs
= gpgme_ctx
.decrypt_verify(block_b
, plain_b
)
401 plaintext
= plain_b
.getvalue().decode('utf-8')
402 return (plaintext
, sigs
)
405 def choose_reply_encryption_key (gpgme_ctx
, fingerprints
):
408 for fp
in fingerprints
:
410 key
= gpgme_ctx
.get_key(fp
)
412 if (key
.can_encrypt
== True):
422 def generate_reply (plaintext
, email_from
, email_subject
, encrypt_to_key
,
426 reply
= "To: " + email_from
+ "\n"
427 reply
+= "Subject: " + email_subject
+ "\n"
429 if (encrypt_to_key
!= None):
430 plaintext_reply
= "thanks for the message!\n\n\n"
431 plaintext_reply
+= email_quote_text(plaintext
)
433 # quoted printable encoding lets most ascii characters look normal
434 # before the decrypted mime message is decoded.
435 char_set
= email
.charset
.Charset("utf-8")
436 char_set
.body_encoding
= email
.charset
.QP
438 # MIMEText doesn't allow setting the text encoding
439 # so we use MIMENonMultipart.
440 plaintext_mime
= MIMENonMultipart('text', 'plain')
441 plaintext_mime
.set_payload(plaintext_reply
, charset
=char_set
)
443 encrypted_text
= encrypt_sign_message(plaintext_mime
.as_string(),
447 control_mime
= MIMEApplication("Version: 1",
448 _subtype
='pgp-encrypted',
449 _encoder
=email
.encoders
.encode_7or8bit
)
450 control_mime
['Content-Description'] = 'PGP/MIME version identification'
451 control_mime
.set_charset('us-ascii')
453 encoded_mime
= MIMEApplication(encrypted_text
,
454 _subtype
='octet-stream; name="encrypted.asc"',
455 _encoder
=email
.encoders
.encode_7or8bit
)
456 encoded_mime
['Content-Description'] = 'OpenPGP encrypted message'
457 encoded_mime
['Content-Disposition'] = 'inline; filename="encrypted.asc"'
458 encoded_mime
.set_charset('us-ascii')
460 message_mime
= MIMEMultipart(_subtype
="encrypted", protocol
="application/pgp-encrypted")
461 message_mime
.attach(control_mime
)
462 message_mime
.attach(encoded_mime
)
463 message_mime
['Content-Disposition'] = 'inline'
465 reply
+= message_mime
.as_string()
469 reply
+= "Sorry, i couldn't find your key.\n"
470 reply
+= "I'll need that to encrypt a message to you."
475 def email_quote_text (text
):
477 quoted_message
= re
.sub(r
'^', r
'> ', text
, flags
=re
.MULTILINE
)
479 return quoted_message
482 def encrypt_sign_message (plaintext
, encrypt_to_key
, gpgme_ctx
):
484 plaintext_bytes
= io
.BytesIO(plaintext
.encode('ascii'))
485 encrypted_bytes
= io
.BytesIO()
487 gpgme_ctx
.encrypt_sign([encrypt_to_key
], gpgme
.ENCRYPT_ALWAYS_TRUST
,
488 plaintext_bytes
, encrypted_bytes
)
490 encrypted_txt
= encrypted_bytes
.getvalue().decode('ascii')
494 def error (error_msg
):
496 sys
.stderr
.write(progname
+ ": " + str(error_msg
) + "\n")
499 def debug (debug_msg
):
501 if edward_config
.debug
== True:
506 if __name__
== "__main__":
509 progname
= sys
.argv
[0]
511 if len(sys
.argv
) > 1:
512 print(progname
+ ": error, this program doesn't " \
513 "need any arguments.", file=sys
.stderr
)