├── .gitignore ├── ANONYMOUS.md ├── CHANGELOG ├── COPYING ├── README.md ├── __main__.py ├── constants.py ├── dh_legacy.py ├── dh_m2crypto.py ├── dh_pydhe.py ├── dhparams.pem ├── dhutils.py ├── encodher ├── encodher.keys ├── encodher.py ├── hsub.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | keys.db 3 | pubring.gpg 4 | secring.gpg 5 | trustdb.gpg 6 | random_seed 7 | build/ 8 | dist/ 9 | encoDHer.egg-info/ 10 | -------------------------------------------------------------------------------- /ANONYMOUS.md: -------------------------------------------------------------------------------- 1 | Using [encoDHer] [1] for anonymous communication 2 | === 3 | 4 | [1]: https://github.com/rxcomm/encoDHer/ "encoDHer" 5 | 6 | In this document, we present a brief overview of how 7 | to use encoDHer to communicate anonymously. We first 8 | outline the threat model, then summarize what a typical 9 | communication cycle would look like, and finally conclude 10 | with answers to a few frequently-asked questions. 11 | 12 | ### 1. Threat model 13 | 14 | Alice and Bob want to communicate. They do not want others to 15 | read their communication, and they do not want each other to 16 | know their identities. Further, they do not want others to 17 | know that they are communicating. 18 | 19 | They also fear a malevolent authority taking over a nymserver, 20 | which is the old way of handling this type of communication. 21 | The owner of the nymserver has the set of encryption keys 22 | that is used to guarantee anonymity, and so is vulnerable to 23 | an attack from authority. 24 | 25 | ### 2. Overview of communication cycle 26 | 27 | Alice and Bob decide to communicate. Their communication is 28 | somewhat voluminous (several pages of text are being exchanged). 29 | Thus, irc/instant messaging type communication is not optimal - 30 | rather email-type communication is required. 31 | 32 | Prior to any communication occurring, Alice and Bob will have 33 | created GPG key pairs for themselves that are not posted on any 34 | public media (including keyservers) that can be traced back 35 | to them. We will assume the uids for these keys are *alice* and 36 | *bob* (GPG can create simple uids without email addresses 37 | using the ```--allow-freeform-uid``` 38 | option). Further, both Bob and Alice use encoDHer to generate 39 | a Diffie-Hellman key pair for the *bob* ```->``` *dummy_address* 40 | or *alice* ```->``` *dummy_address* 41 | route respectively using encoDHer's ```--gen-key``` option. 42 | 43 | They then sign their DH public key with their GPG private key, 44 | and post both the signed DH public key as well as their GPG 45 | public key on an anonymized key tablet. They can also provide 46 | this data via other anonymized distribution channels - e.g. 47 | anonymized irc/im. This is accomplished using encoDHer's 48 | ```--sign-pub``` option. 49 | 50 | To start communicating, Alice and Bob need to create 51 | a shared secret between them. 52 | The shared secret will be created by each grabbing the 53 | other's DH and GPG public keys from the key tablet or other 54 | anonymized distribution channel. They then change the *dummy_address* of 55 | the route they generated above using encoDHer's ```--change-toEmail``` option 56 | to the uid of the other person, and 57 | import the other's DH public key using encoDHer's ```--import``` option 58 | Now they are able to create a 59 | shared secret via DH protocol using their DH private key and 60 | the other's DH public key. 61 | 62 | Alice then creates her plaintext message to Bob. If she also 63 | wants perfect forward secrecy, she generates a new 64 | DH key pair for the *alice* ```->``` *bob* route, and adds the new DH public key to the bottom 65 | of her plaintext message. She encrypts her plaintext message 66 | with symmetric AES256 encryption using the DH shared secret 67 | as the encryption key. She then creates a hashed subject 68 | (hsub) for the encrypted message using a part of the 69 | DH shared secret as her hsub passphrase. These steps can be accomplished 70 | using encoDHer's ```--encode-email``` option. Finally, she submits 71 | the encrypted message with hsub subject to 72 | alt.anonymous.messages via mixmaster and tor. 73 | 74 | For PFS, Alice then securely destroys her first DH key pair. 75 | 76 | To receive the message from Alice, Bob searches 77 | alt.anonymous.messages with encoDHer's ```--fetch-aam``` 78 | option via tor using the DH shared 79 | secret as his hsub passphrase. When he finds the 80 | message, he decrypts the message using the DH shared secret 81 | with encoDHer's ```--decode-email``` option. He then reads the plaintext message 82 | and recovers Alice's new DH public key. 83 | 84 | To respond, Bob generates a new plaintext message 85 | If Bob wants PFS, he generates a new DH key pair for the 86 | *bob* ```->``` *alice* route and adds his new DH public key to 87 | the bottom of his plaintext message. He then encrypts 88 | the message with a new DH shared secret using his 89 | first DH private key and Alice's current DH public key, 90 | He then creates an hsub using a part of the new DH shared 91 | secret as passphrase and submits the message with hsub 92 | subject to alt.anonymous.messages via mixmaster and tor. 93 | 94 | For PFS, Bob then securely destroys his first DH key pair. 95 | 96 | Alice then searches alt.anonymous.messages via tor with 97 | part of the DH shared secret generated from her second DH private 98 | key and Bob's first DH public key as the hsub passphrase. When she finds 99 | the message, she decrypts it, reads the plaintext 100 | and (if he sent one for PFS) gets Bob's new DH public key. If she desires 101 | to respond, she generates a new plaintext (and if PFS is 102 | desired, a new DH keypair) and the cycle continues. 103 | 104 | ### 3. Notes 105 | 106 | 1. hsub is not strictly required. The alternative 107 | is simply to attempt to decrypt all messages from 108 | alt.anonymous.messages. 109 | 110 | 2. One problem with this protocol is that messaging 111 | must be sequential: Alice ```->``` Bob ```->``` Alice ```->``` Bob ... 112 | The protocol could be modified so that DH shared 113 | secrets were valid e.g. for some pre-arranged 114 | time period. Then Alice could send multiple 115 | messages to Bob during that time period. The cost 116 | is of course, reduction in perfect forward secrecy. 117 | 118 | 3. In practice, when PFS is desired, it is easier to generate a new DH 119 | key pair and send the DH public key as a separate message, rather than including 120 | it in the plaintext message. This is actually the way 121 | that encoDHer has implemented PFS. The option ```--mutate-key``` 122 | is used to do this. 123 | 124 | ### 4. FAQ 125 | 126 | Q. Why symmetric encryption? Isn't public-key good enough if we use --throw-keyids as an option to GPG? 127 | 128 | * The symmetric encryption with dynamic DH shared secrets provides perfect forward secrecy. Once the DH key pair is destroyed, old messages can't be read, even if either Alice or Bob is compromised. To try to accomplish the same thing with public key encryption methods would be much more expensive and time-consuming because public key encryption keys are far more difficult to generate. 129 | 130 | The one possible exception to this is the first two messages - since both DH public keys are assumed to be available long-term on a key tablet, if either Alice or Bob is compromised, the first two messages could be read by an attacker. To compensate for this, it is recommended that the first two messages be throw-away messages, used only to exchange new DH public keys. 131 | 132 | Q. Why use mixmaster/tor combination to submit messages to alt.anonymous.messages? Isn't one or the other good enough? 133 | 134 | * Mixmaster is vulnerable to tagging attacks. Using tor as a submission channel to mixmaster prevents tagged messages from being traced to the sender. Tor is vulnerable to traffic analysis due to its low latency. Using high-latency mixmaster reduces the effectiveness of these attacks. 135 | Note that the submission to the mixmaster network is via smtp. As a result, this should be done using ssl over tor to further prevent traffic analysis and mitm attacks. Also, tor blocks port 25, so open smtp can't be done anyway. 136 | 137 | Q. Why use tor to search alt.anonymous.messages? If all messages are downloaded, no one can tell which of them you are interested in, can they? 138 | 139 | * That is true, but our threat model includes not wanting anyone to know that Alice and Bob are communicating. tor anonymizes the search of alt.anonymous.messages. 140 | 141 | Q. Why use alt.anonymous.messages at all? Couldn't Alice send her message directly to Bob? 142 | 143 | * Yes, but that is difficult to do anonymously. 144 | 145 | Q. What happens if the chain is broken - and one of the messages gets lost. Doesn't that break the sequential DH shared secret bootstrapping? 146 | 147 | * Yes. You would simply start over if this happened. 148 | 149 | Q. What does a typical message to be submitted to alt.anonymous.messages look like? 150 | * Here is an example. The message would be submitted via mixmaster using the command: 151 | ``` 152 | mixmaster -c1 < message.txt 153 | ``` 154 | where message.txt has the following contents: 155 | 156 | ``` 157 | To: mail2news@dizum.com,mail2news@m2n.mixmin.net 158 | Subject: c73dc0a5f92ca70b0b0a0ee98eaec862901f25f3cc6796e2 159 | Newsgroups: alt.anonymous.messages 160 | X-No-Archive: Yes 161 | 162 | -----BEGIN PGP MESSAGE----- 163 | 164 | jA0ECQMIJ1NWy0QcizvU0usB6xNTTWPjDmgEnRiI1kU/ROrWkeXKpMsO//VLYhqs 165 | kogetdM0JjLQuFHJBdEoLiR2jP/L/Avaer1DDq0MymnolasNhq5U2uOZjC6O8u3a 166 | /RPgt3iYSiMnTQbW+cLN+TBs3pO4fasVFJ0tTHJZkse+daCMmRlm3c585mFdwuNE 167 | 0ReQFJnBgUy0wFQGb4SAhVlOZhRDFq89vYCbbo3IoPUbycjuV3yjYNBlnqOnC9SL 168 | ... 169 | 6fvQLr+rx01QrvXodriMG6gbUKh6342z9Yhua8aN+MtQMwWHpTVf4eP8xPhxjJF6 170 | RhSOkC/xdzthjp5g4Ii7yJ0FsuKX/APubMHIw3aNPDjJ4+eUN/Q2KrcQIgoAM661 171 | DDGBFx03kxMIlVktkF+zZ12Bnxo+YdE1I64ONVv3v38Urc07qperf1eGo5kfvwQI 172 | mp/CAc7AhgdYg7TRasP3v6PRj3Ac+hXObUlI98mNyvOnqhDAKtv9gbGyN2n8RHmK 173 | IOck 174 | =AUXa 175 | -----END PGP MESSAGE----- 176 | ``` 177 | 178 | The included headers will: 179 | 180 | 1. send the message to two different mail2news servers 181 | 2. have hsub subject c73... 182 | 3. will be posted at alt.anonymous.messages 183 | 4. will be (hopefully - although it doesn't really matter) unarchived in one week. 184 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | 0.3 - Oct. 16, 2013 2 | * keys.db is now encrypted with AES256 (passphrase supplied by user) 3 | * moved aam parser from rfc822 module to email module 4 | * --fetch-aam option now writes each encrypted message to a separate file 5 | * README.md and ANONYMOUS.md received significant updates 6 | * Updated encoDHer to use OpenSSL for key generation if M2Crypto is 7 | available. M2Crypto is a python wrapper library for OpenSSL. If M2Crypto 8 | is not available, encoDHer will use the old module from Mark Loiseau 9 | (renamed dh_pydhe and updated to use the same prime as in the distributed 10 | dhparams.pem file). A dhparams.pem file is now distributed with encoDHer 11 | that contains an 8192 bit prime using a generator of 5. Such a big prime 12 | is overkill for generating an AES256 encryption key, but what the heck... 13 | Unfortunately, old keys.db databases are not compatible with this upgrade 14 | and will need to be regenerated. 15 | * If the dhparams.pem file is absent, encoDHer will use the Loiseau module 16 | (renamed dh_legacy) with the original 6144-bit RFC3526 prime. This is 17 | backwards-compatible with old keys.db databases, but will NOT be 18 | compatible with databases using the dh_m2crypto or dh_pydhe modules. 19 | 20 | 0.2 - Oct. 8, 2013 21 | * encoDHer now decrypts unicode strings properly 22 | * Invalid public key exception during a.a.m search is now handled 23 | gracefully (this might happen e.g. when you have created a new 24 | route, but not yet imported the destination public key) 25 | * s2k hash has been changed to sha256 26 | * --list-keys changed to --list-routes 27 | * added encodher DH and GPG public keys 28 | 29 | $ gpg --fingerprint encodher 30 | pub 8192R/9F16F7B2 2013-10-09 [expires: 2018-10-08] 31 | Key fingerprint = BB8C 19BB 09C1 19FE 72AA 06F7 8BD1 334F 9F16 F7B2 32 | uid encodher 33 | sub 8192R/8E37D228 2013-10-09 [expires: 2018-10-08] 34 | sub 8192R/AD535BD8 2013-10-09 [expires: 2018-10-08] 35 | 36 | 0.1 - initial release 37 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [encoDHer] [1] - ephemeral Diffie-Hellman for email communications 2 | === 3 | 4 | [1]: https://github.com/rxcomm/encoDHer/ "encoDHer" 5 | 6 | ### Introduction 7 | 8 | encoDHer is a python utility to facilitate symmetric encryption of email 9 | messages using the Diffie-Hellman (DH) protocol for generating a shared 10 | secret between the sender and recipient of an email message. 11 | 12 | Keys are stored in the database file keys.db. 13 | 14 | encoDHer implements perfect forward secrecy (PFS) in email communications. 15 | It is essentially ephemeral Diffie-Hellman for email, where dynamic key changes 16 | are provided by the ```--mutate-key``` option in encoDHer. 17 | 18 | ### Why symmetric encryption? Isn't using public key encryption good enough if we use ```--throw-keyids``` as an option with GPG? 19 | 20 | The biggest argument in favor of 21 | symmetric encryption has to do with the difficulty required to generate new keys. It is 22 | much easier to generate a new set of DH keys than it is to generate a new pair of RSA keys, 23 | for example. 24 | So, when we want to rotate keys to preserve perfect forward secrecy, the key-generation 25 | process is very quick. 26 | 27 | An important second argument 28 | in favor of using the DH key exchange protocol is that for 29 | a given key length, DH protocols are stronger than public key protocols. The additional 30 | strength comes from the fact that the best known algorithm for cracking either is the 31 | [General Number Field Sieve] [2]. The matrix algebra part of this algorithm involves 32 | a large matrix with bits as entries for public key protocols, and with large integers as 33 | entries for DH protocols. In essence, this makes the DH protocols stronger by a factor 34 | of the length of the integers in the matrix (the length of the large prime used in DH). 35 | More detail on the above can be found 36 | [here] [3]. 37 | 38 | [2]: https://en.wikipedia.org/wiki/General_number_field_sieve "General Number Field Sieve" 39 | [3]: http://security.stackexchange.com/questions/35471/is-there-any-particular-reason-to-use-diffie-hellman-over-rsa-for-key-exchange" "here" 40 | 41 | One further advantage of DH protocols is that both sender and receiver are automatically 42 | authenticated. 43 | It takes the sender's DH secret key and receiver's DH public key to encrypt a message 44 | and the sender's DH public key and receiver's DH private key to decrypt the message. 45 | In contrast, public key protocols only authenticate the receiver - anyone can encrypt 46 | a message using the receiver's public key. While it is true that the sender can sign the 47 | message to authenticate it, this requires a separate operation and is not a part of 48 | the basic public key encryption protocol. 49 | 50 | There are some additional minor advantages that arise due to the nature of the standards 51 | specifying these two encryption methodologies - DH is free and the public-key algorithms 52 | have historically been protected by patents. 53 | 54 | The primary disadvantage of using DH for generating shared secrets is, of course, 55 | that you need a separate DH secret key for each email route that you want to use. 56 | EncoDHer provides a simple way to manage all of these keys. 57 | 58 | EncoDHer also provides a mechanism for anonymous communication between parties. 59 | In this case, communication takes place via the public usenet newsgroup mailbox 60 | alt.anonymous.messages rather than by standard email. 61 | 62 | ### Installation requirements 63 | 64 | The encodher package requires python-gnupg-0.3.5 or greater to function. 65 | The latest version is documented at: 66 | 67 | http://pythonhosted.org/python-gnupg/ 68 | 69 | Since version 0.3, encoDHer uses OpenSSL (through the M2Crypto library) 70 | for key generation and Diffie Hellman parameter management. 71 | Details regarding the use of OpenSSL are explained further 72 | below in this README. We note the following for those desiring legacy operation: 73 | 74 | * Legacy (pre-version 0.3) operation of encoDHer made use of the DiffieHellman() class from [Mark Loiseau] [4]. This Diffie Hellman class is still included in the distribution and 75 | can be used by removing the dhparams.pem file. 76 | 77 | [4]: http://blog.markloiseau.com/2013/01/diffie-hellman-tutorial-in-python/ "Mark Loiseau" 78 | 79 | Finally, this package requires the use of gnupg to sign DH public keys for 80 | export and to identify DH public keys for import. You will need the 81 | GPG secret key to sign your DH keys, and the receiver's GPG public key to 82 | verify and import DH public keys. 83 | 84 | You should also edit the constants.py file to reflect your parameters. 85 | 86 | Install the encoDHer module using the command: 87 | 88 | sudo python setup.py install 89 | 90 | from the encoDHer directory. An executable named encodher will be created 91 | and copied to /usr/local/bin/encodher. The setup.py command should also 92 | automatically install python-gnupg with most linux variants if you have ```setuptools``` 93 | installed (for example, ```sudo apt-get install python-setuptools``` in ubuntu). 94 | 95 | ### Startup 96 | 97 | To use the program, you must first initialize the keys database. This is 98 | accomplished with the following command: 99 | 100 | encodher --init 101 | 102 | Once your database is created, you can generate keys for specific email routes 103 | using the command: 104 | 105 | encodher --gen-key sender@example.org receiver@otherexample.org 106 | 107 | where your email address is sender@example.org and your intended recipient's 108 | email address is receiver@otherexample.org. Note that using the DH shared 109 | secret protocol requires generating a DH secret key for each sender -> receiver 110 | route. So you will probably end up with several keys in the database. 111 | 112 | ### Key distribution 113 | 114 | You can then export your signed DH public key with the command: 115 | 116 | encodher --sign-pub sender@example.org receiver@otherexample.org 117 | 118 | The output will be a GPG signed version of your DH public key. You can then 119 | send that public key to a recipient over a non-secret channel. An 120 | anonymized key tablet will be developed later to facilitate DH public key 121 | exchanges for the encodher utility, but any nonsecure channel will work. 122 | 123 | When the recipient receives your DH public key, she can then import your 124 | key into her database using the command: 125 | 126 | encodher --import textfile 127 | 128 | where textfile is a text file containing your signed DH public key. Note 129 | that the GPG public key used to sign your DH public key must be in her 130 | keychain in order to verify the signature on the DH public key. 131 | 132 | Your intended recipient should then export her signed DH public key and 133 | send it to you. You can then import her signed DH public key and you 134 | are ready to communicate using symmetric key encryption with a DH shared 135 | secret key. 136 | 137 | ### Message encryption and exchange 138 | 139 | To encrypt a message, first create the plaintext in a file. You can 140 | then encrypt the contents of that message with your DH shared secret 141 | key using the command: 142 | 143 | encodher --encode-email file sender@example.org receiver@otherexample.org 144 | 145 | The email will be encrypted using symmetric AES256 encryption and output 146 | to file.asc. The file is an ascii-armored pgp-format file. 147 | 148 | Upon receipt of the encrypted message, the receiver can then decrypt the 149 | file using the command: 150 | 151 | encodher --decode-email file.asc sender@example.org receiver@otherexample.org 152 | 153 | The plaintext message will then be displayed. It is probably good to note 154 | here that the first email address is always the message sender, and the second 155 | is always the receiver. So for example, if I received a message at 156 | alice@alice.com from my buddy bob@bob.com, the correct syntax to decrypt the 157 | message would be: 158 | 159 | encodher --decode-email file.asc bob@bob.com alice@alice.com 160 | 161 | because bob was the sender of the email and alice was the receiver. When alice 162 | encrypts an email to bob, the correct syntax is: 163 | 164 | encodher --encode-email file alice@alice.com bob@bob.com 165 | 166 | because in this case alice is the sender and bob the receiver. 167 | 168 | ### Key cloning 169 | 170 | It is possible to clone your DH secret key to another route. This functionality 171 | is useful when, for example you want to post your DH public key on a 172 | key table or other public place to enable multiple people to send you 173 | encrypted email. You clone keys by using the command: 174 | 175 | encodher --clone-key old1@first.org old2@second.org new1@third.org new2@fourth.org 176 | 177 | This will clone your secret key from the route old1@first.org -> old2@second.org 178 | to the new route new1@third.org -> new2@fourth.org. When someone wants 179 | to use your posted DH public key to send you encrypted email, they will send 180 | you their DH public key over any insecure channel. You can then import their 181 | public key and the new route will have a completely different shared secret 182 | than the old route does. 183 | 184 | ### Other options 185 | 186 | Various options for key management exist. The following list of options 187 | can be obtained by executing encodher without any arguments. 188 | 189 | Options: 190 | --init, -i: initialize keys.db database 191 | --import, -m: import signed public key 192 | --mutate-key, -a: mutate DH secret key 193 | --sign-pub, -s: sign your own public key 194 | --change-toemail, -t: change toEmail on key 195 | --change-fromemail, -f: change fromEmail on key 196 | --change-pubkey, -p: change public key for fromEmail -> toEmail 197 | --encode-email, -e: symmetrically encode a file for fromEmail -> toEmail 198 | --decode-email, -d: symmetrically decode a file for fromEmail -> toEmail 199 | --list-routes, -l: list all routes in database 200 | --gen-secret, -c: generate shared secret for fromEmail -> toEmail 201 | --gen-key, -n: generate a new key for fromEmail -> toEmail 202 | --get-key, -g: get key for fromEmail -> toEmail from database 203 | --fetch-aam, -h: fetch messages from alt.anonymous.messages newsgroup 204 | --clone-key, -y: clone key from one route to another 205 | --rollback, -b: roll back the a.a.m last read timestamp 206 | --change-dbkey, -k: change keys.db encryption key 207 | 208 | ### Perfect forward secrecy 209 | 210 | The primary reason for using symmetric encryption with DH shared secrets 211 | for email exchanges is to provide for perfect forward secrecy (PFS). If, after 212 | an exchange, the DH keys are destroyed by both parties, any messages 213 | encrypted with these keys can no longer be read, achieving PFS. Users can 214 | change their keys to take advantage of PFS by executing: 215 | 216 | encodher --mutate-key sender@example.org receiver@example.org 217 | 218 | This will destroy sender@example.org's old DH secret key, generate a new 219 | DH secret key and export the corresponding new DH public key encrypted with the 220 | old DH shared secret. This encrypted file can be emailed to the receiver, 221 | who can then decrypt the file and import the key using the ```--import``` option. 222 | If an unencrypted version of the new signed DH public key is desired, 223 | the ```--sign-pub``` option can be used. Once the new DH public key has been 224 | imported by the receiver, no one (including the original sender and receiver) 225 | will be able to read the old messages. Change keys carefully. 226 | 227 | ### Anonymous communication 228 | 229 | If anonymous communication is desired, encodher presents an option to encode 230 | the email for transmission using the mixmaster network. Once the appropriate 231 | mixmaster headers are added (by answering affirmatively to the question about 232 | sending anonymously), the message can be dispatched to the 233 | alt.anonymous.messages newsgroup with the command: 234 | 235 | mixmaster -c 1 < message.asc 236 | 237 | where message.asc contains the encrypted message and plaintext headers. Note 238 | that you must have the mixmaster https://github.com/crooks/mixmaster package 239 | installed and stats updated for this to work. Most linux flavors have this 240 | package available. 241 | 242 | To receive messages sent to you at a.a.m using a DH key of yours, you can 243 | execute the command: 244 | 245 | encodher --fetch-aam 246 | 247 | This will fetch and decrypt all a.a.m messages for each of the keys in your 248 | database. 249 | 250 | ### Building an executable 251 | 252 | To install the executable, change to the encoDHer directory and execute the command: 253 | 254 | sudo python setup.py install 255 | 256 | This will create the executable named 'encodher' and copy it to /usr/local/bin/encodher. 257 | You will need the python-gnupg library 258 | (version 0.3.5 or greater - see the link above) before the executable will run. 259 | This should be automatically installed by setup.py for most linux variants. 260 | 261 | If you don't want to download the entire source, the executable should run on 262 | most linux systems without any changes. So you can grab a copy using wget: 263 | 264 | wget https://github.com/rxcomm/encoDHer/raw/master/encodher 265 | 266 | make it executable: 267 | 268 | chmod +x encodher 269 | 270 | and it should run if you have python-gnupg installed. To extract the python source 271 | from the executable, rename it as a .zip archive and unzip it, e.g.: 272 | 273 | mv encodher encodher.zip 274 | unzip encodher.zip 275 | 276 | ### encoDHer with OpenSSL 277 | 278 | Since version 0.3, encoDHer has used OpenSSL for key generation. 279 | The Diffie-Hellman parameters are imported from an OpenSSL dhparams.pem file. 280 | encoDHer interacts with OpenSSL through the M2Crypto library. 281 | In most linux systems, the M2Crypto library can be installed through the 282 | command: 283 | 284 | ``` 285 | sudo apt-get install python-m2crypto 286 | ``` 287 | 288 | or similar, depending on your particular flavor of linux. 289 | If M2Crypto is not present, encoDHer will use a version of the 290 | DiffieHellman() class that contains the same prime, generator, and keysize 291 | that is distributed in dhparams.pem. If the dhparams.pem file is not present, encoDHer will 292 | gracefully roll back to the pre-version 0.3 DiffieHellman() class from Mark Loiseau. 293 | 294 | The dhparams.pem file that is distributed with encoDHer uses an 8192 bit 295 | prime and a generator of 5. This file is NOT secret, and may be re-used. 296 | 297 | *For* *the* *truly* *paranoid* - if you don't trust the dhparams.pem file provided by 298 | me and want to replace it with your own, the command to generate 299 | a new set of DH parameters with an 8192 bit prime is: 300 | 301 | ``` 302 | openssl dhparam -[2,5] -out dhparams.pem 8192 303 | ``` 304 | 305 | Using 2 in the command will force a generator of 2, and 5 will force a 306 | generator of 5. Keep in mind that everyone you communicate with needs to use 307 | the same set of DH parameters, so you will need to distribute those somehow. 308 | Smaller prime sizes (4096, 2048, 1024) will also work, although you will see 309 | a lot of zeros in your exported DH public keys. 310 | 311 | To find the prime in your new dhparams.pem file, execute the command: 312 | 313 | ``` 314 | ./dh_m2crypto.py 315 | ``` 316 | 317 | This will run a key-matching test, and both the prime and generator are output 318 | as a part of this test. If you do change dhparams.pem, you should also edit 319 | the prime and generator definitions in dh\_pydhe.py to reflect your new prime and 320 | generator. The prime should be copied directly (incluing the 0x hex prefix). 321 | If you change the prime size, you should also change the DH private key size in 322 | the \_\_init\_\_() method of dh\_pydhe.py to match your new prime. 323 | -------------------------------------------------------------------------------- /__main__.py: -------------------------------------------------------------------------------- 1 | import encodher 2 | import sys 3 | 4 | def main(): 5 | encodher.main() 6 | 7 | if __name__ == '__main__': 8 | main() 9 | -------------------------------------------------------------------------------- /constants.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | 5 | user_path = os.path.expanduser('~') 6 | config_path = user_path+'/.config/encoDHer' 7 | 8 | if not os.path.exists(config_path): 9 | os.makedirs(config_path) 10 | 11 | # working directory 12 | HOME = config_path # should be ~/.config/encoDHer for most installs 13 | 14 | # GPG public keyring 15 | KEYRING = [config_path+'/pubring.gpg', user_path+'/.gnupg/pubring.gpg'] 16 | 17 | # GPG secret keyring 18 | SECRET_KEYRING = [config_path+'/secring.gpg', user_path+'/.gnupg/secring.gpg'] 19 | 20 | # GPG binary 21 | #GPGBINARY = '/usr/bin/gpg' 22 | GPGBINARY = '/usr/bin/gpg2' 23 | 24 | # newsserver address 25 | NEWSSERVER = "localhost" 26 | 27 | # newsserver port 28 | NEWSPORT = 119 29 | 30 | # location of keys database 31 | KEYS_DB = config_path+'/keys.db' 32 | 33 | # symmetric cipher to be used - any cipher from gpg --version can go here 34 | CIPHER = 'AES256' 35 | #CIPHER = 'CAMELLIA256' 36 | -------------------------------------------------------------------------------- /dh_legacy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | PyDHE - Diffie-Hellman Key Exchange in Python 4 | Copyright (C) 2013 by Mark Loiseau 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | 19 | 20 | For more information: 21 | http://blog.markloiseau.com/2013/01/diffie-hellman-tutorial-in-python/ 22 | 23 | Reformatted and modified to display dhparams when executed directly. 24 | All modifications Copyright (C) 2013 by David R. Andersen 25 | and released under the GNU General Public License. 26 | """ 27 | 28 | from binascii import hexlify 29 | import hashlib 30 | 31 | # If a secure random number generator is unavailable, exit with an error. 32 | try: 33 | import Crypto.Random.random 34 | secure_random = Crypto.Random.random.getrandbits 35 | except ImportError: 36 | import OpenSSL 37 | secure_random = lambda x: long(hexlify(OpenSSL.rand.bytes(x>>3)), 16) 38 | 39 | 40 | class DiffieHellman(object): 41 | """ 42 | A reference implementation of the Diffie-Hellman protocol. 43 | This class uses the 6144-bit MODP Group (Group 17) from RFC 3526. 44 | This prime is sufficient to generate an AES 256 key when used with a 540+ bit 45 | exponent. 46 | """ 47 | 48 | prime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DCC4024FFFFFFFFFFFFFFFF 49 | generator = 2 50 | 51 | def __init__(self): 52 | """ 53 | Generate the public and private keys. 54 | """ 55 | self.privateKey = self.genPrivateKey(576) 56 | self.publicKey = self.genPublicKey() 57 | 58 | 59 | def genPrivateKey(self, bits): 60 | """ 61 | Generate a private key using a secure random number generator. 62 | """ 63 | return secure_random(bits) 64 | 65 | 66 | def genPublicKey(self): 67 | """ 68 | Generate a public key X with g**x % p. 69 | """ 70 | return pow(self.generator, self.privateKey, self.prime) 71 | 72 | 73 | def checkPublicKey(self, otherKey): 74 | """ 75 | Check the other party's public key to make sure it's valid. 76 | Since a safe prime is used, verify that the Legendre symbol is equal to one. 77 | """ 78 | if(otherKey > 2 and otherKey < self.prime - 1): 79 | if(pow(otherKey, (self.prime - 1)/2, self.prime) == 1): 80 | return True 81 | return False 82 | 83 | 84 | def genSecret(self, privateKey, otherKey): 85 | """ 86 | Check to make sure the public key is valid, then combine it with the 87 | private key to generate a shared secret. 88 | """ 89 | if(self.checkPublicKey(otherKey) == True): 90 | sharedSecret = pow(otherKey, privateKey, self.prime) 91 | return sharedSecret 92 | else: 93 | raise Exception("Invalid public key.") 94 | 95 | 96 | def genKey(self, privateKey, otherKey): 97 | """ 98 | Derive the shared secret, then hash it to obtain the shared key. 99 | """ 100 | self.sharedSecret = self.genSecret(privateKey, otherKey) 101 | s = hashlib.sha256() 102 | s.update(str(self.sharedSecret)) 103 | self.key = s.digest() 104 | 105 | def getKey(self): 106 | """ 107 | Return the shared secret key 108 | """ 109 | return self.key 110 | 111 | def showParams(self): 112 | """ 113 | Show the Diffie Hellman parameters obtained from dhparams.pem file. 114 | """ 115 | print '' 116 | print "DH Parameters:" 117 | p_len = len(hex(self.prime)) 118 | print "Prime: ", hex(self.prime)[:p_len-1] 119 | print "Prime Length: ", str((p_len-3) * 4)+' bits' 120 | print "Generator: ", str(self.generator) 121 | 122 | def showResults(self): 123 | """ 124 | Show the results of a Diffie-Hellman exchange. 125 | """ 126 | print "Results:" 127 | print 128 | print "Shared secret: ", self.sharedSecret 129 | print "Shared key: ", hexlify(self.key) 130 | print 131 | 132 | if __name__ == '__main__': 133 | """ 134 | Run an example Diffie-Hellman exchange 135 | """ 136 | 137 | a = DiffieHellman() 138 | b = DiffieHellman() 139 | 140 | a.genKey(a.privateKey, b.publicKey) 141 | b.genKey(b.privateKey, a.publicKey) 142 | 143 | if(a.getKey() == b.getKey()): 144 | print "Shared keys match." 145 | print '' 146 | print "Key:", hexlify(a.key) 147 | else: 148 | print "Shared secrets didn't match!" 149 | print "Shared secret: ", a.genSecret(a.privateKey, b.publicKey) 150 | print "Shared secret: ", b.genSecret(b.privateKey, a.publicKey) 151 | 152 | a.showParams() 153 | 154 | -------------------------------------------------------------------------------- /dh_m2crypto.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | PyDHE - Diffie-Hellman Key Exchange in Python 4 | Copyright (C) 2013 by Mark Loiseau 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | 19 | 20 | For more information: 21 | http://blog.markloiseau.com/2013/01/diffie-hellman-tutorial-in-python/ 22 | 23 | Modified to use M2Crypto OpenSSL library for DH parameters. 24 | All modifications Copyright (C) 2013 by David R. Andersen 25 | and released under the GNU General Public License. 26 | """ 27 | 28 | import hashlib 29 | from binascii import hexlify 30 | from M2Crypto import DH 31 | from constants import * 32 | 33 | class DiffieHellman(object): 34 | 35 | def __init__(self): 36 | """ 37 | Load OpenSSL dhparams from dhparams.pem file - the encoDHer distribution 38 | includes a 8192 bit prime in dhparams.pem. Also, strip the OpenSSL headers 39 | from the imported dhparams and convert to long. 40 | """ 41 | self.dh = DH.load_params('/usr/local/lib/dhparams.pem') 42 | self.dh.gen_key() 43 | self.prime = long(hexlify(self.dh.p)[10:], 16) 44 | self.generator = int(hexlify(self.dh.g)[8:], 16) 45 | self.privateKey = long(hexlify(self.dh.priv)[8:], 16) 46 | self.publicKey = long(hexlify(self.dh.pub)[8:], 16) 47 | 48 | def genSecret(self, privateKey, otherKey): 49 | """ 50 | Generate a shared secret using my privateKey and target's otherKey. 51 | We can't use OpenSSL for this because it won't let us import the 52 | private key. The OpenSSL DH implementation is optimized (naturally) 53 | for SSL/TLS encryption, so it has no idea about importing or exporting 54 | keys for use later. So we use this hack - but it's not too ugly! 55 | """ 56 | sharedSecret = pow(otherKey, privateKey, self.prime) 57 | return sharedSecret 58 | 59 | def genKey(self, privateKey, otherKey): 60 | """ 61 | Derive the shared secret, then hash it to obtain the shared secret 62 | used for AES256 encryption. 63 | """ 64 | sharedSecret = self.genSecret(privateKey, otherKey) 65 | s = hashlib.sha256() 66 | s.update(str(sharedSecret)) 67 | self.key = s.digest() 68 | 69 | def getKey(self): 70 | """ 71 | Return the shared secret key 72 | """ 73 | return self.key 74 | 75 | 76 | def showParams(self): 77 | """ 78 | Show the Diffie Hellman parameters obtained from dhparams.pem file. 79 | """ 80 | print '' 81 | print "DH Parameters:" 82 | p_len = len(hex(self.prime)) 83 | print "Prime: ", hex(self.prime)[:p_len-1] 84 | print "Prime Length: ", str((p_len-3) * 4)+' bits' 85 | print "Generator: ", str(self.generator) 86 | 87 | 88 | if __name__ == '__main__': 89 | """ 90 | Run an example Diffie-Hellman exchange 91 | """ 92 | 93 | a = DiffieHellman() 94 | b = DiffieHellman() 95 | 96 | a.genKey(a.privateKey, b.publicKey) 97 | b.genKey(b.privateKey, a.publicKey) 98 | 99 | if(a.getKey() == b.getKey()): 100 | print "Shared keys match." 101 | print '' 102 | print "Key:", hexlify(a.key) 103 | else: 104 | print "Shared secrets didn't match!" 105 | print "Shared secret: ", a.genSecret(a.privateKey, b.publicKey) 106 | print "Shared secret: ", b.genSecret(b.privateKey, a.publicKey) 107 | 108 | a.showParams() 109 | -------------------------------------------------------------------------------- /dh_pydhe.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | PyDHE - Diffie-Hellman Key Exchange in Python 4 | Copyright (C) 2013 by Mark Loiseau 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | 19 | 20 | For more information: 21 | http://blog.markloiseau.com/2013/01/diffie-hellman-tutorial-in-python/ 22 | 23 | Modified to use dhparams.pem from OpenSSL for DH parameters. 24 | All modifications Copyright (C) 2013 by David R. Andersen 25 | and released under the GNU General Public License. 26 | """ 27 | 28 | from binascii import hexlify 29 | import hashlib 30 | 31 | # If a secure random number generator is unavailable, exit with an error. 32 | try: 33 | import Crypto.Random.random 34 | secure_random = Crypto.Random.random.getrandbits 35 | except ImportError: 36 | import OpenSSL 37 | secure_random = lambda x: long(hexlify(OpenSSL.rand.bytes(x>>3)), 16) 38 | 39 | 40 | class DiffieHellman(object): 41 | """ 42 | A reference implementation of the Diffie-Hellman protocol. 43 | This class uses the same prime that is shipped with the dhparams.pem file 44 | in the encoDHer distriubtion. It is an 8192 bit prime generated using: 45 | 46 | openssl dhparam -5 -out dhparams.pem 8192 47 | 48 | and so will be compatible with encoDHer installations using the dh_m2crypto 49 | module. 50 | """ 51 | 52 | prime = 0xeb8d2e0bfda29137c04f5a748e88681e87038d2438f1ae9a593f620381e58b47656bf5386f7880da383788a35d3b4a6991d3634b149b3875e0dccff21250dccc0bf865a5b262f204b04e38b2385c7f4fb4e2058f73a8f65252e556b667b1570465b2f6d1beeab215b05cd0e28b9277f3f48c01b1619b30147fcfc87b5b6903e70078babb45c2ee6a6bd4099ab87b01ba09a38c36279b46309ef0df5e45e15df9ba5cb296baa535c60bb0065669fd8078269eb759416d9b27229f9cb6e5f60f7d8756f6f621ad519745f914e81a7c8d09b3c7a764863dd5d5f2bcab5ef283aa3781c985d07f2b1aafb2e7747b3217dbbfea2e91484c31a00e22467c0c7f9d40f73d392594c516b302aa7c1aa6ca5a0b346cc6bfc1cd201dfe78aabf717f6c69f30a896567b07090e352e87fd698128da0594916d27203e22b7bb1f7f860842fd0aee2e532a077629451ef86163fdf567048266050a473d4db27e85a33bc985b16569afddaa9a94a5b9155b32b78c84b261ce7acf7d8d0ef23d4e1d028104aff6a77cab79ecdf7dd19468f67d3cb9b86835cce1a87dbf4b2d3100a9bd7a9e251272bf4e2fed2c2f7535e556b8cc1fc6fcfc1a2ca188c02ea9298bb4a7f12afd4164ad9211f7935f51be3d9d932e835a1fd322e7db75ba587021f8c730d7f021905e89a0ddb80bf8ea53b8f1603cf08c734aadfe7f9184e0de9e91651c3d88deb68fd1bc0188e479747caab9a157ef6ec68295a1bfb6391973364987cda6c7817dfee2ab9d4e0eaefb29154f23eafedcab06d67fbcc5d1788a20315c50f9c6471dbb45419b07ddec0d507c16a0b7e2d79290d3115edcdc2996897015dfa430389a1d63533e52aa6309c76e7069e0a99af65702036e7829bc8e86ad3e23983debf72c82d8e3a2e9d767cccfb2abed6b0b0c9f217bb496ea816ea3c32111f60916d91f8a97cfa38b163ca1261733cd98cb2ff77a7ee9290bda74be8dc206489d06abca4e5ae82ae4923fa43b451fa419da06d74f15e4efc4852bf5edf37e581edeaaefd28a8b3c672bb76068439635adecebaf8311d4018fe8e62892f784d7a44747178c4cb540c58e5e2a660a3f02c873d12b43f0643d3794d8b310fe9fa6d798e0724d38c85c9e4d5c8c9ba645f3411dd4645ef1ef1dad9ba60325b12def1bd706d11386045e450fee2a60c88cf6387dea0521acc4d869fb146a47ef4e34480d30f84ffa0e0e0a4a4c7f1b0a8e642223e8bec4d1c8effd98ba235dc5c5f7e296ecd7476595ef17371a1aec3a38c3e7f7e08e7b5e7c927f5843062f753e5ee85f7e64164dd0ccb7261d4ca3a35058ca88f87275a292e96100005c025742f85be7a2598406b9c792f2ba2a496f8074d899821110effb184e3c679330b182a8c14ba1699f3761168d64e838829c0250c6be87bc8dc2b29954bf6cb450ba7bed793cf97 53 | 54 | generator = 5 55 | 56 | def __init__(self): 57 | """ 58 | Generate the public and private keys. 59 | """ 60 | self.privateKey = self.genPrivateKey(8192) 61 | self.publicKey = self.genPublicKey() 62 | 63 | 64 | def genPrivateKey(self, bits): 65 | """ 66 | Generate a private key using a secure random number generator. 67 | """ 68 | return secure_random(bits) 69 | 70 | 71 | def genPublicKey(self): 72 | """ 73 | Generate a public key X with g**x % p. 74 | """ 75 | return pow(self.generator, self.privateKey, self.prime) 76 | 77 | 78 | def checkPublicKey(self, otherKey): 79 | """ 80 | Check the other party's public key to make sure it's valid. 81 | Since a safe prime is used, verify that the Legendre symbol is equal to one. 82 | """ 83 | if(otherKey > 2 and otherKey < self.prime - 1): 84 | if(pow(otherKey, (self.prime - 1)/2, self.prime) == 1): 85 | return True 86 | return False 87 | 88 | 89 | def genSecret(self, privateKey, otherKey): 90 | """ 91 | Check to make sure the public key is valid, then combine it with the 92 | private key to generate a shared secret. Here we skip the Legendre 93 | Symbol check because OpenSSL does not use this for their primes and 94 | we want to be compatible with the OpenSSL implementation. 95 | """ 96 | sharedSecret = pow(otherKey, privateKey, self.prime) 97 | return sharedSecret 98 | 99 | 100 | def genKey(self, privateKey, otherKey): 101 | """ 102 | Derive the shared secret, then hash it to obtain the shared key. 103 | """ 104 | self.sharedSecret = self.genSecret(privateKey, otherKey) 105 | s = hashlib.sha256() 106 | s.update(str(self.sharedSecret)) 107 | self.key = s.digest() 108 | 109 | def getKey(self): 110 | """ 111 | Return the shared secret key 112 | """ 113 | return self.key 114 | 115 | def showParams(self): 116 | """ 117 | Show the Diffie Hellman parameters obtained from dhparams.pem file. 118 | """ 119 | print '' 120 | print "DH Parameters:" 121 | p_len = len(hex(self.prime)) 122 | print "Prime: ", hex(self.prime)[:p_len-1] 123 | print "Prime Length: ", str((p_len-3) * 4)+' bits' 124 | print "Generator: ", str(self.generator) 125 | 126 | def showResults(self): 127 | """ 128 | Show the results of a Diffie-Hellman exchange. 129 | """ 130 | print "Results:" 131 | print 132 | print "Shared secret: ", self.sharedSecret 133 | print "Shared key: ", hexlify(self.key) 134 | print 135 | 136 | if __name__ == '__main__': 137 | """ 138 | Run an example Diffie-Hellman exchange 139 | """ 140 | 141 | a = DiffieHellman() 142 | b = DiffieHellman() 143 | 144 | a.genKey(a.privateKey, b.publicKey) 145 | b.genKey(b.privateKey, a.publicKey) 146 | 147 | if(a.getKey() == b.getKey()): 148 | print "Shared keys match." 149 | print '' 150 | print "Key:", hexlify(a.key) 151 | else: 152 | print "Shared secrets didn't match!" 153 | print "Shared secret: ", a.genSecret(a.privateKey, b.publicKey) 154 | print "Shared secret: ", b.genSecret(b.privateKey, a.publicKey) 155 | 156 | a.showParams() 157 | 158 | -------------------------------------------------------------------------------- /dhparams.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN DH PARAMETERS----- 2 | MIIECAKCBAEA640uC/2ikTfAT1p0johoHocDjSQ48a6aWT9iA4Hli0dla/U4b3iA 3 | 2jg3iKNdO0ppkdNjSxSbOHXg3M/yElDczAv4ZaWyYvIEsE44sjhcf0+04gWPc6j2 4 | UlLlVrZnsVcEZbL20b7qshWwXNDii5J38/SMAbFhmzAUf8/Ie1tpA+cAeLq7RcLu 5 | amvUCZq4ewG6CaOMNiebRjCe8N9eReFd+bpcspa6pTXGC7AGVmn9gHgmnrdZQW2b 6 | JyKfnLbl9g99h1b29iGtUZdF+RToGnyNCbPHp2SGPdXV8ryrXvKDqjeByYXQfysa 7 | r7LndHsyF9u/6i6RSEwxoA4iRnwMf51A9z05JZTFFrMCqnwapspaCzRsxr/BzSAd 8 | /niqv3F/bGnzCollZ7BwkONS6H/WmBKNoFlJFtJyA+Ire7H3+GCEL9Cu4uUyoHdi 9 | lFHvhhY/31ZwSCZgUKRz1Nsn6FozvJhbFlaa/dqpqUpbkVWzK3jISyYc56z32NDv 10 | I9Th0CgQSv9qd8q3ns333RlGj2fTy5uGg1zOGofb9LLTEAqb16niUScr9OL+0sL3 11 | U15Va4zB/G/PwaLKGIwC6pKYu0p/Eq/UFkrZIR95NfUb49nZMug1of0yLn23W6WH 12 | Ah+Mcw1/AhkF6JoN24C/jqU7jxYDzwjHNKrf5/kYTg3p6RZRw9iN62j9G8AYjkeX 13 | R8qrmhV+9uxoKVob+2ORlzNkmHzabHgX3+4qudTg6u+ykVTyPq/tyrBtZ/vMXReI 14 | ogMVxQ+cZHHbtFQZsH3ewNUHwWoLfi15KQ0xFe3NwplolwFd+kMDiaHWNTPlKqYw 15 | nHbnBp4Kma9lcCA254KbyOhq0+I5g96/csgtjjounXZ8zPsqvtawsMnyF7tJbqgW 16 | 6jwyER9gkW2R+Kl8+jixY8oSYXM82Yyy/3en7pKQvadL6NwgZInQaryk5a6Crkkj 17 | +kO0UfpBnaBtdPFeTvxIUr9e3zflge3qrv0oqLPGcrt2BoQ5Y1rezrr4MR1AGP6O 18 | YokveE16RHRxeMTLVAxY5eKmYKPwLIc9ErQ/BkPTeU2LMQ/p+m15jgck04yFyeTV 19 | yMm6ZF80Ed1GRe8e8drZumAyWxLe8b1wbRE4YEXkUP7ipgyIz2OH3qBSGsxNhp+x 20 | RqR+9ONEgNMPhP+g4OCkpMfxsKjmQiI+i+xNHI7/2YuiNdxcX34pbs10dlle8XNx 21 | oa7Do4w+f34I57XnySf1hDBi91Pl7oX35kFk3QzLcmHUyjo1BYyoj4cnWikulhAA 22 | BcAldC+FvnolmEBrnHkvK6KklvgHTYmYIREO/7GE48Z5MwsYKowUuhaZ83YRaNZO 23 | g4gpwCUMa+h7yNwrKZVL9stFC6e+15PPlwIBBQ== 24 | -----END DH PARAMETERS----- 25 | -------------------------------------------------------------------------------- /dhutils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | encoDHer - a python package for symmetric encryption of email 4 | using the Diffie-Hellman shared secret key protocol. 5 | 6 | Copyright (C) 2013 by David R. Andersen 7 | 8 | This program is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program. If not, see . 20 | 21 | For more information, see https://github.com/rxcomm/encoDHer 22 | """ 23 | import sqlite3 24 | import sys 25 | import os 26 | import time 27 | import hashlib 28 | from getpass import getpass 29 | from binascii import hexlify 30 | from constants import * 31 | try: 32 | with open('/usr/local/lib/dhparams.pem'): 33 | try: 34 | from dh_m2crypto import * 35 | print 'Using M2Crypto/OpenSSL' 36 | except: 37 | from dh_pydhe import * 38 | print 'Using pyDHE' 39 | except IOError: 40 | print 'No dhparams.pem file found - using 6144-bit RFC 3526 prime' 41 | print 'with generator 2' 42 | from dh_legacy import * 43 | 44 | def makeKeys(): 45 | """ 46 | Create a DH keyset 47 | """ 48 | 49 | a = DiffieHellman() 50 | privkey = a.privateKey 51 | pubkey = a.publicKey 52 | return str(privkey), str(pubkey) 53 | 54 | def initDB(gpg,dbpassphrase): 55 | """ 56 | Initialize the database with the keys table format and 57 | a timestamp marking the beginning of time to search a.a.m 58 | """ 59 | 60 | timeStamp = time.time() 61 | 62 | try: 63 | with open(KEYS_DB): pass 64 | db = openDB(KEYS_DB,gpg,dbpassphrase) 65 | except IOError: 66 | db = sqlite3.connect(':memory:') 67 | 68 | with db: 69 | 70 | cur = db.cursor() 71 | cur.execute('CREATE TABLE IF NOT EXISTS keys (FromEmail TEXT, ToEmail TEXT, SecretKey TEXT, PublicKey TEXT, OtherPublicKey TEXT, TimeStamp FLOAT)') 72 | cur.execute('CREATE TABLE IF NOT EXISTS news (Id INTEGER PRIMARY KEY, LastReadTime FLOAT)') 73 | cur.execute('INSERT OR REPLACE INTO news (Id, LastReadTime) VALUES(?,?)', (1,timeStamp)) 74 | closeDB(db, KEYS_DB, gpg,dbpassphrase) 75 | os.chmod(KEYS_DB,0600) 76 | 77 | def rollback(days,gpg,dbpassphrase): 78 | """ 79 | Roll back the database news timestamp. 80 | The timestamp marks the beginning of time to search a.a.m 81 | """ 82 | 83 | try: 84 | timeStamp = time.time() - float(days)*86400. 85 | except ValueError: 86 | print 'Number of days to roll back must be a (real) number.' 87 | sys.exit(1) 88 | YYYYMMDD = time.strftime('%Y-%m-%d', time.gmtime(timeStamp)) 89 | HHMMSS = time.strftime('%H:%M:%S', time.gmtime(timeStamp)) 90 | 91 | print 'a.a.m last read time rolled back to '+YYYYMMDD+' at '+HHMMSS+' GMT' 92 | db = openDB(KEYS_DB,gpg,dbpassphrase) 93 | 94 | with db: 95 | 96 | cur = db.cursor() 97 | cur.execute('UPDATE news SET LastReadTime = ? WHERE Id = ?', (timeStamp,1)) 98 | closeDB(db, KEYS_DB, gpg,dbpassphrase) 99 | 100 | def insertKeys(fromEmail,toEmail,otherpubkey,gpg,dbpassphrase): 101 | """ 102 | Create a new keyset for the fromEmail -> toEmail route 103 | """ 104 | 105 | db = openDB(KEYS_DB, gpg,dbpassphrase) 106 | 107 | with db: 108 | 109 | timeStamp = time.time() 110 | privkey, mypubkey = makeKeys() 111 | cur = db.cursor() 112 | cur.execute('CREATE TABLE IF NOT EXISTS keys (FromEmail TEXT, ToEmail TEXT, SecretKey TEXT, PublicKey TEXT, OtherPublicKey TEXT, TimeStamp INT)') 113 | cur.execute('INSERT INTO keys VALUES(?,?,?,?,?,?)', (fromEmail,toEmail,privkey,mypubkey,otherpubkey,timeStamp)) 114 | 115 | cur.execute("SELECT * FROM keys") 116 | rows = cur.fetchall() 117 | print 'You have %d total routes' % len(rows) 118 | closeDB(db, KEYS_DB, gpg,dbpassphrase) 119 | 120 | def getKeys(fromEmail,toEmail,gpg,dbpassphrase): 121 | """ 122 | Get the key for the fromEmail -> toEmail route 123 | return privkey, mypubkey, otherpubkey 124 | """ 125 | 126 | db = openDB(KEYS_DB, gpg,dbpassphrase) 127 | 128 | with db: 129 | 130 | cur = db.cursor() 131 | cur.execute("SELECT * FROM keys") 132 | rows = cur.fetchall() 133 | for row in rows: 134 | if row[0] == fromEmail and row[1] == toEmail: 135 | return row[2], row[3], row[4] 136 | 137 | def listKeys(gpg,dbpassphrase): 138 | """ 139 | List routes for all keys in database 140 | """ 141 | 142 | db = openDB(KEYS_DB, gpg,dbpassphrase) 143 | 144 | with db: 145 | 146 | cur = db.cursor() 147 | cur.execute("SELECT * FROM keys") 148 | rows = cur.fetchall() 149 | for row in rows: 150 | print row[0]+' -> '+row[1] 151 | print 'You have %d total routes' % len(rows) 152 | 153 | def cloneKey(fromEmail,toEmail,newFromEmail,newToEmail,gpg,dbpassphrase): 154 | """ 155 | Clone key from route fromEmail -> toEmail to new route newFromEmail -> newToEmail 156 | """ 157 | 158 | db = openDB(KEYS_DB, gpg,dbpassphrase) 159 | 160 | with db: 161 | 162 | changed = False 163 | cur = db.cursor() 164 | cur.execute("SELECT * FROM keys") 165 | rows = cur.fetchall() 166 | for row in rows: 167 | if row[0] == fromEmail and row[1] == toEmail: 168 | changed = True 169 | cur.execute('INSERT INTO keys VALUES(?,?,?,?,?,?)', (newFromEmail,newToEmail,row[2],row[3],row[4],row[5])) 170 | if not changed: print 'Matching key not found, nothing changed.' 171 | closeDB(db, KEYS_DB, gpg,dbpassphrase) 172 | 173 | def changePubKey(fromEmail,toEmail,pubkey,gpg,dbpassphrase): 174 | """ 175 | Change the otherpubkey for the fromEmail -> toEmail route 176 | """ 177 | 178 | db = openDB(KEYS_DB, gpg,dbpassphrase) 179 | 180 | with db: 181 | 182 | changed = False 183 | cur = db.cursor() 184 | cur.execute("SELECT * FROM keys") 185 | rows = cur.fetchall() 186 | for row in rows: 187 | if row[0] == fromEmail and row[1] == toEmail: 188 | changed = True 189 | cur.execute('UPDATE keys SET OtherPublicKey = ? WHERE FromEmail = ? AND ToEmail = ?', (pubkey,row[0],row[1])) 190 | if not changed: print 'Matching key not found, nothing changed.' 191 | closeDB(db, KEYS_DB, gpg,dbpassphrase) 192 | 193 | def changeToEmail(fromEmail,oldToEmail,newToEmail,gpg,dbpassphrase): 194 | """ 195 | Change the toEmail address on the fromEmail -> oldToEmail route 196 | """ 197 | 198 | db = openDB(KEYS_DB, gpg,dbpassphrase) 199 | 200 | with db: 201 | 202 | changed = False 203 | cur = db.cursor() 204 | cur.execute("SELECT * FROM keys") 205 | rows = cur.fetchall() 206 | for row in rows: 207 | if row[0] == fromEmail and row[1] == oldToEmail: 208 | changed = True 209 | cur.execute('UPDATE keys SET ToEmail = ? WHERE FromEmail = ? AND ToEmail = ?', (newToEmail,row[0],row[1])) 210 | if not changed: print 'Matching key not found, nothing changed.' 211 | closeDB(db, KEYS_DB, gpg,dbpassphrase) 212 | 213 | def changeFromEmail(oldFromEmail,newFromEmail,toEmail,gpg,dbpassphrase): 214 | """ 215 | Change the fromEmail address on the oldFromEmail -> toEmail route 216 | """ 217 | 218 | db = openDB(KEYS_DB, gpg,dbpassphrase) 219 | 220 | with db: 221 | 222 | changed = False 223 | cur = db.cursor() 224 | cur.execute("SELECT * FROM keys") 225 | rows = cur.fetchall() 226 | for row in rows: 227 | if row[0] == oldFromEmail and row[1] == toEmail: 228 | changed = True 229 | cur.execute('UPDATE keys SET FromEmail = ? WHERE FromEmail = ? AND ToEmail = ?', (newFromEmail,row[0],row[1])) 230 | if not changed: print 'Matching key not found, nothing changed.' 231 | closeDB(db, KEYS_DB, gpg,dbpassphrase) 232 | 233 | def deleteKey(fromEmail,toEmail,gpg,dbpassphrase): 234 | """ 235 | Delete the fromEmail -> toEmail key from the database 236 | """ 237 | 238 | db = openDB(KEYS_DB, gpg,dbpassphrase) 239 | 240 | with db: 241 | 242 | cur = db.cursor() 243 | cur.execute("SELECT * FROM keys") 244 | rows = cur.fetchall() 245 | for row in rows: 246 | if row[0] == fromEmail and row[1] == toEmail: 247 | cur.execute('DELETE FROM keys WHERE FromEmail = ? AND ToEmail = ?', (fromEmail,toEmail)) 248 | closeDB(db, KEYS_DB, gpg,dbpassphrase) 249 | 250 | def genSharedSecret(fromEmail,toEmail,gpg,dbpassphrase): 251 | """ 252 | Generate the shared secret for the fromEmail -> toEmail route 253 | """ 254 | 255 | try: 256 | a = DiffieHellman() 257 | privkey, mypubkey, otherpubkey = getKeys(fromEmail,toEmail,gpg,dbpassphrase) 258 | a.genKey(long(privkey),long(otherpubkey)) 259 | return hexlify(a.key) 260 | except Exception: 261 | print 'Invalid public key: %s -> %s' % (fromEmail, toEmail) 262 | 263 | def mutateKey(fromEmail,toEmail,gpg,dbpassphrase): 264 | """ 265 | Change the privkey, mypubkey pair on the fromEmail -> toEmail route 266 | without modifying the otherpubkey. Also, create a mutatekey.asc file 267 | containing the new mypubkey encrypted with the old shared secret. 268 | This file can be securely transmitted to the receiver for decryption 269 | and importation to complete the key swap process. This makes the 270 | old shared secret disappear completely once the receiver has imported 271 | the new key. (ephemeral DH - perfect forward secrecy) 272 | """ 273 | 274 | db = openDB(KEYS_DB, gpg,dbpassphrase) 275 | 276 | with db: 277 | 278 | changed = False 279 | timeStamp = time.time() 280 | privkey, mypubkey = makeKeys() 281 | cur = db.cursor() 282 | cur.execute("SELECT * FROM keys") 283 | rows = cur.fetchall() 284 | for row in rows: 285 | if row[0] == fromEmail and row[1] == toEmail: 286 | changed = True 287 | cur.execute('UPDATE keys SET SecretKey = ? WHERE FromEmail = ? AND ToEmail = ?', (privkey,fromEmail,toEmail)) 288 | cur.execute('UPDATE keys SET PublicKey = ? WHERE FromEmail = ? AND ToEmail = ?', (mypubkey,fromEmail,toEmail)) 289 | if not changed: print 'Matching key not found, nothing changed.' 290 | closeDB(db,KEYS_DB,gpg,dbpassphrase) 291 | 292 | def getNewsTimestamp(gpg,dbpassphrase): 293 | """ 294 | Get the old timestamp for reading messages from a.a.m. 295 | Also, get the current time. 296 | """ 297 | curTime = time.time() 298 | db = openDB(KEYS_DB,gpg,dbpassphrase) 299 | 300 | with db: 301 | cur = db.cursor() 302 | cur.execute("SELECT * FROM news") 303 | rows = cur.fetchall() 304 | for row in rows: 305 | if row[0] == 1: timeStamp = int(row[1])-1 306 | closeDB(db,KEYS_DB,gpg,dbpassphrase) 307 | return timeStamp, curTime 308 | 309 | def setNewsTimestamp(curTimeStamp,gpg,dbpassphrase): 310 | """ 311 | Replace the old news timestamp with a new one for next time 312 | """ 313 | db = openDB(KEYS_DB,gpg,dbpassphrase) 314 | 315 | with db: 316 | cur = db.cursor() 317 | cur.execute("SELECT * FROM news") 318 | rows = cur.fetchall() 319 | for row in rows: 320 | if row[0] == 1: 321 | cur.execute('UPDATE news SET LastReadTime = ? WHERE Id = 1', (curTimeStamp,)) 322 | closeDB(db,KEYS_DB,gpg,dbpassphrase) 323 | 324 | def getListOfKeys(gpg,dbpassphrase): 325 | """ 326 | Get the route and shared secret for all keys in the database. This 327 | will be used to query a.a.m for any messages associated with our keys. 328 | """ 329 | 330 | db = openDB(KEYS_DB, gpg,dbpassphrase) 331 | listOfKeys = [] 332 | 333 | with db: 334 | cur = db.cursor() 335 | cur.execute("SELECT * FROM keys") 336 | rows = cur.fetchall() 337 | for row in rows: 338 | sSecret = genSharedSecret(row[0],row[1],gpg,dbpassphrase) 339 | if sSecret: 340 | listOfKeys.append((row[0],row[1],sSecret)) 341 | return listOfKeys 342 | 343 | def changeDBKey(keys_db,gpg,dbpassphrase): 344 | db = openDB(keys_db,gpg,dbpassphrase) 345 | passphrase1='1' 346 | passphrase2='2' 347 | while passphrase1 != passphrase2: 348 | passphrase1 = getpass('New passphrase for keys.db database: ') 349 | passphrase2 = getpass('Retype: ') 350 | if passphrase1 != passphrase2: 351 | print 'Passphrase did not match.' 352 | closeDB(db,keys_db,gpg,passphrase1) 353 | 354 | def openDB(keys_db,gpg,dbpassphrase): 355 | 356 | db = sqlite3.connect(':memory:') 357 | 358 | with open(keys_db, 'rb') as f: 359 | sql = gpg.decrypt_file(f, passphrase=dbpassphrase) 360 | if not sql: 361 | print 'Bad passphrase!' 362 | sys.exit(1) 363 | db.cursor().executescript(str(sql)) 364 | return db 365 | 366 | def closeDB(db,keys_db,gpg,dbpassphrase): 367 | 368 | sql = '' 369 | for item in db.iterdump(): 370 | sql = sql+item+'\n' 371 | crypt_sql = gpg.encrypt(sql, recipients=None, symmetric=CIPHER, 372 | always_trust=True, passphrase=dbpassphrase) 373 | 374 | with open(keys_db, 'wb') as f: 375 | f.write(str(crypt_sql)) 376 | 377 | if __name__=="__main__": 378 | """ 379 | Run an example key insertion 380 | """ 381 | makeKeys() 382 | insertKeys(sys.argv[1], sys.argv[2], sys.argv[3]) 383 | sharedSecret = genSharedSecret(sys.argv[1], sys.argv[2]) 384 | print sharedSecret 385 | print len(sharedSecret) 386 | 387 | -------------------------------------------------------------------------------- /encodher: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rxcomm/encoDHer/c191418ac8f0d2eaeeb896834d7ea410875bfc0e/encodher -------------------------------------------------------------------------------- /encodher.keys: -------------------------------------------------------------------------------- 1 | -----BEGIN PGP SIGNED MESSAGE----- 2 | Hash: SHA256 3 | 4 | DH Public Key: 5 | 00000000000000000000000000000000000173595775228889 6 | 01623669194514162571695208182164083733600917194040 7 | 22755263963530895066142518965288118088339065825287 8 | 42981931949889118174909552130942942832158357700241 9 | 24410166222232538832693686336639616897082887698791 10 | 27822020855718956267560064629532614547334513754868 11 | 09851205801006159621734420295676525232671627663352 12 | 58265359910775588648127416330318973736648692153296 13 | 06208790409729056837272460933159501775584398965050 14 | 09632547809778930528650901102761192938450709136144 15 | 53427968167996311484183729248159804705159185407514 16 | 41974274557864421895117959651574503566482900259877 17 | 47103983105621813451232175960890924404510989190868 18 | 13557325884853575910060109288689177104248320084980 19 | 38633005904163171723624973657253760411010995094502 20 | 30297929009835218089674888956347922595775563493217 21 | 77881880108274850725872352786964912065407009304093 22 | 43678698121154792517982134530912653758211710444388 23 | 69464793649274500794632091040987039829143528469634 24 | 76227582156580956758671329670722294345599984483652 25 | 81991537624495075136857333258377995465903365231107 26 | 76898884095603350772138619095043093700900206273263 27 | 70190799565313193245649880265615714896126201873300 28 | 81109500322397153096736842302192841954076663533046 29 | 05202057345560722786419396264696474737575812590712 30 | 89417140669018704821474681471869897297601182270435 31 | 68433526193460681062060777409574904671572123056394 32 | 37918183683318281483397410418824984192690443234126 33 | 59548647469581006496382144945957930181066316756818 34 | 09154792061569177717888253028773194728133924436349 35 | 45986435192015549531823722122203503178147976830102 36 | 95191149986546617391972521966998239320346503812324 37 | 80327584066147497823734124431240091444910982024801 38 | 89954714415995055983289123289225548650343111405729 39 | 40814586769664436398842170056338054205062959692444 40 | 74628102170034454531282701930619392024179672774927 41 | 64437623835264671203621924173075544734172344901700 42 | 97585560179707572807242134971134998727386202493444 43 | 93762977615704493412849938451905257109096969823328 44 | 90318921183547425249197648118203598893473334326368 45 | 01630345099587878589936834641347027191249130910688 46 | 63417330644497957529408827941785271949732357259590 47 | 35897064599971830539926795738487798104740356243197 48 | 57630627284923055567200159253333227693546133355161 49 | 00273782965256315807358530798384206151226493138587 50 | 68318427572140387819229203304553326652505440384184 51 | 48724879976755526302179479463261158859424139133290 52 | 18201578850173644456080199324174837349046237301182 53 | 04928372737538327376561881299468290064492954881784 54 | 60049344974817382023238629245603506367041302241073 55 | 56 | -----BEGIN PGP SIGNATURE----- 57 | Version: GnuPG v2.0.19 (GNU/Linux) 58 | 59 | iQQcBAEBCAAGBQJSY7eAAAoJEPg2RfKON9IogPgf/0z2ig7bbtztaimgHVDVdVLl 60 | V0f3HjHx+dzHzpe90jcjbiSDMXprKNldi4s/6dL+nNqpsQ0XTIBlkhiiVYktcPF+ 61 | A3wdBix6RXfFRuvU0tK+xFFRvCK7TQ0NlOa4/SDhSrbQ1QGyJ/GNGJ83BdTqHabl 62 | 07A/gKBBA211s5wK7B1/brhxd8kaD7Xz/w06cVZPbfABJe+m4OR4vBUFZA+oi1aT 63 | BcoPO3XCt0pfBKMfHvmZe43I63g+iuF/DH94Jz6xW8PHCP2OWxMmyBQj7by2egsZ 64 | sLXCNPcuS4qIzZ7o6brWHU6Mepwn1UwvFFR6XSlhZY5FFAD/kSOpLajn5R9P6iD5 65 | yTx10W08tsw+Fd4gFuBHwtmjhNtWlXQ6J4ON8MSN6ukwiGkC1mjJQ4HjcZ2NiJkg 66 | Wh+o/c0cL3CW8FBh0Sg4jJKSC6jwrMxmPbKLdUFS41gsLSGucwoR1w2uOH3QltT0 67 | /yIyfWHBq9jhYTFkPtppr89iaSvekUT8t63UABs0twyJZC7NimWyTNvELlX+bSFp 68 | TCRdfqigQGWxqT1EHwu62hUE70NH1YNCxRIf/CWKW2vfhroVKKv7QqDcamneYDjs 69 | GlbdQmP4OEwEZpjE5CIi0lIHszdNjapd1QbMMNWwUNr/5JQxrVZDGsVR16jPJbHE 70 | 37UHWugwuB0ftwWxZzD6xtZW1WjL4iuPAcjyn7nURlNfkGLmrFAFbnc51vXAKQPO 71 | +5wrMp/VH8CdaNhvTRROcaNV6PIBYBAhgFq7fESObmauZZKsihwNo1J/dqIWW2oV 72 | L0S/wYG8rWRjVyDZpJztxdRYhjFNO7XsUFIIhqdIA8PLhBWoRZNEgCdSeWJ0u/lw 73 | u/2kQuhZKoxz9po4LoPFBsy8RRthb+JNM7q4QKImLgZOf7NLslH5UiVSGgTr9doK 74 | 2S+b/uRPGuj8ln/IMjSEvsIefUMze5rb7weiZuatVUNBT0F6x+rdAehm0e4VvRvt 75 | IO+atG+bZiNVSFigXOKV1R9hhWUtUvbrgkt6ZMzUalxsDZsMqXsfjE+o8FMChyJV 76 | B6F/GYKprvbBG0bENqE6a/YdqQYo7oijABX5o03xoJtS69ff+0wZVWl2AkCPanc2 77 | MsLLCQZwBTaRC0EjFivqMYGuapCbgO6r+gSFd/1zqah9zBNkHcTl05qS44j9c7R+ 78 | GTvH7N8x4KnE+RsjZYTkXqoje5J6nuc4p9LIJGVXR9CkadYPpsmwecbOSULze4BU 79 | 573tUyV1neNvIpk69Z/cwJTISm97YYQWiupymH1NKU+ANElG/dhjWxV9EeIjCzq9 80 | byEiwfW68EaXOb6xmC7W6mg7X679q/FjC44jFkieC5/KkwQGwKPVf7bk8ouTFpg= 81 | =MJNK 82 | -----END PGP SIGNATURE----- 83 | 84 | 85 | -----BEGIN PGP PUBLIC KEY BLOCK----- 86 | Version: GnuPG v1.4.12 (GNU/Linux) 87 | 88 | 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 242 | AKecmSBTdkg= 243 | =4EXU 244 | -----END PGP PUBLIC KEY BLOCK----- 245 | -------------------------------------------------------------------------------- /encodher.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | encoDHer - a python package for symmetric encryption of email 4 | using the Diffie-Hellman shared secret key protocol. 5 | 6 | Copyright (C) 2013 by David R. Andersen 7 | 8 | This program is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program. If not, see . 20 | 21 | For more information, see https://github.com/rxcomm/encoDHer 22 | """ 23 | print 'encoDHer version 0.3' 24 | 25 | import os 26 | import sys 27 | import hsub 28 | import gnupg 29 | import dhutils 30 | import re 31 | import time 32 | import string 33 | import random 34 | import email 35 | import nntplib 36 | from getpass import getpass 37 | from constants import * 38 | 39 | gpg = gnupg.GPG(gnupghome=HOME, gpgbinary=GPGBINARY, keyring=KEYRING, 40 | secret_keyring=SECRET_KEYRING, options=['--throw-keyids', 41 | '--personal-digest-preferences=sha256','--s2k-digest-algo=sha256']) 42 | gpg.encoding = 'utf-8' 43 | 44 | try: 45 | opt = sys.argv[1] 46 | except (IndexError): 47 | print 'Options:' 48 | print ' --init, -i: initialize keys.db database' 49 | print ' --import, -m: import signed public key' 50 | print ' --mutate-key, -a: mutate DH secret key for PFS' 51 | print ' --sign-pub, -s: sign your own public key' 52 | print ' --change-toemail, -t: change toEmail on key' 53 | print ' --change-fromemail, -f: change fromEmail on key' 54 | print ' --change-pubkey, -p: change public key for fromEmail -> toEmail' 55 | print ' --encode-email, -e: symmetrically encode a file for fromEmail -> toEmail' 56 | print ' --decode-email, -d: symmetrically decode a file for fromEmail -> toEmail' 57 | print ' --list-routes, -l: list all routes in database' 58 | print ' --gen-secret, -c: generate shared secret for fromEmail -> toEmail' 59 | print ' --gen-key, -n: generate a new key for fromEmail -> toEmail' 60 | print ' --get-key, -g: get key for fromEmail -> toEmail from database' 61 | print ' --fetch-aam, -h: fetch messages from alt.anonymous.messages newsgroup' 62 | print ' --clone-key, -y: clone key from one route to another' 63 | print ' --rollback, -b: roll back the a.a.m last read timestamp' 64 | print ' --change-dbkey, -k: change keys.db encryption key' 65 | sys.exit(0) 66 | 67 | try: 68 | with open(KEYS_DB): 69 | dbpassphrase = getpass('Passphrase to decrypt keys.db: ') 70 | except IOError: 71 | pass 72 | 73 | def init(): 74 | 75 | try: 76 | dhutils.initDB(gpg,dbpassphrase) 77 | print 'Database already exists. Only the news timestamp was updated.' 78 | except NameError: 79 | dhutils.initDB(gpg,'password') 80 | print 'New keys.db database created, password is: password' 81 | print 'Change it immediately using: '+sys.argv[0]+' --change-dbkey' 82 | 83 | def rollback(): 84 | 85 | try: 86 | days = sys.argv[2] 87 | except (IndexError): 88 | print 'You need to supply the number of days to roll back nntp!' 89 | print 'Ex: '+sys.argv[0]+' --rollback <# of days>' 90 | sys.exit(1) 91 | 92 | try: 93 | with open(KEYS_DB): pass 94 | except IOError: 95 | print 'No keys database (keys.db)' 96 | print 'initialize the database with '+sys.argv[0]+' --init' 97 | sys.exit(1) 98 | 99 | dhutils.rollback(days,gpg,dbpassphrase) 100 | 101 | def importKey(): 102 | 103 | try: 104 | file = sys.argv[2] 105 | except (IndexError): 106 | print 'You need to supply a source key file!' 107 | print 'Ex: '+sys.argv[0]+' --import ' 108 | sys.exit(1) 109 | 110 | try: 111 | with open(KEYS_DB): pass 112 | except IOError: 113 | print 'No keys database (keys.db)' 114 | print 'initialize the database with '+sys.argv[0]+' --init' 115 | sys.exit(1) 116 | 117 | print 'Importing new DH public key to database' 118 | 119 | with open (file, "r") as f: 120 | signed_data=f.read() 121 | 122 | verified = gpg.verify(str(signed_data)) 123 | if verified.username is not None: 124 | print('Verified signed by: %s' % verified.username) 125 | print('at trust level: %s' % verified.trust_text) 126 | else: 127 | print 'Signature not valid' 128 | sys.exit(0) 129 | 130 | data = signed_data.split('\n') 131 | pubkey = '' 132 | for line in data: 133 | if len(line) == 50: 134 | pubkey += line 135 | while pubkey[:1] == '0': 136 | pubkey = pubkey[1:] 137 | 138 | try: 139 | toEmail = verified.username.split('<')[1].split('>')[0] # regular email 140 | except IndexError: 141 | toEmail = verified.username # only a name - probably anonymous 142 | print 'To Email is: %s' % toEmail.lower() 143 | fromEmail = raw_input('Enter From Email: ') 144 | 145 | keys = dhutils.getKeys(fromEmail.lower(),toEmail.lower(),gpg,dbpassphrase) 146 | 147 | if not keys: 148 | print 'key doesn\'t exist for the '+fromEmail+' -> '+toEmail+' route' 149 | print 'create new key?' 150 | ans = raw_input('y/N: ') 151 | if ans == 'y': 152 | dhutils.insertKeys(fromEmail.lower(),toEmail.lower(),pubkey.lower(),gpg,dbpassphrase) 153 | else: 154 | print 'key exists for the '+fromEmail.lower()+' -> '+toEmail.lower()+' route' 155 | print 'change key?' 156 | ans = raw_input('y/N: ') 157 | if ans == 'y': 158 | dhutils.changePubKey(fromEmail.lower(),toEmail.lower(),pubkey.lower(),gpg,dbpassphrase) 159 | 160 | 161 | def sign_pub(): 162 | 163 | try: 164 | fromEmail = sys.argv[2] 165 | toEmail = sys.argv[3] 166 | 167 | except (IndexError): 168 | print 'You need to supply source and target email addresses!' 169 | print 'Ex: '+sys.argv[0]+' --sign-pub ' 170 | sys.exit(1) 171 | 172 | try: 173 | with open(KEYS_DB): pass 174 | except IOError: 175 | print 'No keys database (keys.db)' 176 | print 'initialize the database with '+sys.argv[0]+' --init' 177 | sys.exit(1) 178 | 179 | privkey, mypubkey, otherpubkey = dhutils.getKeys(fromEmail,toEmail,gpg,dbpassphrase) 180 | while len(mypubkey) < 50*50: 181 | mypubkey = '0'+mypubkey 182 | brokenkey = [mypubkey[i:i+50] for i in range(0, len(mypubkey), 50)] 183 | new_mypubkey = '' 184 | for line in brokenkey: 185 | new_mypubkey += line+'\n' 186 | 187 | passphrase = getpass('Signing key ('+fromEmail+') password: ') 188 | signed_data = gpg.sign('DH Public Key:\n'+new_mypubkey+'\n', passphrase=passphrase, 189 | keyid=fromEmail) 190 | print '' 191 | print str(signed_data) 192 | 193 | verified = gpg.verify(str(signed_data)) 194 | if verified.username is not None: 195 | print('Verified signed by: %s' % verified.username) 196 | print('at trust level: %s' % verified.trust_text) 197 | else: 198 | print 'Sigature not verified' 199 | 200 | def change_toEmail(): 201 | try: 202 | fromEmail = sys.argv[2] 203 | oldToEmail = sys.argv[3] 204 | newToEmail = sys.argv[4] 205 | 206 | except (IndexError): 207 | print 'You need to supply fromEmail, oldToEmail, and newToEmail addresses' 208 | print 'Ex: '+sys.argv[0]+' --change-toemail ' 209 | sys.exit(1) 210 | 211 | try: 212 | with open(KEYS_DB): pass 213 | except IOError: 214 | print 'No keys database (keys.db)' 215 | print 'initialize the database with '+sys.argv[0]+' --init' 216 | sys.exit(1) 217 | 218 | keys = dhutils.changeToEmail(fromEmail,oldToEmail,newToEmail,gpg,dbpassphrase) 219 | 220 | 221 | def change_fromEmail(): 222 | try: 223 | oldFromEmail = sys.argv[2] 224 | newFromEmail = sys.argv[3] 225 | toEmail = sys.argv[4] 226 | 227 | except (IndexError): 228 | print 'You need to supply oldFromEmail, newFromEmail, and toEmail addresses' 229 | print 'Ex: '+sys.argv[0]+' --change-fromemail ' 230 | sys.exit(1) 231 | 232 | try: 233 | with open(KEYS_DB): pass 234 | except IOError: 235 | print 'No keys database (keys.db)' 236 | print 'initialize the database with '+sys.argv[0]+' --init' 237 | sys.exit(1) 238 | 239 | keys = dhutils.changeFromEmail(oldFromEmail,newFromEmail,toEmail,gpg,dbpassphrase) 240 | 241 | def change_pub(): 242 | try: 243 | fromEmail = sys.argv[2] 244 | toEmail = sys.argv[3] 245 | pubkey = sys.argv[4] 246 | 247 | except (IndexError): 248 | print 'You need to supply fromEmail, toEmail, and public key!' 249 | print 'Ex: '+sys.argv[0]+' --change-pub ' 250 | sys.exit(1) 251 | 252 | try: 253 | with open(KEYS_DB): pass 254 | except IOError: 255 | print 'No keys database (keys.db)' 256 | print 'initialize the database with '+sys.argv[0]+' --init' 257 | sys.exit(1) 258 | 259 | keys = dhutils.changePubKey(fromEmail,toEmail,pubkey,gpg,dbpassphrase) 260 | 261 | def hs(): 262 | try: 263 | file_name = sys.argv[2] 264 | fromEmail = sys.argv[3] 265 | toEmail = sys.argv[4] 266 | except (IndexError): 267 | print 'You need to supply a target file to be encrypted, fromEmail, and toEmail!' 268 | print 'Ex: '+sys.argv[0]+' --encode-email ' 269 | sys.exit(1) 270 | 271 | try: 272 | with open(KEYS_DB): pass 273 | except IOError: 274 | print 'No keys database (keys.db)' 275 | print 'initialize the database with '+sys.argv[0]+' --init' 276 | sys.exit(1) 277 | 278 | ans = raw_input('Do you want to send this message anonymously? (y/N)') 279 | if ans == 'y': 280 | sendAnon = True 281 | else: 282 | sendAnon = False 283 | 284 | passphrase = dhutils.genSharedSecret(fromEmail,toEmail,gpg,dbpassphrase) 285 | 286 | with open(file_name, "rb") as f: 287 | msg = gpg.encrypt_file(f, recipients=None, symmetric=CIPHER, 288 | always_trust=True, passphrase=passphrase) 289 | if sendAnon: 290 | iv = hsub.cryptorandom() 291 | hsubject = hsub.hash(passphrase[:16]) # first 64 bits to calc hsub 292 | 293 | # A note here about using part of the passphrase as the hsub password. 294 | # We use 64 bits (16 ascii bytes hex encoded = 8 bytes binary entropy) 295 | # for the hsub passphrase. Assuming those 64 bits are completely 296 | # compromised (unlikekly, as it would require a rainbow table with 297 | # 3.4 x 10^38 entries) that leaves us with 192 bits of aes key entropy. 298 | # Still plenty strong. 299 | 300 | with open(file_name+'.asc', "w") as f: 301 | 302 | if sendAnon: 303 | f.write('To: mail2news@dizum.com,mail2news@m2n.mixmin.net\n') 304 | f.write('Subject: %s\n' % hsubject) 305 | f.write('Newsgroups: alt.anonymous.messages\n') 306 | f.write('X-No-Archive: Yes\n') 307 | f.write('\n') 308 | f.write(re.sub('\nV.*$', '', str(msg), count=1, flags=re.MULTILINE)) 309 | 310 | print 'The encrypted file is '+file_name+'.asc' 311 | print 'Passphrase: %s' % passphrase 312 | 313 | 314 | def hsd(): 315 | # Try getting the route info from the X-encoDHer-Route header. 316 | # If the header doesn't exist, pass and parse the normal way. 317 | try: 318 | file_name = sys.argv[2] 319 | with open(file_name, 'r') as f: 320 | header = f.readline().split(': ') 321 | if header[0] == 'X-encoDHer-Route': 322 | route = header[1].strip().split('->') 323 | passphrase = dhutils.genSharedSecret(route[1],route[0],gpg,dbpassphrase) 324 | msg = gpg.decrypt_file(f, passphrase=passphrase, always_trust=True) 325 | if not msg: 326 | print 'Bad shared secret!' 327 | sys.exit(1) 328 | print '\n'+unicode(msg) 329 | sys.exit(0) 330 | else: 331 | pass 332 | except IndexError: 333 | pass 334 | 335 | try: 336 | file_name = sys.argv[2] 337 | fromEmail = sys.argv[3] 338 | toEmail = sys.argv[4] 339 | except (IndexError): 340 | print 'You need to supply a target file to be decrypted, and optionally route information!' 341 | print 'Ex: '+sys.argv[0]+' --decode-email [ ]' 342 | sys.exit(1) 343 | 344 | try: 345 | with open(KEYS_DB): pass 346 | except IOError: 347 | print 'No keys database (keys.db)' 348 | print 'initialize the database with '+sys.argv[0]+' --init' 349 | sys.exit(1) 350 | 351 | base, ext = os.path.splitext(file_name) 352 | with open(file_name, "r") as f: 353 | passphrase = dhutils.genSharedSecret(toEmail,fromEmail,gpg,dbpassphrase) 354 | msg = gpg.decrypt_file(f, passphrase=passphrase, always_trust=True) 355 | if not msg: 356 | print 'Bad shared secret!' 357 | sys.exit(1) 358 | print '\n'+unicode(msg) 359 | 360 | 361 | def list_keys(): 362 | try: 363 | with open(KEYS_DB): pass 364 | except IOError: 365 | print 'No keys database (keys.db)' 366 | print 'initialize the database with '+sys.argv[0]+' --init' 367 | sys.exit(1) 368 | 369 | print 'Listing of all routes in database:' 370 | dhutils.listKeys(gpg,dbpassphrase) 371 | 372 | def secret(): 373 | try: 374 | fromEmail = sys.argv[2] 375 | toEmail = sys.argv[3] 376 | except (IndexError): 377 | print 'You need to supply a fromEmail, and toEmail!' 378 | print 'Ex: '+sys.argv[0]+' --gen-secret ' 379 | sys.exit(1) 380 | 381 | try: 382 | with open(KEYS_DB): pass 383 | except IOError: 384 | print 'No keys database (keys.db)' 385 | print 'initialize the database with '+sys.argv[0]+' --init' 386 | sys.exit(1) 387 | 388 | sharedSecret = dhutils.genSharedSecret(fromEmail,toEmail,gpg,dbpassphrase) 389 | print 'Secret: ',sharedSecret 390 | 391 | def gen(): 392 | try: 393 | fromEmail = sys.argv[2] 394 | toEmail = sys.argv[3] 395 | except (IndexError): 396 | print 'You need to supply a fromEmail, and toEmail!' 397 | print 'Ex: '+sys.argv[0]+' --gen-key ' 398 | sys.exit(1) 399 | 400 | try: 401 | with open(KEYS_DB): pass 402 | except IOError: 403 | print 'No keys database (keys.db)' 404 | print 'initialize the database with '+sys.argv[0]+' --init' 405 | sys.exit(1) 406 | 407 | dhutils.makeKeys() 408 | dhutils.insertKeys(fromEmail,toEmail,1,gpg,dbpassphrase) 409 | 410 | 411 | def get(): 412 | try: 413 | fromEmail = sys.argv[2] 414 | toEmail = sys.argv[3] 415 | except (IndexError): 416 | print 'You need to supply a fromEmail, and toEmail!' 417 | print 'Ex: '+sys.argv[0]+' --get-key ' 418 | sys.exit(1) 419 | 420 | try: 421 | with open(KEYS_DB): pass 422 | except IOError: 423 | print 'No keys database (keys.db)' 424 | print 'initialize the database with '+sys.argv[0]+' --init' 425 | sys.exit(1) 426 | 427 | privkey, mypubkey, otherpubkey = dhutils.getKeys(fromEmail,toEmail,gpg,dbpassphrase) 428 | print fromEmail+' Public Key: ', mypubkey 429 | print toEmail+' Public Key: ', otherpubkey 430 | 431 | def delete(): 432 | try: 433 | fromEmail = sys.argv[2] 434 | toEmail = sys.argv[3] 435 | except (IndexError): 436 | print 'You need to supply a fromEmail, and toEmail!' 437 | print 'Ex: '+sys.argv[0]+' --delete-key ' 438 | sys.exit(1) 439 | 440 | try: 441 | with open(KEYS_DB): pass 442 | except IOError: 443 | print 'No keys database (keys.db)' 444 | print 'initialize the database with '+sys.argv[0]+' --init' 445 | sys.exit(1) 446 | 447 | dhutils.deleteKey(fromEmail,toEmail,gpg,dbpassphrase) 448 | 449 | def mutate(): 450 | try: 451 | fromEmail = sys.argv[2] 452 | toEmail = sys.argv[3] 453 | except (IndexError): 454 | print 'You need to supply a fromEmail, and toEmail!' 455 | print 'Ex: '+sys.argv[0]+' --mutate-key ' 456 | sys.exit(1) 457 | 458 | try: 459 | with open(KEYS_DB): pass 460 | except IOError: 461 | print 'No keys database (keys.db)' 462 | print 'initialize the database with '+sys.argv[0]+' --init' 463 | sys.exit(1) 464 | 465 | oldpassphrase = dhutils.genSharedSecret(fromEmail,toEmail,gpg,dbpassphrase) 466 | dhutils.mutateKey(fromEmail,toEmail,gpg,dbpassphrase) 467 | 468 | privkey, mypubkey, otherpubkey = dhutils.getKeys(fromEmail,toEmail,gpg,dbpassphrase) 469 | while len(mypubkey) < 50*50: 470 | mypubkey = '0'+mypubkey 471 | brokenkey = [mypubkey[i:i+50] for i in range(0, len(mypubkey), 50)] 472 | new_mypubkey = '' 473 | for line in brokenkey: 474 | new_mypubkey += line+'\n' 475 | 476 | passphrase = getpass('Signing key ('+fromEmail+') password: ') 477 | signed_data = gpg.sign('DH Public Key:\n'+new_mypubkey+'\n', passphrase=passphrase, 478 | keyid=fromEmail) 479 | print '' 480 | print str(signed_data) 481 | 482 | ans = raw_input('Do you want to send this key anonymously? (y/N)') 483 | if ans == 'y': 484 | sendAnon = True 485 | else: 486 | sendAnon = False 487 | 488 | msg = gpg.encrypt(str(signed_data), recipients=None, symmetric=CIPHER, 489 | always_trust=True, passphrase=oldpassphrase) 490 | if sendAnon: 491 | iv = hsub.cryptorandom() 492 | hsubject = hsub.hash(oldpassphrase) 493 | 494 | with open('mutatedkey.asc', "w") as f: 495 | 496 | if sendAnon: 497 | f.write('To: mail2news@dizum.com,mail2news@m2n.mixmin.net\n') 498 | f.write('Subject: %s\n' % hsubject) 499 | f.write('Newsgroups: alt.anonymous.messages\n') 500 | f.write('X-No-Archive: Yes\n') 501 | f.write('\n') 502 | f.write(re.sub('\nV.*$', '', str(msg), count=1, flags=re.MULTILINE)) 503 | print 'New key encrypted with old DH shared secret is in "mutatedkey.asc"' 504 | print 'Get unencrypted, signed copy of new key with '+sys.argv[0]+' --sign-pub '+fromEmail+' '+toEmail 505 | 506 | def aam(): 507 | GROUP = "alt.anonymous.messages" 508 | 509 | timeStamp, curTimeStamp = dhutils.getNewsTimestamp(gpg,dbpassphrase) 510 | YYMMDD = time.strftime('%y%m%d', time.gmtime(timeStamp)) 511 | HHMMSS = time.strftime('%H%M%S', time.gmtime(timeStamp)) 512 | 513 | passphrases = dhutils.getListOfKeys(gpg,dbpassphrase) 514 | 515 | # connect to server 516 | server = nntplib.NNTP(NEWSSERVER,NEWSPORT) 517 | 518 | server.newnews(GROUP, YYMMDD, HHMMSS, '.newnews') 519 | 520 | with open ('.newnews', "r") as f: 521 | ids=f.read().splitlines() 522 | 523 | for msg_id in ids: 524 | try: 525 | resp, number, message_id, text = server.article(msg_id) 526 | except (nntplib.error_temp, nntplib.error_perm): 527 | pass # no such message (maybe it was deleted?) 528 | text = string.join(text, "\n") 529 | 530 | message = email.message_from_string(text) 531 | match = False 532 | 533 | for passphrase in passphrases: 534 | for label, item in message.items(): 535 | if label == 'Subject': 536 | match = hsub.check(passphrase[2][:16],item) 537 | #if match, decrypt 538 | if match: 539 | print '\nMail for: '+passphrase[0]+' from '+passphrase[1] 540 | msg = gpg.decrypt(message.as_string(), passphrase=passphrase[2], 541 | always_trust=True) 542 | if not msg: 543 | print 'Bad shared secret!' 544 | sys.exit(1) 545 | print '\n'+unicode(msg) 546 | with open('message_'+message_id[1:6]+'.txt', "w") as f: 547 | f.write('X-encoDHer-Route: '+passphrase[1]+'->'+passphrase[0]+'\n') 548 | f.write(message.as_string()+'\n') 549 | print 'encrypted message stored in message_'+message_id[1:6]+'.txt' 550 | 551 | dhutils.setNewsTimestamp(curTimeStamp,gpg,dbpassphrase) 552 | print 'End of messages.' 553 | 554 | def clone(): 555 | try: 556 | fromEmail = sys.argv[2] 557 | toEmail = sys.argv[3] 558 | newFromEmail = sys.argv[4] 559 | newToEmail = sys.argv[5] 560 | except (IndexError): 561 | print 'You need to supply a fromEmail, and toEmail!' 562 | print 'Ex: '+sys.argv[0]+' --clone-key ' 563 | sys.exit(1) 564 | 565 | try: 566 | with open(KEYS_DB): pass 567 | except IOError: 568 | print 'No keys database (keys.db)' 569 | print 'initialize the database with '+sys.argv[0]+' --init' 570 | sys.exit(1) 571 | 572 | dhutils.cloneKey(fromEmail,toEmail,newFromEmail,newToEmail,gpg,dbpassphrase) 573 | 574 | def changeDBKey(): 575 | 576 | dhutils.changeDBKey(KEYS_DB,gpg,dbpassphrase) 577 | print 'Key changed' 578 | 579 | def errhandler(): 580 | print 'Invalid option, try again!' 581 | print 'Execute '+sys.argv[0]+' to get a list of options.' 582 | sys.exit(1) 583 | 584 | options = { '--init' : init, 585 | '-i' : init, 586 | '--import' : importKey, 587 | '-m' : importKey, 588 | '--sign-pub' : sign_pub, 589 | '-s' : sign_pub, 590 | '--change-toemail' : change_toEmail, 591 | '-t' : change_toEmail, 592 | '--change-fromemail' : change_fromEmail, 593 | '-f' : change_fromEmail, 594 | '--change-pubkey' : change_pub, 595 | '-p' : change_pub, 596 | '--encode-email' : hs, 597 | '-e' : hs, 598 | '--decode-email' : hsd, 599 | '-d' : hsd, 600 | '--list-routes' : list_keys, 601 | '-l' : list_keys, 602 | '--gen-secret' : secret, 603 | '-c' : secret, 604 | '--gen-key' : gen, 605 | '-n' : gen, 606 | '--get-key' : get, 607 | '-g' : get, 608 | '--delete-key' : delete, 609 | '-x' : delete, 610 | '--mutate-key' : mutate, 611 | '-a' : mutate, 612 | '--fetch-aam' : aam, 613 | '-h' : aam, 614 | '--clone-key' : clone, 615 | '-y' : clone, 616 | '--rollback' : rollback, 617 | '-b' : rollback, 618 | '--change-dbkey' : changeDBKey, 619 | '-k' : changeDBKey 620 | } 621 | 622 | def main(): 623 | options.get(sys.argv[1],errhandler)() 624 | 625 | if __name__ == '__main__': 626 | main() 627 | -------------------------------------------------------------------------------- /hsub.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # vim: tabstop=4 expandtab shiftwidth=4 autoindent 4 | # 5 | # Copyright (C) 2010 Steve Crook 6 | # 7 | # This program is free software; you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by the 9 | # Free Software Foundation; either version 2, or (at your option) any later 10 | # version. 11 | # 12 | # This program is distributed in the hope that it will be useful, but 13 | # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY 14 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 | # for more details. 16 | 17 | from hashlib import sha256 18 | from os import urandom 19 | 20 | HSUBLEN = 48 21 | 22 | def hash(text, iv = None, hsublen = HSUBLEN): 23 | """Create an hSub (Hashed Subject). This is constructed as: 24 | -------------------------------------- 25 | | 64bit iv | 256bit SHA2 'iv + text' | 26 | --------------------------------------""" 27 | # Generate a 64bit random IV if none is provided. 28 | if iv is None: iv = cryptorandom() 29 | # Concatenate our IV with a SHA256 hash of text + IV. 30 | hsub = iv + sha256(iv + text).digest() 31 | return hsub.encode('hex')[:hsublen] 32 | 33 | def check(text, hsub): 34 | """Create an hSub using a known iv, (stripped from a passed hSub). If 35 | the supplied and generated hSub's collide, the message is probably for 36 | us.""" 37 | # We are prepared to check variable length hsubs within boundaries. 38 | # The low bound is the current Type-I esub length. The high bound 39 | # is the 256 bits within SHA2-256. 40 | hsublen = len(hsub) 41 | # 48 digits = 192 bit hsub, the smallest we allow. 42 | # 80 digits = 320 bit hsub, the full length of SHA256 + 64 bit IV 43 | if hsublen < 48 or hsublen > 80: return False 44 | iv = hexiv(hsub) 45 | if not iv: return False 46 | # Return True if our generated hSub collides with the supplied 47 | # sample. 48 | return hash(text, iv, hsublen) == hsub 49 | 50 | def cryptorandom(bytes = 8): 51 | """Return a string of random bytes. By default we return the default 52 | IV length (64bits).""" 53 | return urandom(bytes) 54 | 55 | def hexiv(hsub, digits = 16): 56 | """Return the decoded IV from an hsub. By default the IV is the first 57 | 64bits of the hsub. As it's hex encoded, this equates to 16 digits.""" 58 | # We don't want to process IVs of inadequate length. 59 | if len(hsub) < digits: return False 60 | try: 61 | iv = hsub[:digits].decode('hex') 62 | except TypeError: 63 | # Not all Subjects are hSub'd so just bail out if it's non-hex. 64 | return False 65 | return iv 66 | 67 | def main(): 68 | """Only used for testing purposes. We Generate an hSub and then check it 69 | using the same input text.""" 70 | passphrase = "91c5dc4d604c9dee4a4074bbaef4f0fe94d92f406da5aee04d414400dd6d9f42" 71 | # hsub = hash(passphrase) 72 | hsub = '0b07815eac0b4631e8814855af5bf9f5c691f36ddd47c7b4' 73 | iv = hexiv(hsub) 74 | print "Passphrase: " + passphrase 75 | print "IV: %s" % iv.encode('hex') 76 | print "hsub: " + hsub 77 | print "hsub length: %d bytes" % len(hsub) 78 | print "Should return True: %s" % check(passphrase, hsub) 79 | print "Should return False: %s" % check('false', hsub) 80 | 81 | # Call main function. 82 | if (__name__ == "__main__"): 83 | main() 84 | 85 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | try: 2 | from setuptools import setup 3 | except: 4 | from distutils.core import setup 5 | import zipfile 6 | import os 7 | import pwd 8 | 9 | setup(name='encoDHer', 10 | version='0.3', 11 | description='symmetric email encryption utility for python', 12 | author='David R. Andersen', 13 | url='https://github.com/rxcomm/encoDHer', 14 | py_modules=['encodher','dhutils','dh','constants','hsub'], 15 | install_requires=['python-gnupg >= 0.3.5'], 16 | ) 17 | 18 | 19 | with zipfile.ZipFile('encodher', 'w', zipfile.ZIP_DEFLATED) as z: 20 | z.write('__main__.py') 21 | z.write('encodher.py') 22 | z.write('dhutils.py') 23 | z.write('dh_m2crypto.py') 24 | z.write('dh_pydhe.py') 25 | z.write('dh_legacy.py') 26 | z.write('hsub.py') 27 | 28 | with open('encodher', 'r+') as z: 29 | zipdata = z.read() 30 | z.seek(0) 31 | z.write('#!/usr/bin/env python\n'+zipdata) 32 | 33 | user = os.getenv('SUDO_USER') 34 | uid, gid = pwd.getpwnam(user)[2:4] 35 | os.chown('encodher', uid, gid) 36 | os.chmod('encodher',0755) 37 | os.system('cp encodher /usr/local/bin/encodher') 38 | os.system('cp dhparams.pem /usr/local/lib/dhparams.pem') 39 | print 'encodher executable copied to /usr/local/bin/encodher' 40 | --------------------------------------------------------------------------------