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
45 from email
.mime
.multipart
import MIMEMultipart
46 from email
.mime
.application
import MIMEApplication
47 from email
.mime
.nonmultipart
import MIMENonMultipart
55 email_text
= sys
.stdin
.read()
56 email_from
, email_subject
= email_from_subject(email_text
)
58 os
.environ
['GNUPGHOME'] = edward_config
.gnupghome
59 gpgme_ctx
= gpgme
.Context()
60 gpgme_ctx
.armor
= True
62 add_gpg_keys(email_text
, gpgme_ctx
)
64 plaintext
, keys
= email_decode_flatten(email_text
, gpgme_ctx
)
65 encrypt_to_key
= choose_reply_encryption_key(keys
)
67 reply_message
= generate_reply(plaintext
, email_from
, \
68 email_subject
, encrypt_to_key
,
69 edward_config
.sign_with_key
,
75 def email_decode_flatten (email_text
, gpgme_ctx
):
80 email_struct
= email
.parser
.Parser().parsestr(email_text
)
82 for subpart
in email_struct
.walk():
84 payload
, description
, filename
, content_type \
85 = get_email_subpart_info(subpart
)
90 if content_type
== "multipart":
93 if content_type
== "application/pgp-encrypted":
94 if description
== "PGP/MIME version identification":
95 if payload
.strip() != "Version: 1":
96 print(progname
+ ": Warning: unknown " \
97 + description
+ ": " \
98 + payload
.strip(), file=sys
.stderr
)
102 if (filename
== "encrypted.asc") or (content_type
== "pgp/mime"):
103 plaintext
, more_keys
= decrypt_text(payload
, gpgme_ctx
)
108 elif content_type
== "application/pgp-keys":
109 keys
+= add_gpg_keys(payload
, gpgme_ctx
)
111 elif content_type
== "text/plain":
112 body
+= payload
+ "\n"
115 body
+= payload
+ "\n"
120 def email_from_subject (email_text
):
122 email_struct
= email
.parser
.Parser().parsestr(email_text
)
124 email_from
= email_struct
['From']
125 email_subject
= email_struct
['Subject']
127 return email_from
, email_subject
130 def get_email_subpart_info (part
):
132 charset
= part
.get_content_charset()
133 payload_bytes
= part
.get_payload(decode
=True)
135 filename
= part
.get_filename()
136 content_type
= part
.get_content_type()
137 description_list
= part
.get_params(header
='content-description')
142 if payload_bytes
!= None:
143 payload
= payload_bytes
.decode(charset
)
147 if description_list
!= None:
148 description
= description_list
[0][0]
152 return payload
, description
, filename
, content_type
155 def add_gpg_keys (text
, gpgme_ctx
):
157 keys
= scan_and_grab(text
,
158 '-----BEGIN PGP PUBLIC KEY BLOCK-----',
159 '-----END PGP PUBLIC KEY BLOCK-----')
163 fp
= io
.BytesIO(key
.encode('ascii'))
165 result
= gpgme_ctx
.import_(fp
)
167 fingerprint
= result
.imports
[0][0]
168 debug("added gpg key: " + fingerprint
)
175 def decrypt_text (gpg_text
, gpgme_ctx
):
180 gpg_chunks
= scan_and_grab(gpg_text
,
181 '-----BEGIN PGP MESSAGE-----',
182 '-----END PGP MESSAGE-----')
184 plaintext_and_sigs_chunks
= decrypt_chunks(gpg_chunks
, gpgme_ctx
)
186 for chunk
in plaintext_and_sigs_chunks
:
191 key
= get_pub_key(sig
, gpgme_ctx
)
194 # recursive for nested layers of mime and/or gpg
195 plaintext
, more_keys
= email_decode_flatten(plaintext
, gpgme_ctx
)
203 def get_pub_key (sig
, gpgme_ctx
):
205 fingerprint
= sig
.fpr
206 key
= gpgme_ctx
.get_key(fingerprint
)
211 def scan_and_grab (text
, start_text
, end_text
):
213 matches
= re
.search('(' + start_text
+ '.*' + end_text
+ ')',
214 text
, flags
=re
.DOTALL
)
217 match_tuple
= matches
.groups()
224 def decrypt_chunks (gpg_chunks
, gpgme_ctx
):
226 return [decrypt_chunk(chunk
, gpgme_ctx
) for chunk
in gpg_chunks
]
229 def decrypt_chunk (gpg_chunk
, gpgme_ctx
):
231 chunk_b
= io
.BytesIO(gpg_chunk
.encode('ascii'))
232 plain_b
= io
.BytesIO()
234 sigs
= gpgme_ctx
.decrypt_verify(chunk_b
, plain_b
)
236 plaintext
= plain_b
.getvalue().decode('utf-8')
237 return (plaintext
, sigs
)
240 def choose_reply_encryption_key (keys
):
244 if (key
.can_encrypt
== True):
251 def generate_reply (plaintext
, email_from
, email_subject
, encrypt_to_key
,
252 sign_with_fingerprint
, gpgme_ctx
):
255 reply
= "To: " + email_from
+ "\n"
256 reply
+= "Subject: " + email_subject
+ "\n"
258 if (encrypt_to_key
!= None):
259 plaintext_reply
= "thanks for the message!\n\n\n"
260 plaintext_reply
+= email_quote_text(plaintext
)
262 # quoted printable encoding lets most ascii characters look normal
263 # before the decrypted mime message is decoded.
264 char_set
= email
.charset
.Charset("utf-8")
265 char_set
.body_encoding
= email
.charset
.QP
267 # MIMEText doesn't allow setting the text encoding
268 # so we use MIMENonMultipart.
269 plaintext_mime
= MIMENonMultipart('text', 'plain')
270 plaintext_mime
.set_payload(plaintext_reply
, charset
=char_set
)
272 encrypted_text
= encrypt_sign_message(plaintext_mime
.as_string(),
274 sign_with_fingerprint
,
277 control_mime
= MIMEApplication("Version: 1",
278 _subtype
='pgp-encrypted',
279 _encoder
=email
.encoders
.encode_7or8bit
)
280 control_mime
['Content-Description'] = 'PGP/MIME version identification'
281 control_mime
.set_charset('us-ascii')
283 encoded_mime
= MIMEApplication(encrypted_text
,
284 _subtype
='octet-stream; name="encrypted.asc"',
285 _encoder
=email
.encoders
.encode_7or8bit
)
286 encoded_mime
['Content-Description'] = 'OpenPGP encrypted message'
287 encoded_mime
['Content-Disposition'] = 'inline; filename="encrypted.asc"'
288 encoded_mime
.set_charset('us-ascii')
290 message_mime
= MIMEMultipart(_subtype
="encrypted", protocol
="application/pgp-encrypted")
291 message_mime
.attach(control_mime
)
292 message_mime
.attach(encoded_mime
)
293 message_mime
['Content-Disposition'] = 'inline'
295 reply
+= message_mime
.as_string()
299 reply
+= "Sorry, i couldn't find your key.\n"
300 reply
+= "I'll need that to encrypt a message to you."
305 def email_quote_text (text
):
307 quoted_message
= re
.sub(r
'^', r
'> ', text
, flags
=re
.MULTILINE
)
309 return quoted_message
312 def encrypt_sign_message (plaintext
, encrypt_to_key
, sign_with_fingerprint
, gpgme_ctx
):
314 sign_with_key
= gpgme_ctx
.get_key(sign_with_fingerprint
)
315 gpgme_ctx
.signers
= [sign_with_key
]
317 plaintext_bytes
= io
.BytesIO(plaintext
.encode('ascii'))
318 encrypted_bytes
= io
.BytesIO()
320 gpgme_ctx
.encrypt_sign([encrypt_to_key
], gpgme
.ENCRYPT_ALWAYS_TRUST
,
321 plaintext_bytes
, encrypted_bytes
)
323 encrypted_txt
= encrypted_bytes
.getvalue().decode('ascii')
327 def debug (debug_msg
):
329 if edward_config
.debug
== True:
330 sys
.stderr
.write(debug_msg
+ "\n")
334 if __name__
== "__main__":
337 progname
= sys
.argv
[0]
339 if len(sys
.argv
) > 1:
340 print(progname
+ ": error, this program doesn't " \
341 "need any arguments.", file=sys
.stderr
)