├── .gitignore
├── .travis.yml
├── CONTRIB
├── COPYING
├── COPYING.LESSER
├── README.md
├── docs
├── Makefile
├── conf.py
└── index.rst
├── requirements.txt
├── setup.cfg
├── setup.py
├── sphinxmix
├── SphinxClient.py
├── SphinxNode.py
├── SphinxParams.py
├── SphinxParamsC25519.py
├── UltrixClient.py
├── UltrixNode.py
└── __init__.py
├── timings.py
├── timings_ultrix.py
└── tox.ini
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 | MANIFEST
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 |
49 | # Translations
50 | *.mo
51 | *.pot
52 |
53 | # Django stuff:
54 | *.log
55 | .static_storage/
56 | .media/
57 | local_settings.py
58 |
59 | # Flask stuff:
60 | instance/
61 | .webassets-cache
62 |
63 | # Scrapy stuff:
64 | .scrapy
65 |
66 | # Sphinx documentation
67 | docs/_build/
68 |
69 | # PyBuilder
70 | target/
71 |
72 | # Jupyter Notebook
73 | .ipynb_checkpoints
74 |
75 | # pyenv
76 | .python-version
77 |
78 | # celery beat schedule file
79 | celerybeat-schedule
80 |
81 | # SageMath parsed files
82 | *.sage.py
83 |
84 | # Environments
85 | .env
86 | .venv
87 | env/
88 | venv/
89 | ENV/
90 | env.bak/
91 | venv.bak/
92 |
93 | # Spyder project settings
94 | .spyderproject
95 | .spyproject
96 |
97 | # Rope project settings
98 | .ropeproject
99 |
100 | # mkdocs documentation
101 | /site
102 |
103 | # mypy
104 | .mypy_cache/
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: false
2 | language: python
3 | python:
4 | - "2.7"
5 | - "3.5"
6 | install: pip install tox-travis coverage coveralls
7 | script:
8 | - tox
9 | after_success:
10 | - coveralls
--------------------------------------------------------------------------------
/CONTRIB:
--------------------------------------------------------------------------------
1 | Contributors:
2 |
3 | Ian Goldberg (2011)
4 | George Danezis (UCL InfoSec Group)
5 |
6 | Funding:
7 |
8 | Thanks to EU H2020 Privacy and Accountability in Networks via Optimized Randomized Mix-nets (Project ID: 653497).
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/COPYING.LESSER:
--------------------------------------------------------------------------------
1 | GNU LESSER 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 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
166 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | The Sphinxmix python package
2 | ============================
3 | []()
4 | [](http://sphinxmix.readthedocs.io/en/latest/?badge=latest)
5 | [](https://travis-ci.org/UCL-InfoSec/sphinx)
6 | [](https://coveralls.io/github/UCL-InfoSec/sphinx?branch=master)
7 |
8 | The ``sphinxmix`` package implements the Sphinx mix packet format core cryptographic functions.
9 |
10 | The paper describing sphinx may be found here:
11 |
12 | George Danezis and Ian Goldberg. Sphinx: A Compact and Provably Secure Mix Format. IEEE Symposium on Security and Privacy 2009.
13 | http://www.cypherpunks.ca/~iang/pubs/Sphinx_Oakland09.pdf
14 |
15 | Beyond the original proposal it allows for clients to communicate additional information to mix servers to implement arbitrary mixing strategies.
16 |
17 | More information
18 | ----------------
19 |
20 | The sphinxmix python package may be installed from pypi using pip: https://pypi.python.org/pypi/sphinxmix/
21 |
22 | The documentation for sphinxmix may be found on Read the Docs: http://sphinxmix.readthedocs.io/en/latest/
23 |
24 | The Git repository for sphinxmix may be found at the UCL Information Security repository at: https://github.com/UCL-InfoSec/sphinx
25 |
26 |
27 | Licence
28 | -------
29 |
30 | Sphinx v0.8-UCL README
31 | 2016-11-12
32 | George Danezis
33 |
34 | ```
35 | # Copyright 2011 Ian Goldberg
36 | # Copyright 2016 George Danezis (UCL InfoSec Group)
37 | #
38 | # This file is part of Sphinx.
39 | #
40 | # Sphinx is free software: you can redistribute it and/or modify
41 | # it under the terms of version 3 of the GNU Lesser General Public
42 | # License as published by the Free Software Foundation.
43 | #
44 | # Sphinx is distributed in the hope that it will be useful,
45 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
46 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
47 | # GNU Lesser General Public License for more details.
48 | #
49 | # You should have received a copy of the GNU Lesser General Public
50 | # License along with Sphinx. If not, see
51 | # .
52 | ```
53 |
54 | This is a UCL branch and port of the original Sphinx software to using modern python libraries, including petlib for cryptography and msgpack for binary formats. It also decouples the message processing from other concerns to allow sphix to be embedded into other applications. It is based on the original software by Ian Goldberg (U. Waterloo) and retains both his copyright and the original LGPL licence.
55 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = _build
9 |
10 | # User-friendly check for sphinx-build
11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
13 | endif
14 |
15 | # Internal variables.
16 | PAPEROPT_a4 = -D latex_paper_size=a4
17 | PAPEROPT_letter = -D latex_paper_size=letter
18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
19 | # the i18n builder cannot share the environment and doctrees with the others
20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
21 |
22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext
23 |
24 | help:
25 | @echo "Please use \`make ' where is one of"
26 | @echo " html to make standalone HTML files"
27 | @echo " dirhtml to make HTML files named index.html in directories"
28 | @echo " singlehtml to make a single large HTML file"
29 | @echo " pickle to make pickle files"
30 | @echo " json to make JSON files"
31 | @echo " htmlhelp to make HTML files and a HTML help project"
32 | @echo " qthelp to make HTML files and a qthelp project"
33 | @echo " applehelp to make an Apple Help Book"
34 | @echo " devhelp to make HTML files and a Devhelp project"
35 | @echo " epub to make an epub"
36 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
37 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
38 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
39 | @echo " text to make text files"
40 | @echo " man to make manual pages"
41 | @echo " texinfo to make Texinfo files"
42 | @echo " info to make Texinfo files and run them through makeinfo"
43 | @echo " gettext to make PO message catalogs"
44 | @echo " changes to make an overview of all changed/added/deprecated items"
45 | @echo " xml to make Docutils-native XML files"
46 | @echo " pseudoxml to make pseudoxml-XML files for display purposes"
47 | @echo " linkcheck to check all external links for integrity"
48 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
49 | @echo " coverage to run coverage check of the documentation (if enabled)"
50 |
51 | clean:
52 | rm -rf $(BUILDDIR)/*
53 |
54 | html:
55 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
56 | @echo
57 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
58 |
59 | dirhtml:
60 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
61 | @echo
62 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
63 |
64 | singlehtml:
65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
66 | @echo
67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
68 |
69 | pickle:
70 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
71 | @echo
72 | @echo "Build finished; now you can process the pickle files."
73 |
74 | json:
75 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
76 | @echo
77 | @echo "Build finished; now you can process the JSON files."
78 |
79 | htmlhelp:
80 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
81 | @echo
82 | @echo "Build finished; now you can run HTML Help Workshop with the" \
83 | ".hhp project file in $(BUILDDIR)/htmlhelp."
84 |
85 | qthelp:
86 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
87 | @echo
88 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
89 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
90 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/sphinxmix.qhcp"
91 | @echo "To view the help file:"
92 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/sphinxmix.qhc"
93 |
94 | applehelp:
95 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
96 | @echo
97 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
98 | @echo "N.B. You won't be able to view it unless you put it in" \
99 | "~/Library/Documentation/Help or install it in your application" \
100 | "bundle."
101 |
102 | devhelp:
103 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
104 | @echo
105 | @echo "Build finished."
106 | @echo "To view the help file:"
107 | @echo "# mkdir -p $$HOME/.local/share/devhelp/sphinxmix"
108 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/sphinxmix"
109 | @echo "# devhelp"
110 |
111 | epub:
112 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
113 | @echo
114 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
115 |
116 | latex:
117 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
118 | @echo
119 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
120 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
121 | "(use \`make latexpdf' here to do that automatically)."
122 |
123 | latexpdf:
124 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
125 | @echo "Running LaTeX files through pdflatex..."
126 | $(MAKE) -C $(BUILDDIR)/latex all-pdf
127 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
128 |
129 | latexpdfja:
130 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
131 | @echo "Running LaTeX files through platex and dvipdfmx..."
132 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
133 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
134 |
135 | text:
136 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
137 | @echo
138 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
139 |
140 | man:
141 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
142 | @echo
143 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
144 |
145 | texinfo:
146 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
147 | @echo
148 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
149 | @echo "Run \`make' in that directory to run these through makeinfo" \
150 | "(use \`make info' here to do that automatically)."
151 |
152 | info:
153 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
154 | @echo "Running Texinfo files through makeinfo..."
155 | make -C $(BUILDDIR)/texinfo info
156 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
157 |
158 | gettext:
159 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
160 | @echo
161 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
162 |
163 | changes:
164 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
165 | @echo
166 | @echo "The overview file is in $(BUILDDIR)/changes."
167 |
168 | linkcheck:
169 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
170 | @echo
171 | @echo "Link check complete; look for any errors in the above output " \
172 | "or in $(BUILDDIR)/linkcheck/output.txt."
173 |
174 | doctest:
175 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
176 | @echo "Testing of doctests in the sources finished, look at the " \
177 | "results in $(BUILDDIR)/doctest/output.txt."
178 |
179 | coverage:
180 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
181 | @echo "Testing of coverage in the sources finished, look at the " \
182 | "results in $(BUILDDIR)/coverage/python.txt."
183 |
184 | xml:
185 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
186 | @echo
187 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml."
188 |
189 | pseudoxml:
190 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
191 | @echo
192 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
193 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # sphinxmix documentation build configuration file, created by
4 | # sphinx-quickstart on Sun Nov 13 20:36:25 2016.
5 | #
6 | # This file is execfile()d with the current directory set to its
7 | # containing dir.
8 | #
9 | # Note that not all possible configuration values are present in this
10 | # autogenerated file.
11 | #
12 | # All configuration values have a default; values that are commented out
13 | # serve to show the default.
14 |
15 | import sys
16 | import os
17 | import shlex
18 |
19 | # If extensions (or modules to document with autodoc) are in another directory,
20 | # add these directories to sys.path here. If the directory is relative to the
21 | # documentation root, use os.path.abspath to make it absolute, like shown here.
22 | prev = os.path.abspath('..')
23 | print(os.listdir(prev))
24 |
25 | sys.path.insert(0, os.path.abspath('..'))
26 | sys.path.insert(0, os.path.abspath('.'))
27 |
28 | print("Current Directory: %s" % os.getcwd())
29 | print("Current Path: %s" % str(sys.path))
30 |
31 | # -- General configuration ------------------------------------------------
32 |
33 | # If your documentation needs a minimal Sphinx version, state it here.
34 | #needs_sphinx = '1.0'
35 |
36 | # Add any Sphinx extension module names here, as strings. They can be
37 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
38 | # ones.
39 | extensions = [
40 | 'sphinx.ext.autodoc',
41 | 'sphinx.ext.doctest',
42 | ]
43 |
44 | # Add any paths that contain templates here, relative to this directory.
45 | templates_path = ['_templates']
46 |
47 | # The suffix(es) of source filenames.
48 | # You can specify multiple suffix as a list of string:
49 | # source_suffix = ['.rst', '.md']
50 | source_suffix = '.rst'
51 |
52 | # The encoding of source files.
53 | #source_encoding = 'utf-8-sig'
54 |
55 | # The master toctree document.
56 | master_doc = 'index'
57 |
58 | # General information about the project.
59 | project = u'sphinxmix'
60 | copyright = u'2016, George Danezis (UCL)'
61 | author = u'George Danezis (UCL)'
62 |
63 | # The version info for the project you're documenting, acts as replacement for
64 | # |version| and |release|, also used in various other places throughout the
65 | # built documents.
66 | #
67 | # The short X.Y version.
68 | import sphinxmix
69 | version = sphinxmix.VERSION
70 | # The full version, including alpha/beta/rc tags.
71 | release = sphinxmix.VERSION
72 |
73 | # The language for content autogenerated by Sphinx. Refer to documentation
74 | # for a list of supported languages.
75 | #
76 | # This is also used if you do content translation via gettext catalogs.
77 | # Usually you set "language" from the command line for these cases.
78 | language = None
79 |
80 | # There are two options for replacing |today|: either, you set today to some
81 | # non-false value, then it is used:
82 | #today = ''
83 | # Else, today_fmt is used as the format for a strftime call.
84 | #today_fmt = '%B %d, %Y'
85 |
86 | # List of patterns, relative to source directory, that match files and
87 | # directories to ignore when looking for source files.
88 | exclude_patterns = ['_build']
89 |
90 | # The reST default role (used for this markup: `text`) to use for all
91 | # documents.
92 | #default_role = None
93 |
94 | # If true, '()' will be appended to :func: etc. cross-reference text.
95 | #add_function_parentheses = True
96 |
97 | # If true, the current module name will be prepended to all description
98 | # unit titles (such as .. function::).
99 | #add_module_names = True
100 |
101 | # If true, sectionauthor and moduleauthor directives will be shown in the
102 | # output. They are ignored by default.
103 | #show_authors = False
104 |
105 | # The name of the Pygments (syntax highlighting) style to use.
106 | pygments_style = 'sphinx'
107 |
108 | # A list of ignored prefixes for module index sorting.
109 | #modindex_common_prefix = []
110 |
111 | # If true, keep warnings as "system message" paragraphs in the built documents.
112 | #keep_warnings = False
113 |
114 | # If true, `todo` and `todoList` produce output, else they produce nothing.
115 | todo_include_todos = False
116 |
117 |
118 | # -- Options for HTML output ----------------------------------------------
119 |
120 | # The theme to use for HTML and HTML Help pages. See the documentation for
121 | # a list of builtin themes.
122 | html_theme = 'alabaster'
123 |
124 | # Theme options are theme-specific and customize the look and feel of a theme
125 | # further. For a list of options available for each theme, see the
126 | # documentation.
127 | #html_theme_options = {}
128 |
129 | # Add any paths that contain custom themes here, relative to this directory.
130 | #html_theme_path = []
131 |
132 | # The name for this set of Sphinx documents. If None, it defaults to
133 | # " v documentation".
134 | #html_title = None
135 |
136 | # A shorter title for the navigation bar. Default is the same as html_title.
137 | #html_short_title = None
138 |
139 | # The name of an image file (relative to this directory) to place at the top
140 | # of the sidebar.
141 | #html_logo = None
142 |
143 | # The name of an image file (within the static path) to use as favicon of the
144 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
145 | # pixels large.
146 | #html_favicon = None
147 |
148 | # Add any paths that contain custom static files (such as style sheets) here,
149 | # relative to this directory. They are copied after the builtin static files,
150 | # so a file named "default.css" will overwrite the builtin "default.css".
151 | html_static_path = ['_static']
152 |
153 | # Add any extra paths that contain custom files (such as robots.txt or
154 | # .htaccess) here, relative to this directory. These files are copied
155 | # directly to the root of the documentation.
156 | #html_extra_path = []
157 |
158 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
159 | # using the given strftime format.
160 | #html_last_updated_fmt = '%b %d, %Y'
161 |
162 | # If true, SmartyPants will be used to convert quotes and dashes to
163 | # typographically correct entities.
164 | #html_use_smartypants = True
165 |
166 | # Custom sidebar templates, maps document names to template names.
167 | #html_sidebars = {}
168 |
169 | # Additional templates that should be rendered to pages, maps page names to
170 | # template names.
171 | #html_additional_pages = {}
172 |
173 | # If false, no module index is generated.
174 | #html_domain_indices = True
175 |
176 | # If false, no index is generated.
177 | #html_use_index = True
178 |
179 | # If true, the index is split into individual pages for each letter.
180 | #html_split_index = False
181 |
182 | # If true, links to the reST sources are added to the pages.
183 | #html_show_sourcelink = True
184 |
185 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
186 | #html_show_sphinx = True
187 |
188 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
189 | #html_show_copyright = True
190 |
191 | # If true, an OpenSearch description file will be output, and all pages will
192 | # contain a tag referring to it. The value of this option must be the
193 | # base URL from which the finished HTML is served.
194 | #html_use_opensearch = ''
195 |
196 | # This is the file name suffix for HTML files (e.g. ".xhtml").
197 | #html_file_suffix = None
198 |
199 | # Language to be used for generating the HTML full-text search index.
200 | # Sphinx supports the following languages:
201 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
202 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
203 | #html_search_language = 'en'
204 |
205 | # A dictionary with options for the search language support, empty by default.
206 | # Now only 'ja' uses this config value
207 | #html_search_options = {'type': 'default'}
208 |
209 | # The name of a javascript file (relative to the configuration directory) that
210 | # implements a search results scorer. If empty, the default will be used.
211 | #html_search_scorer = 'scorer.js'
212 |
213 | # Output file base name for HTML help builder.
214 | htmlhelp_basename = 'sphinxmixdoc'
215 |
216 | # -- Options for LaTeX output ---------------------------------------------
217 |
218 | latex_elements = {
219 | # The paper size ('letterpaper' or 'a4paper').
220 | #'papersize': 'letterpaper',
221 |
222 | # The font size ('10pt', '11pt' or '12pt').
223 | #'pointsize': '10pt',
224 |
225 | # Additional stuff for the LaTeX preamble.
226 | #'preamble': '',
227 |
228 | # Latex figure (float) alignment
229 | #'figure_align': 'htbp',
230 | }
231 |
232 | # Grouping the document tree into LaTeX files. List of tuples
233 | # (source start file, target name, title,
234 | # author, documentclass [howto, manual, or own class]).
235 | latex_documents = [
236 | (master_doc, 'sphinxmix.tex', u'sphinxmix Documentation',
237 | u'George Danezis (UCL)', 'manual'),
238 | ]
239 |
240 | # The name of an image file (relative to this directory) to place at the top of
241 | # the title page.
242 | #latex_logo = None
243 |
244 | # For "manual" documents, if this is true, then toplevel headings are parts,
245 | # not chapters.
246 | #latex_use_parts = False
247 |
248 | # If true, show page references after internal links.
249 | #latex_show_pagerefs = False
250 |
251 | # If true, show URL addresses after external links.
252 | #latex_show_urls = False
253 |
254 | # Documents to append as an appendix to all manuals.
255 | #latex_appendices = []
256 |
257 | # If false, no module index is generated.
258 | #latex_domain_indices = True
259 |
260 |
261 | # -- Options for manual page output ---------------------------------------
262 |
263 | # One entry per manual page. List of tuples
264 | # (source start file, name, description, authors, manual section).
265 | man_pages = [
266 | (master_doc, 'sphinxmix', u'sphinxmix Documentation',
267 | [author], 1)
268 | ]
269 |
270 | # If true, show URL addresses after external links.
271 | #man_show_urls = False
272 |
273 |
274 | # -- Options for Texinfo output -------------------------------------------
275 |
276 | # Grouping the document tree into Texinfo files. List of tuples
277 | # (source start file, target name, title, author,
278 | # dir menu entry, description, category)
279 | texinfo_documents = [
280 | (master_doc, 'sphinxmix', u'sphinxmix Documentation',
281 | author, 'sphinxmix', 'One line description of project.',
282 | 'Miscellaneous'),
283 | ]
284 |
285 | # Documents to append as an appendix to all manuals.
286 | #texinfo_appendices = []
287 |
288 | # If false, no module index is generated.
289 | #texinfo_domain_indices = True
290 |
291 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
292 | #texinfo_show_urls = 'footnote'
293 |
294 | # If true, do not generate a @detailmenu in the "Top" node's menu.
295 | #texinfo_no_detailmenu = False
296 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | .. sphinxmix documentation master file, created by
2 | sphinx-quickstart on Sun Nov 13 20:36:25 2016.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | The sphinxmix package documentation
7 | ===================================
8 |
9 | This documentation relates to the `sphinxmix` package version |version|.
10 |
11 | Installing
12 | ----------
13 |
14 | Install using `pip` through the command::
15 |
16 | $ pip install sphinxmix
17 |
18 | Basic usage
19 | -----------
20 |
21 | .. automodule:: sphinxmix
22 | :members:
23 |
24 | Development
25 | -----------
26 |
27 | The git repository for ``sphinxmix`` can be cloned from here:
28 | https://github.com/UCL-InfoSec/sphinx
29 |
30 | The ``pytest`` unit tests and doctests of ``sphinxmix`` may be ran using ``tox`` simply through the command::
31 |
32 | $ tox
33 |
34 | To upload a new distribution of ``sphinxmix`` the maintainer simply uses::
35 |
36 | $ python setup.py sdist upload
37 |
38 |
39 | Core classes and functions
40 | ==========================
41 |
42 | .. autoclass:: sphinxmix.SphinxParams.SphinxParams
43 |
44 | .. autoclass:: sphinxmix.SphinxParams.Group_ECC
45 |
46 | .. autoclass:: sphinxmix.SphinxParamsC25519.Group_C25519
47 |
48 | Utility functions
49 | -----------------
50 |
51 | .. autofunction:: sphinxmix.SphinxClient.pki_entry
52 |
53 | .. autofunction:: sphinxmix.SphinxClient.Nenc
54 |
55 | .. autodata:: sphinxmix.SphinxClient.Relay_flag
56 |
57 | .. autodata:: sphinxmix.SphinxClient.Dest_flag
58 |
59 | .. autodata:: sphinxmix.SphinxClient.Surb_flag
60 |
61 | .. autofunction:: sphinxmix.SphinxClient.PFdecode
62 |
63 | .. autofunction:: sphinxmix.SphinxClient.rand_subset
64 |
65 | Client functions
66 | ----------------
67 |
68 | .. autofunction:: sphinxmix.SphinxClient.create_forward_message
69 |
70 | .. autofunction:: sphinxmix.SphinxClient.receive_forward
71 |
72 | Packaging messages
73 | ------------------
74 |
75 | .. autofunction:: sphinxmix.SphinxClient.pack_message
76 |
77 | .. autofunction:: sphinxmix.SphinxClient.unpack_message
78 |
79 | Mix functions
80 | -------------
81 |
82 | .. autofunction:: sphinxmix.SphinxNode.sphinx_process
83 |
84 | SURB functions
85 | --------------
86 |
87 | .. autofunction:: sphinxmix.SphinxClient.create_surb
88 |
89 | .. autofunction:: sphinxmix.SphinxClient.package_surb
90 |
91 | .. autofunction:: sphinxmix.SphinxClient.receive_surb
92 |
93 |
94 | Ultrix Format
95 | =============
96 |
97 | Mix functions
98 | -------------
99 |
100 | .. autofunction:: sphinxmix.UltrixNode.ultrix_process
101 |
102 | Client functions
103 | ----------------
104 |
105 | .. autofunction:: sphinxmix.UltrixClient.create_forward_message
106 |
107 | .. autofunction:: sphinxmix.UltrixClient.receive_forward
108 |
109 | SURB functions
110 | --------------
111 |
112 | .. autofunction:: sphinxmix.UltrixClient.create_surb
113 |
114 | .. autofunction:: sphinxmix.UltrixClient.package_surb
115 |
116 | .. autofunction:: sphinxmix.UltrixClient.decode_surb
117 |
118 | .. autofunction:: sphinxmix.UltrixClient.receive_surb
119 |
120 |
121 | Indices and tables
122 | ==================
123 |
124 | * :ref:`genindex`
125 | * :ref:`modindex`
126 | * :ref:`search`
127 |
128 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | future>=0.14.3
2 | pytest>=2.5.0
3 | msgpack-python>=0.4.6
4 | petlib>=0.0.41
5 | pynacl>=1.1.0
6 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [aliases]
2 | test=pytest
3 |
4 | [tool:pytest]
5 | addopts = --doctest-modules
6 | python_files = sphinxmix/__init__.py sphinxmix/SphinxClient.py sphinxmix/SphinxParams.py sphinxmix/SphinxNode.py sphinxmix/UltrixClient.py sphinxmix/UltrixNode.py sphinxmix/SphinxParamsC25519.py
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 | import sphinxmix
4 |
5 | if __name__ == "__main__":
6 |
7 | setup(name='sphinxmix',
8 | version=sphinxmix.VERSION,
9 | description='A Python implementation of the Sphinx mix packet format.',
10 | author='George Danezis',
11 | author_email='g.danezis@ucl.ac.uk',
12 | url=r'http://sphinxmix.readthedocs.io/en/latest/',
13 | packages=['sphinxmix'],
14 | license="2-clause BSD",
15 | long_description="""A Python implementation of the Sphinx mix packet format.
16 |
17 | For full documentation see: http://sphinxmix.readthedocs.io/en/latest/
18 | """,
19 |
20 | setup_requires=['pytest-runner', "pytest"],
21 | tests_require=[
22 | "pytest",
23 | "future >= 0.14.3",
24 | "pytest >= 3.0.0",
25 | "msgpack-python >= 0.4.6",
26 | "petlib >= 0.0.41",
27 | "pynacl >= 1.1.0",
28 | ],
29 | install_requires=[
30 | "future >= 0.14.3",
31 | "pytest >= 3.0.0",
32 | "msgpack-python >= 0.4.6",
33 | "petlib >= 0.0.41",
34 | "pynacl >= 1.1.0",
35 | ]
36 | )
--------------------------------------------------------------------------------
/sphinxmix/SphinxClient.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | # Copyright 2011 Ian Goldberg
4 | # Copyright 2016 George Danezis (UCL InfoSec Group)
5 | #
6 | # This file is part of Sphinx.
7 | #
8 | # Sphinx is free software: you can redistribute it and/or modify
9 | # it under the terms of version 3 of the GNU Lesser General Public
10 | # License as published by the Free Software Foundation.
11 | #
12 | # Sphinx is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU Lesser General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU Lesser General Public
18 | # License along with Sphinx. If not, see
19 | # .
20 |
21 |
22 | from os import urandom
23 | from collections import namedtuple
24 | from struct import pack
25 |
26 | from petlib.pack import encode, decode
27 |
28 | # Python 2/3 compatibility
29 | from builtins import bytes
30 |
31 | from .SphinxParams import SphinxParams
32 | from . import SphinxException
33 |
34 |
35 | # FLAGS
36 |
37 | #: Routing flag indicating message is to be relayed.
38 | Relay_flag = "\xF0"
39 |
40 | #: Routing flag indicating message is to be delivered.
41 | Dest_flag = "\xF1"
42 |
43 | #: Routing flag indicating surb reply is to be delivered.
44 | Surb_flag = "\xF2"
45 |
46 | # Padding/unpadding of message bodies: a 0 bit, followed by as many 1
47 | # bits as it takes to fill it up
48 |
49 | header_record = namedtuple("header_record", ["alpha", "s", "b", "aes"])
50 |
51 | #: A helper named tuple to store PKI information.
52 | pki_entry = namedtuple("pki_entry", ["id", "x", "y"])
53 |
54 |
55 | def pad_body(msgtotalsize, body):
56 | """ Unpad the Sphinx message body."""
57 | body = body + b"\x7f"
58 | body = body + (b"\xff" * (msgtotalsize - len(body)))
59 |
60 | if (msgtotalsize - len(body)) < 0:
61 | raise SphinxException("Insufficient space for body")
62 |
63 | return body
64 |
65 | def unpad_body(body):
66 | """ Pad a Sphinx message body. """
67 | body = bytes(body)
68 | l = len(body) - 1
69 | x_marker = bytes(b"\x7f")[0]
70 | f_marker = bytes(b"\xff")[0]
71 | while body[l] == f_marker and l > 0:
72 | l -= 1
73 |
74 | if body[l] == x_marker:
75 | ret = body[:l]
76 | else:
77 | ret = b''
78 |
79 | return ret
80 |
81 | # Prefix-free encoding/decoding of node names and destinations
82 |
83 | # Sphinx nodes
84 | def Nenc(idnum):
85 | """ The encoding of mix names. """
86 | return Route_pack((Relay_flag, idnum))
87 |
88 | def Route_pack(info):
89 | return encode(info)
90 |
91 | # Decode the prefix-free encoding. Return the type, value, and the
92 | # remainder of the input string
93 | def PFdecode(param, packed):
94 | """ Decoder of prefix free encoder for commands received by mix or clients."""
95 | assert type(packed) is bytes
96 | return decode(packed)
97 |
98 |
99 | def rand_subset(lst, nu):
100 | """Return a list of nu random elements of the given list (without
101 | replacement)."""
102 |
103 | # Randomize the order of the list by sorting on a random key
104 | nodeids = [(urandom(8),x) for x in lst]
105 | nodeids.sort(key=lambda x:x[0])
106 |
107 | # Return the first nu elements of the randomized list
108 | return list(map(lambda x:x[1], nodeids[:nu]))
109 |
110 |
111 | def create_header(params, nodelist, keys, dest, assoc=None):
112 | """ Internal function, creating a Sphinx header."""
113 |
114 | node_meta = [pack("b", len(n)) + n for n in nodelist]
115 |
116 | if params.assoc_len > 0:
117 | assoc = assoc
118 | else:
119 | assoc = [b''] * len(nodelist)
120 |
121 | assert len(assoc) == len(nodelist)
122 | for assoc_data in assoc:
123 | assert len(assoc_data) == params.assoc_len
124 |
125 | p = params
126 | nu = len(nodelist)
127 | max_len = p.max_len
128 |
129 | group = p.group
130 | x = group.gensecret()
131 |
132 | blind_factors = [ x ]
133 | asbtuples = []
134 |
135 | from binascii import hexlify
136 |
137 | for k in keys:
138 | alpha = group.expon_base(blind_factors)
139 |
140 | s = group.expon(k, blind_factors)
141 | aes_s = p.get_aes_key(s)
142 |
143 | b = p.hb(aes_s)
144 | blind_factors += [ b ]
145 |
146 | hr = header_record(alpha, s, b, aes_s)
147 | asbtuples.append(hr)
148 |
149 | # Compute the filler strings
150 | phi = b''
151 | min_len = (max_len - 32)
152 | for i in range(1,nu):
153 | plain = phi + (b"\x00" * (p.k + len(node_meta[i])))
154 |
155 | kx = p.hrho(asbtuples[i-1].aes)
156 | mx = (b"\x00"*min_len)+plain
157 |
158 | phi = p.xor_rho(kx, mx)
159 | phi = phi[min_len:]
160 |
161 | min_len -= len(node_meta[i]) + p.k
162 |
163 |
164 | assert len(phi) == sum(map(len, node_meta[1:])) + (nu-1)*p.k
165 |
166 | # Compute the (beta, gamma) tuples
167 | # The os.urandom used to be a string of 0x00 bytes, but that's wrong
168 |
169 | final_routing = pack("b", len(dest)) + dest
170 |
171 | len_meta = sum(map(len, node_meta[1:]))
172 | random_pad_len = (max_len - 32) - len_meta - (nu-1)*p.k - len(final_routing)
173 |
174 | if random_pad_len < 0:
175 | raise SphinxException("Insufficient space routing info")
176 |
177 | beta = final_routing + urandom(random_pad_len)
178 | beta = p.xor_rho(p.hrho(asbtuples[nu-1].aes), beta) + phi
179 |
180 | # Compute the MAC over the associated data and beta
181 | gamma = p.mu(p.hmu(asbtuples[nu-1].aes), assoc[nu-1] + beta)
182 |
183 | for i in range(nu-2, -1, -1):
184 | node_id = node_meta[i+1]
185 |
186 | plain_beta_len = (max_len - 32) - p.k - len(node_id)
187 |
188 | plain = node_id + gamma + beta[:plain_beta_len]
189 |
190 | beta = p.xor_rho(p.hrho(asbtuples[i].aes), plain)
191 | gamma = p.mu(p.hmu(asbtuples[i].aes), assoc[i] + beta)
192 |
193 | return (asbtuples[0].alpha, beta, gamma), \
194 | [x.aes for x in asbtuples]
195 |
196 |
197 | def create_forward_message(params, nodelist, keys, dest, msg, assoc=None):
198 | """Creates a forward Sphix message, ready to be processed by a first mix.
199 |
200 | It takes as parameters a node list of mix information, that will be provided to each mix, forming the path of the message;
201 | a list of public keys of all intermediate mixes; a destination and a message; and optinally an array of associated data (byte arrays)."""
202 |
203 | p = params
204 | # pki = p.pki
205 | nu = len(nodelist)
206 | assert len(dest) < 128 and len(dest) > 0
207 | assert p.k + 1 + len(dest) + len(msg) < p.m
208 |
209 | # Compute the header and the secrets
210 |
211 | final = Route_pack((Dest_flag, ))
212 | header, secrets = create_header(params, nodelist, keys, final, assoc)
213 |
214 |
215 | payload = pad_body(p.m - p.k, encode((dest, msg)))
216 | mac = p.mu(p.hpi(secrets[nu-1]), payload)
217 | body = mac + payload
218 |
219 | # Compute the delta values
220 | delta = p.pi(p.hpi(secrets[nu-1]), body)
221 | for i in range(nu-2, -1, -1):
222 | delta = p.pi(p.hpi(secrets[i]), delta)
223 |
224 | return header, delta
225 |
226 | def create_surb(params, nodelist, keys, dest, assoc=None):
227 | """Creates a Sphinx single use reply block (SURB) using a set of parameters;
228 | a sequence of mix identifiers; a pki mapping names of mixes to keys; and a final
229 | destination. An array of associated data, for each mix on the path, may optionally
230 | be passed in.
231 |
232 | Returns:
233 | - A triplet (surbid, surbkeytuple, nymtuple). Where the surbid can be
234 | used as an index to store the secrets surbkeytuple; nymtuple is the actual
235 | SURB that needs to be sent to the receiver.
236 |
237 | """
238 | p = params
239 | nu = len(nodelist)
240 | xid = urandom(p.k)
241 |
242 | # Compute the header and the secrets
243 | final = Route_pack((Surb_flag, dest, xid))
244 | header, secrets = create_header(params, nodelist, keys, final, assoc )
245 |
246 | ktilde = urandom(p.k)
247 | keytuple = [ktilde]
248 | keytuple.extend(map(p.hpi, secrets))
249 | return xid, keytuple, (nodelist[0], header, ktilde)
250 |
251 | def package_surb(params, nymtuple, message):
252 | """Packages a message to be sent with a SURB. The message has to be bytes,
253 | and the nymtuple is the structure returned by the create_surb call.
254 |
255 | Returns a header and a body to pass to the first mix.
256 | """
257 | n0, header0, ktilde = nymtuple
258 |
259 | message = pad_body(params.m - params.k, message)
260 | mac = params.mu(ktilde, message)
261 | body = params.pi(ktilde, mac + message )
262 | return (header0, body)
263 |
264 |
265 | def receive_forward(params, mac_key, delta):
266 | """ Decodes the body of a forward message, and checks its MAC tag."""
267 |
268 | if delta[:params.k] != params.mu(mac_key, delta[params.k:]):
269 | raise SphinxException("Modified Body")
270 |
271 | delta = unpad_body(delta[params.k:])
272 | return decode(delta)
273 |
274 | def receive_surb(params, keytuple, delta):
275 | """Processes a SURB body to extract the reply. The keytuple was provided at the time of
276 | SURB creation, and can be indexed by the SURB id, which is also returned to the receiving user.
277 |
278 | Returns the decoded message.
279 | """
280 | p = params
281 |
282 | ktilde = keytuple.pop(0)
283 | nu = len(keytuple)
284 | for i in range(nu-1, -1, -1):
285 | delta = p.pi(keytuple[i], delta)
286 | delta = p.pii(ktilde, delta)
287 |
288 | if delta[:p.k] == p.mu(ktilde, delta[p.k:]):
289 | msg = unpad_body(delta[p.k:])
290 | else:
291 | raise SphinxException("Modified SURB Body")
292 |
293 | return msg
294 |
295 | def pack_message(params, m):
296 | """ A method to pack mix messages. """
297 | return encode(((params.max_len, params.m), m))
298 |
299 | def unpack_message(params_dict, m):
300 | """ A method to unpack mix messages. """
301 | lens, msg = decode(m)
302 | if tuple(lens) not in params_dict:
303 | raise SphinxException("No parameter settings for: %s" % lens)
304 | return params_dict[tuple(lens)], msg
305 |
306 | def test_timing(rep=100, payload_size=1024 * 10):
307 | r = 5
308 | params = SphinxParams(body_len=payload_size)
309 | pki = {}
310 |
311 | pkiPriv = {}
312 | pkiPub = {}
313 |
314 | for i in range(10):
315 | nid = pack("b", i)
316 | x = params.group.gensecret()
317 | y = params.group.expon(params.group.g, [ x ])
318 | pkiPriv[nid] = pki_entry(nid, x, y)
319 | pkiPub[nid] = pki_entry(nid, None, y)
320 |
321 | # The simplest path selection algorithm and message packaging
322 | use_nodes = rand_subset(pkiPub.keys(), r)
323 | nodes_routing = list(map(Nenc, use_nodes))
324 | node_keys = [pkiPub[n].y for n in use_nodes]
325 | print()
326 |
327 | import time
328 | t0 = time.time()
329 | for _ in range(rep):
330 | header, delta = create_forward_message(params, nodes_routing, node_keys, b"dest", b"this is a test")
331 | t1 = time.time()
332 | print("Time per mix encoding: %.2fms" % ((t1-t0)*1000.0/rep))
333 | T_package = (t1-t0)/rep
334 |
335 | from .SphinxNode import sphinx_process
336 | import time
337 | t0 = time.time()
338 | for _ in range(rep):
339 | x = pkiPriv[use_nodes[0]].x
340 | sphinx_process(params, x, header, delta)
341 | t1 = time.time()
342 | print("Time per mix processing: %.2fms" % ((t1-t0)*1000.0/rep))
343 | T_process = (t1-t0)/rep
344 |
345 | return T_package, T_process
346 |
347 |
348 | def test_minimal():
349 | from .SphinxParams import SphinxParams
350 | r = 5
351 |
352 | params = SphinxParams()
353 |
354 | # The minimal PKI involves names of nodes and keys
355 |
356 | pkiPriv = {}
357 | pkiPub = {}
358 |
359 | for i in range(10):
360 | nid = pack("b", i) # Nenc(params, bytes([i]))
361 | x = params.group.gensecret()
362 | y = params.group.expon(params.group.g, [ x ])
363 | pkiPriv[nid] = pki_entry(nid, x, y)
364 | pkiPub[nid] = pki_entry(nid, None, y)
365 |
366 | # The simplest path selection algorithm and message packaging
367 | use_nodes = rand_subset(pkiPub.keys(), r)
368 | nodes_routing = list(map(Nenc, use_nodes))
369 | node_keys = [pkiPub[n].y for n in use_nodes]
370 | dest = b"bob"
371 | message = b"this is a test"
372 | header, delta = create_forward_message(params, nodes_routing, node_keys, dest, message)
373 |
374 | # Test encoding and decoding
375 |
376 | bin_message = pack_message(params, (header, delta))
377 | param_dict = { (params.max_len, params.m):params }
378 |
379 | px, (header1, delta1) = unpack_message(param_dict, bin_message)
380 | assert px == params
381 | assert header == tuple(header1)
382 | assert delta == delta1
383 |
384 | # Process message by the sequence of mixes
385 | from .SphinxNode import sphinx_process
386 | x = pkiPriv[use_nodes[0]].x
387 |
388 | i = 0
389 | while True:
390 |
391 | ret = sphinx_process(params, x, header, delta)
392 | (tag, B, (header, delta), mac_key) = ret
393 | routing = PFdecode(params, B)
394 |
395 | print("round %d" % i)
396 | i += 1
397 |
398 | # print("Type: %s" % typex)
399 | if routing[0] == Relay_flag:
400 | addr = routing[1]
401 | x = pkiPriv[addr].x
402 | elif routing[0] == Dest_flag:
403 | assert len(routing) == 1
404 | # assert delta[:16] == b"\x00" * params.k
405 | dec_dest, dec_msg = receive_forward(params, mac_key, delta)
406 | assert dec_dest == dest
407 | assert dec_msg == message
408 |
409 | break
410 | else:
411 | print("Error")
412 | assert False
413 | break
414 |
415 | # Test the nym creation
416 | surbid, surbkeytuple, nymtuple = create_surb(params, nodes_routing, node_keys, b"myself")
417 |
418 | message = b"This is a reply"
419 | header, delta = package_surb(params, nymtuple, message)
420 |
421 | x = pkiPriv[use_nodes[0]].x
422 |
423 | while True:
424 | ret = sphinx_process(params, x, header, delta)
425 | (tag, B, (header, delta), mac_key) = ret
426 | routing = PFdecode(params, B)
427 |
428 | if routing[0] == Relay_flag:
429 | flag, addr = routing
430 | x = pkiPriv[addr].x
431 | elif routing[0] == Surb_flag:
432 | flag, dest, myid = routing
433 | break
434 |
435 | received = receive_surb(params, surbkeytuple, delta)
436 | assert received == message
437 |
438 | def test_assoc(rep=100, payload_size=1024 * 10):
439 | r = 5
440 | params = SphinxParams(body_len=payload_size, assoc_len=4)
441 | pki = {}
442 |
443 | pkiPriv = {}
444 | pkiPub = {}
445 |
446 | for i in range(10):
447 | nid = pack("b", i)
448 | x = params.group.gensecret()
449 | y = params.group.expon(params.group.g, [ x ])
450 | pkiPriv[nid] = pki_entry(nid, x, y)
451 | pkiPub[nid] = pki_entry(nid, None, y)
452 |
453 |
454 | # The simplest path selection algorithm and message packaging
455 | use_nodes = rand_subset(pkiPub.keys(), r)
456 | nodes_routing = list(map(Nenc, use_nodes))
457 | node_keys = [pkiPub[n].y for n in use_nodes]
458 | print()
459 |
460 | assoc = [b"XXXX"] * len(nodes_routing)
461 |
462 | import time
463 | t0 = time.time()
464 | for _ in range(rep):
465 | header, delta = create_forward_message(params, nodes_routing, node_keys, b"dest", b"this is a test", assoc)
466 | t1 = time.time()
467 | print("Time per mix encoding: %.2fms" % ((t1-t0)*1000.0/rep))
468 | T_package = (t1-t0)/rep
469 |
470 | from .SphinxNode import sphinx_process
471 | import time
472 | t0 = time.time()
473 | for _ in range(rep):
474 | x = pkiPriv[use_nodes[0]].x
475 | sphinx_process(params, x, header, delta, b"XXXX")
476 | t1 = time.time()
477 | print("Time per mix processing: %.2fms" % ((t1-t0)*1000.0/rep))
478 | T_process = (t1-t0)/rep
479 |
480 | return T_package, T_process
481 |
482 | from nacl.bindings import crypto_scalarmult_base, crypto_scalarmult
483 |
484 | def test_c25519(rep=100, payload_size=1024 * 10):
485 | r = 5
486 | from .SphinxParamsC25519 import Group_C25519
487 |
488 | group = Group_C25519()
489 | params = SphinxParams(group=group, body_len=payload_size, assoc_len=4)
490 |
491 | # Monkey patch to use AES-CTR
492 | params.lioness_enc = params.xor_rho
493 | params.lioness_dec = params.xor_rho
494 |
495 |
496 | pki = {}
497 |
498 | pkiPriv = {}
499 | pkiPub = {}
500 |
501 | for i in range(10):
502 | nid = pack("b", i)
503 | x = params.group.gensecret()
504 | y = crypto_scalarmult_base(x)
505 | pkiPriv[nid] = pki_entry(nid, x, y)
506 | pkiPub[nid] = pki_entry(nid, None, y)
507 |
508 |
509 | # The simplest path selection algorithm and message packaging
510 | use_nodes = rand_subset(pkiPub.keys(), r)
511 | nodes_routing = list(map(Nenc, use_nodes))
512 | node_keys = [pkiPub[n].y for n in use_nodes]
513 | print()
514 |
515 | assoc = [b"XXXX"] * len(nodes_routing)
516 |
517 | import time
518 | t0 = time.time()
519 | for _ in range(rep):
520 | header, delta = create_forward_message(params, nodes_routing, node_keys, b"dest", b"this is a test", assoc)
521 | t1 = time.time()
522 | print("Time per mix encoding: %.2fms" % ((t1-t0)*1000.0/rep))
523 | T_package = (t1-t0)/rep
524 |
525 | from .SphinxNode import sphinx_process
526 | import time
527 | t0 = time.time()
528 | for _ in range(rep):
529 | x = pkiPriv[use_nodes[0]].x
530 | sphinx_process(params, x, header, delta, b"XXXX")
531 | t1 = time.time()
532 | print("Time per mix processing: %.2fms" % ((t1-t0)*1000.0/rep))
533 | T_process = (t1-t0)/rep
534 |
535 | return T_package, T_process
536 |
537 | def test_c25519_hemi(rep=1, payload_size=1024):
538 | r = 5
539 | from .SphinxParamsC25519 import Group_C25519
540 |
541 | group = Group_C25519()
542 | params = SphinxParams(group=group, body_len=payload_size, assoc_len=4)
543 |
544 | # Monkey patch to use AES-CTR
545 | params.lioness_enc = params.xor_rho
546 | params.lioness_dec = params.xor_rho
547 |
548 |
549 | pki = {}
550 |
551 | pkiPriv = {}
552 | pkiPub = {}
553 |
554 | for i in range(10):
555 | nid = pack("b", i) # Nenc(params, bytes([i]))
556 | x = params.group.gensecret()
557 | y = crypto_scalarmult_base(x)
558 | pkiPriv[nid] = pki_entry(nid, x, y)
559 | pkiPub[nid] = pki_entry(nid, None, y)
560 |
561 |
562 | # The simplest path selection algorithm and message packaging
563 | use_nodes = rand_subset(pkiPub.keys(), r)
564 | nodes_routing = list(map(Nenc, use_nodes))
565 | node_keys = [pkiPub[n].y for n in use_nodes]
566 |
567 | assoc = [b"XXXX"] * len(nodes_routing)
568 |
569 | header, delta = create_forward_message(params, nodes_routing, node_keys, b"dest", b"this is a test", assoc)
570 |
571 |
572 | from .SphinxNode import sphinx_process
573 | from binascii import hexlify
574 |
575 | x = pkiPriv[use_nodes[0]].x
576 | i = 0
577 | while True:
578 | assert pkiPriv[use_nodes[i]].x == x
579 | assert pkiPriv[use_nodes[i]].y == node_keys[i]
580 |
581 | alpha, beta, gamma = header
582 |
583 | (_, B, (header, delta), mac_key) = sphinx_process(params, x, header, delta, b"XXXX")
584 |
585 | routing = PFdecode(params, B)
586 | assert i == 4 or B == nodes_routing[i+1]
587 |
588 | i += 1
589 |
590 | if routing[0] == Relay_flag:
591 | addr = routing[1]
592 | assert addr == use_nodes[i]
593 | x = pkiPriv[addr].x
594 | elif routing[0] == Dest_flag:
595 | assert len(routing) == 1
596 | dec_dest, dec_msg = receive_forward(params, mac_key, delta)
597 | assert dec_dest == b"dest"
598 | assert dec_msg == b"this is a test"
599 |
600 | break
601 | else:
602 | print("Error")
603 | assert False
604 | break
605 |
606 |
607 |
608 |
609 | if __name__ == "__main__":
610 | test_timing()
--------------------------------------------------------------------------------
/sphinxmix/SphinxNode.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | # Copyright 2011 Ian Goldberg
4 | # Copyright 2016 George Danezis (UCL InfoSec Group)
5 | #
6 | # This file is part of Sphinx.
7 | #
8 | # Sphinx is free software: you can redistribute it and/or modify
9 | # it under the terms of version 3 of the GNU Lesser General Public
10 | # License as published by the Free Software Foundation.
11 | #
12 | # Sphinx is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU Lesser General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU Lesser General Public
18 | # License along with Sphinx. If not, see
19 | # .
20 |
21 |
22 | # Python 2/3 compatibility
23 | from builtins import bytes
24 |
25 | from . import SphinxException
26 |
27 | # Core Process function -- devoid of any chrome
28 | def sphinx_process(params, secret, header, delta, assoc=b''):
29 | """ The heart of a Sphinx server, that processes incoming messages.
30 | It takes a set of parameters, the secret of the server,
31 | and an incoming message header and body. Optinally some Associated
32 | data may also be passed in to check their integrity.
33 |
34 | """
35 | p = params
36 | group = p.group
37 | alpha, beta, gamma = header
38 |
39 | if params.assoc_len != len(assoc):
40 | raise SphinxException("Associated data length mismatch: expected %s and got %s." % (params.assoc_len, len(assoc)))
41 |
42 | # Check that alpha is in the group
43 | if not group.in_group(alpha):
44 | raise SphinxException("Alpha not in Group.")
45 |
46 | # Compute the shared secret
47 | s = group.expon(alpha, [ secret ])
48 | aes_s = p.get_aes_key(s)
49 |
50 | assert len(beta) == p.max_len - 32
51 |
52 | newgamma = p.mu(p.hmu(aes_s), assoc + beta)
53 | if gamma != newgamma:
54 | raise SphinxException("MAC mismatch.")
55 |
56 | beta_pad = beta + (b"\x00" * (2 * p.max_len))
57 | B = p.xor_rho(p.hrho(aes_s), beta_pad)
58 |
59 | length = B[0]
60 | routing = B[1:1+length]
61 | rest = B[1+length:]
62 |
63 | tag = p.htau(aes_s)
64 | b = p.hb(aes_s)
65 |
66 | alpha_new = group.expon(alpha, [ b ])
67 | alpha = alpha_new
68 |
69 | gamma = rest[:p.k]
70 | beta = rest[p.k:p.k+(p.max_len - 32)]
71 | delta = p.pii(p.hpi(aes_s), delta)
72 |
73 | mac_key = p.hpi(aes_s)
74 | ret = (tag, routing, ((alpha, beta, gamma), delta), mac_key)
75 | return ret
76 |
77 |
--------------------------------------------------------------------------------
/sphinxmix/SphinxParams.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | # Copyright 2011 Ian Goldberg
4 | # Copyright 2016 George Danezis (UCL InfoSec Group)
5 | #
6 | # This file is part of Sphinx.
7 | #
8 | # Sphinx is free software: you can redistribute it and/or modify
9 | # it under the terms of version 3 of the GNU Lesser General Public
10 | # License as published by the Free Software Foundation.
11 | #
12 | # Sphinx is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU Lesser General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU Lesser General Public
18 | # License along with Sphinx. If not, see
19 | # .
20 | #
21 | # The LIONESS implementation and the xcounter CTR mode class are adapted
22 | # from "Experimental implementation of the sphinx cryptographic mix
23 | # packet format by George Danezis".
24 |
25 |
26 | from os import urandom
27 | from hashlib import sha256
28 | import hmac
29 |
30 | from petlib.ec import EcGroup, POINT_CONVERSION_UNCOMPRESSED
31 | from petlib.bn import Bn
32 | from petlib.cipher import Cipher
33 |
34 | # Python 2/3 compatibility
35 | from builtins import bytes
36 |
37 | zero_iv = b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
38 |
39 | class Group_ECC:
40 | "Group operations in ECC"
41 |
42 | def __init__(self, gid=713):
43 | self.G = EcGroup(gid)
44 | self.g = self.G.generator()
45 |
46 | def gensecret(self):
47 | return self.G.order().random()
48 |
49 | def expon(self, base, exp):
50 | x = exp[0]
51 | for f in exp[1:]:
52 | x = x.mod_mul(f, self.G.order())
53 | b = base
54 | return (x * b)
55 |
56 | def expon_base(self, exp):
57 | x = exp[0]
58 | for f in exp[1:]:
59 | x = x.mod_mul(f, self.G.order())
60 | return (x * self.g)
61 |
62 | def makeexp(self, data):
63 | return (Bn.from_binary(data) % self.G.order())
64 |
65 | def in_group(self, alpha):
66 | # All strings of length 32 are in the group, says DJB
67 | b = alpha
68 | return self.G.check_point(b)
69 |
70 | def printable(self, alpha):
71 | return alpha.export(POINT_CONVERSION_UNCOMPRESSED)
72 |
73 |
74 | class SphinxParams:
75 |
76 | def __init__(self, group=None, header_len = 192, body_len = 1024, assoc_len=0, k=16, dest_len=16):
77 | self.aes = Cipher("AES-128-CTR")
78 | self.cbc = Cipher("AES-128-CBC")
79 |
80 | self.assoc_len = assoc_len
81 | self.max_len = header_len
82 |
83 | self.zero_pad = b"\x00" * (2 * self.max_len)
84 |
85 | self.m = body_len
86 | self.k = k
87 | self.dest_len = dest_len
88 |
89 | self.group = group
90 | if not group:
91 | self.group = Group_ECC()
92 |
93 |
94 | # The LIONESS PRP
95 | def aes_ctr(self, k, m, iv = zero_iv):
96 | #k = bytes(k)
97 | #m = bytes(m)
98 | c = self.aes.enc(k, iv).update(m)
99 | return bytes(c)
100 |
101 | # The LIONESS PRP
102 | def aes_cbc_enc(self, k, m, iv = zero_iv):
103 | cipher = self.cbc.enc(k, iv)
104 | cipher.set_padding(False)
105 | c = cipher.update(m)
106 | #c = c + cipher.finalize()
107 | return bytes(c)
108 |
109 | # The LIONESS PRP
110 | def aes_cbc_dec(self, k, m, iv = zero_iv):
111 | cipher = self.cbc.dec(k, iv)
112 | cipher.set_padding(False)
113 | c = cipher.update(m)
114 | #c = c + cipher.finalize()
115 | return bytes(c)
116 |
117 | def lioness_enc(self, key, message):
118 | assert len(key) == self.k
119 | assert len(message) >= self.k * 2
120 |
121 | # Round 1
122 | k1 = self.hash(message[self.k:]+key+b'1')[:self.k]
123 | c = self.aes_ctr(key, message[:self.k], iv = k1)
124 | r1 = c + message[self.k:]
125 |
126 | # Round 2
127 | c = self.aes_ctr(key, r1[self.k:], iv = r1[:self.k])
128 | r2 = r1[:self.k] + c
129 |
130 | # Round 3
131 | k3 = self.hash(r2[self.k:]+key+b'3')[:self.k]
132 | c = self.aes_ctr(key, r2[:self.k], iv = k3)
133 | r3 = c + r2[self.k:]
134 |
135 | # Round 4
136 | c = self.aes_ctr(key, r3[self.k:], r3[:self.k])
137 | r4 = r3[:self.k] + c
138 |
139 | return r4
140 |
141 | def lioness_dec(self, key, message):
142 | assert len(key) == self.k
143 | assert len(message) >= self.k * 2
144 |
145 | r4 = message
146 | r4_short, r4_long = r4[:self.k], r4[self.k:]
147 |
148 | # Round 4
149 | r3_long = self.aes_ctr(key, r4_long, iv = r4_short)
150 | r3_short = r4_short
151 |
152 | # Round 3
153 | k2 = self.hash(r3_long+key+b'3')[:self.k]
154 | r2_short = self.aes_ctr(key, r3_short, iv = k2)
155 | r2_long = r3_long
156 |
157 | # Round 2
158 | r1_long = self.aes_ctr(key, r2_long, iv = r2_short)
159 | r1_short = r2_short
160 |
161 | # Round 1
162 | k0 = self.hash(r1_long+key+b'1')[:self.k]
163 | c = self.aes_ctr(key, r1_short, iv = k0)
164 | r0 = c + r1_long
165 |
166 | return r0
167 |
168 | # AES-CTR operation
169 | def xor_rho(self, key, plain):
170 | assert len(key) == self.k
171 | return self.aes_ctr(key, plain)
172 |
173 |
174 | # The HMAC; key is of length k, output is of length k
175 | def mu(self, key, data):
176 | mac = hmac.new(key, data, digestmod=sha256).digest()[:self.k]
177 | return mac
178 |
179 | # The PRP; key is of length k, data is of length m
180 | def pi(self, key, data):
181 | assert len(key) == self.k
182 | assert len(data) == self.m
183 |
184 | return self.lioness_enc(key, data)
185 |
186 | # The inverse PRP; key is of length k, data is of length m
187 | def pii(self, key, data):
188 | assert len(key) == self.k
189 | assert len(data) == self.m
190 |
191 | return self.lioness_dec(key, data)
192 |
193 | def small_perm(self, key, data):
194 | assert len(data) == self.k
195 | # aes = Cipher("AES-128-CBC")
196 | enc = self.cbc.enc(key, None)
197 | enc.set_padding(False)
198 | c = enc.update(data)
199 | #c += enc.finalize()
200 | return c
201 |
202 | def small_perm_inv(self, key, data):
203 | assert len(data) == self.k
204 | # aes = Cipher("AES-128-CBC")
205 | dec = self.cbc.dec(key, None)
206 | dec.set_padding(False)
207 | c = dec.update(data)
208 | #c += dec.finalize()
209 | return c
210 |
211 | # The various hashes
212 | def hash(self, data):
213 | return sha256(data).digest()
214 |
215 | def get_aes_key(self, s):
216 | group = self.group
217 | return bytes(self.hash(b"aes_key:" + group.printable(s))[:self.k])
218 |
219 | def get_aes_key_all(self, s):
220 | group = self.group
221 | k = self.hash(b"aes_key:" + group.printable(s))[:self.k]
222 |
223 | num = 3 # (hrho, hmu, htau)
224 | iv = b"UltrUltrUltrUltr"
225 | material = self.aes.enc(k, iv).update(b"\x00" * self.k * num)
226 |
227 | return k, [material[self.k*i:self.k*(i+1)] for i in range(num)]
228 |
229 | def derive_key(self, k, flavor):
230 | assert len(k) == len(flavor) == self.k
231 | iv = flavor
232 | m = b"\x00" * self.k
233 | K = self.aes.enc(k, iv).update(m)
234 | return K
235 |
236 | def hb(self, k):
237 | "Compute a hash of alpha and s to use as a blinding factor"
238 | K = self.derive_key(k, b"hbhbhbhbhbhbhbhb")
239 | return self.group.makeexp(K)
240 |
241 | def hrho(self, k):
242 | "Compute a hash of s to use as a key for the PRG rho"
243 | K = self.derive_key(k, b"hrhohrhohrhohrho")
244 | return K
245 |
246 | def hmu(self, k):
247 | "Compute a hash of s to use as a key for the HMAC mu"
248 | K = self.derive_key(k, b"hmu:hmu:hmu:hmu:")
249 | return K
250 |
251 | # def hmu2(self, k):
252 | # "Compute a hash of s to use as a key for the permutation mu2"
253 | # K = self.derive_key(k, b"hmu2:hmu2:hmu2:h")
254 | # return K
255 |
256 |
257 | def hpi(self, k):
258 | "Compute a hash of s to use as a key for the PRP pi"
259 | K = self.derive_key(k, b"hpi:hpi:hpi:hpi:")
260 | return K
261 |
262 | def htau(self, k):
263 | "Compute a hash of s to use to see if we've seen s before"
264 | K = self.derive_key(k, b"htauhtauhtauhtau")
265 | return K
266 |
267 | def h_body_K(self, k):
268 | "The Ultrix key to protect the user data."
269 | K = self.derive_key(k, b"UbodUbodUbodUbod")
270 | return K
271 |
272 | def h_root_K(self, k):
273 | "The Ultrix key to protect the root key."
274 | K = self.derive_key(k, b"UrooUrooUrooUroo")
275 | return K
276 |
277 | def derive_user_keys(self, k, iv, number=2):
278 | material = self.aes.enc(k, iv).update(b"\x00" * self.k * number)
279 | st_ranges = range(0, self.k * number, self.k)
280 |
281 |
282 | return [ material[st:st+self.k] for st in st_ranges ]
283 |
284 | # All tests
285 |
286 | def test_group():
287 | G = Group_ECC()
288 | sec1 = G.gensecret()
289 | sec2 = G.gensecret()
290 | gen = G.g
291 |
292 | assert G.expon(G.expon(gen, [ sec1 ]), [ sec2 ]) == G.expon(G.expon(gen, [ sec2 ]), [ sec1 ])
293 | assert G.in_group(G.expon(gen, [ sec1 ]))
294 |
295 | def test_params():
296 | # Test Init
297 | params = SphinxParams()
298 |
299 | # Test Lioness
300 | k = b"A" * 16
301 | m = b"ARG"* 16
302 |
303 | c = params.lioness_enc(k,m)
304 | m2 = params.lioness_dec(k, c)
305 | assert m == m2
306 |
307 | # Test CTR
308 | k = urandom(16)
309 | c = params.aes_ctr(k, b"Hello World!")
310 | assert params.aes_ctr(k, c) == b"Hello World!"
311 |
312 | c = params.small_perm(b"\x00"*16, b"\x00"*16)
313 | c2 = params.small_perm_inv(b"\x00"*16, c)
314 | assert c2 == b"\x00"*16
315 |
316 | plain = b"Bob"
317 | k = urandom(16)
318 | c = params.aes_ctr(k, plain)
319 | p = params.aes_ctr(k, c)
320 | assert p == b"Bob"
321 |
322 | plain = b"ACB" * 16
323 | k = urandom(16)
324 | iv = urandom(16)
325 | ctxt = params.aes_cbc_enc(k, plain)
326 | assert len(ctxt) == len(plain)
327 | ptxt = params.aes_cbc_dec(k, ctxt)
328 | assert ptxt == plain
329 |
--------------------------------------------------------------------------------
/sphinxmix/SphinxParamsC25519.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | # Copyright 2011 Ian Goldberg
4 | # Copyright 2016 George Danezis (UCL InfoSec Group)
5 | #
6 | # This file is part of Sphinx.
7 | #
8 | # Sphinx is free software: you can redistribute it and/or modify
9 | # it under the terms of version 3 of the GNU Lesser General Public
10 | # License as published by the Free Software Foundation.
11 | #
12 | # Sphinx is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU Lesser General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU Lesser General Public
18 | # License along with Sphinx. If not, see
19 | # .
20 | #
21 | # The LIONESS implementation and the xcounter CTR mode class are adapted
22 | # from "Experimental implementation of the sphinx cryptographic mix
23 | # packet format by George Danezis".
24 |
25 |
26 | from os import urandom
27 | from hashlib import sha256
28 | import hmac
29 |
30 | from petlib.ec import EcGroup, EcPt, POINT_CONVERSION_UNCOMPRESSED
31 | from petlib.bn import Bn
32 | from petlib.cipher import Cipher
33 |
34 | # Python 2/3 compatibility
35 | from builtins import bytes
36 |
37 | from nacl.bindings import crypto_scalarmult_base, crypto_scalarmult
38 |
39 | def _expand32(K):
40 | return (K+b"\x00"*32)[:32]
41 |
42 | class Group_C25519:
43 | "Group operations using Curve 25519"
44 |
45 | def __init__(self):
46 | pass
47 |
48 | def gensecret(self):
49 | return urandom(32)
50 |
51 | def expon(self, base, exp):
52 | for f in exp:
53 | base = crypto_scalarmult(_expand32(f), base)
54 | return base
55 |
56 | def expon_base(self, exp):
57 | assert len(exp) > 0
58 | base = crypto_scalarmult_base(_expand32(exp[0]))
59 | for f in exp[1:]:
60 | base = crypto_scalarmult(_expand32(f), base)
61 | return base
62 |
63 |
64 | def makeexp(self, data):
65 | return data[:32]
66 |
67 | def in_group(self, alpha):
68 | # All strings of length 32 are in the group, says DJB
69 | return len(alpha) == 32
70 |
71 | def printable(self, alpha):
72 | return alpha
73 |
74 | def test_commut():
75 | G = Group_C25519()
76 | x0, x1, x2 = [G.gensecret() for _ in range(3) ]
77 | x2 = x2[:16]
78 |
79 | assert G.expon_base([x0, x1, x2]) == G.expon_base([x2, x1, x0])
80 |
81 | assert G.expon_base([x0, x1, x2]) == G.expon( G.expon_base([x0, x1]), [ x2 ])
82 | assert G.expon_base([x0, x2]) == G.expon( G.expon_base([x0]), [ x2 ])
--------------------------------------------------------------------------------
/sphinxmix/UltrixClient.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | # Copyright 2011 Ian Goldberg
4 | # Copyright 2016 George Danezis (UCL InfoSec Group)
5 | #
6 | # This file is part of Sphinx.
7 | #
8 | # Sphinx is free software: you can redistribute it and/or modify
9 | # it under the terms of version 3 of the GNU Lesser General Public
10 | # License as published by the Free Software Foundation.
11 | #
12 | # Sphinx is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU Lesser General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU Lesser General Public
18 | # License along with Sphinx. If not, see
19 | # .
20 |
21 |
22 | from os import urandom
23 | from collections import namedtuple
24 | from struct import pack
25 |
26 | from petlib.pack import encode, decode
27 |
28 |
29 | from .SphinxParams import SphinxParams
30 | from . import SphinxException
31 |
32 | from .SphinxClient import Relay_flag, Dest_flag, Surb_flag, pki_entry
33 | from .SphinxClient import pad_body, unpad_body
34 | from .SphinxClient import Nenc, Route_pack, PFdecode, rand_subset
35 | from .SphinxClient import pack_message, unpack_message
36 |
37 |
38 | ultrix_hdr_record = namedtuple("ultrix_hdr_record", ["alpha", "s", "b", "aes", "hrho", "hmu", "htau"])
39 |
40 |
41 | def create_header(params, nodelist, keys, assoc=None, secrets = None, gamma=None, dest_key = None):
42 | """ Internal function, creating a Ultrix header."""
43 |
44 | p = params
45 | max_len = p.max_len
46 | group = p.group
47 |
48 | node_meta = [pack("b", len(n)) + n for n in nodelist]
49 | nodelist = nodelist[:-1] # remove the final destination.
50 | nu = len(nodelist)
51 |
52 | if not params.assoc_len > 0:
53 | assoc = [b''] * len(nodelist)
54 | else:
55 | assert assoc != None
56 |
57 | assert len(assoc) == len(nodelist)
58 | for assoc_data in assoc:
59 | assert len(assoc_data) == params.assoc_len
60 |
61 | # Accept external secrets too -- derandomize
62 | blind_factors = secrets
63 | if not secrets:
64 | x = group.gensecret()
65 | blind_factors = [ x ]
66 |
67 | if not gamma:
68 | gamma = urandom(16)
69 |
70 | if not dest_key:
71 | dest_key = urandom(p.k)
72 |
73 | asbtuples = []
74 |
75 | alpha0 = group.expon_base(blind_factors[-1:])
76 | for k in keys:
77 | alpha = alpha0
78 | s = group.expon(k, blind_factors)
79 | aes_s = p.get_aes_key(s)
80 | (hrho, hmu, htau, b_factor) = p.derive_user_keys(k=aes_s, iv = b"_master_________", number = 4)
81 | b = p.group.makeexp(b_factor)
82 |
83 | #b = p.hb(aes_s)
84 | blind_factors += [ b ]
85 |
86 | hr = ultrix_hdr_record(alpha, s, b, aes_s, hrho, hmu, htau)
87 | asbtuples.append(hr)
88 |
89 | alpha0 = group.expon(alpha0, [b])
90 |
91 | # Compute the filler strings
92 | phi = b''
93 | min_len = (max_len - 32)
94 | for i in range(1,nu):
95 |
96 | plain = phi + (b"\x00" * (len(node_meta[i])))
97 | phi = p.xor_rho(asbtuples[i-1].hrho, (b"\x00"*min_len)+plain)
98 | phi = phi[min_len:]
99 |
100 | min_len -= len(node_meta[i])
101 |
102 | assert len(phi) == sum(map(len, node_meta[1:-1]))
103 |
104 | # Compute the (beta, gamma) tuples
105 | len_meta = sum(map(len, node_meta[1:]))
106 | random_pad_len = (max_len - 32) - len_meta
107 |
108 | if random_pad_len < 0:
109 | raise SphinxException("Insufficient space routing info: missing %s bytes" % (abs(random_pad_len)))
110 |
111 | beta = node_meta[-1] + urandom(random_pad_len)
112 | beta = p.xor_rho(asbtuples[nu-1].hrho, beta) + phi
113 |
114 | beta_all = [ beta ]
115 | for i in range(nu-2, -1, -1):
116 | assert len(beta) == (max_len - 32)
117 | node_id = node_meta[i+1]
118 |
119 | plain_beta_len = (max_len - 32) - len(node_id)
120 |
121 | plain = node_id + beta[:plain_beta_len]
122 | beta = p.xor_rho(asbtuples[i].hrho, plain)
123 | beta_all = [ beta ] + beta_all
124 | assert len(beta) == (max_len - 32)
125 |
126 | # Compute the cummulative MAC.
127 |
128 | original_gamma = gamma
129 | root_keys = []
130 | new_keys = []
131 | for beta_i, k, assoc_data in zip(beta_all, asbtuples, assoc):
132 | xgamma = gamma
133 | round_mac_key = k.hmu
134 | inner_mac = p.mu(round_mac_key, assoc_data + xgamma + beta_i)
135 |
136 | root_K, body_K, gamma = p.derive_user_keys(inner_mac, b"_fragile________", 3)
137 |
138 | root_keys += [ root_K ]
139 | new_keys += [ body_K ]
140 |
141 | # Encrypt the dest key
142 | assert len(root_keys) == len(asbtuples)
143 | for gK in reversed(root_keys):
144 | dest_key = p.small_perm_inv(gK, dest_key)
145 |
146 | assert len(beta) == (max_len - 32)
147 | return (asbtuples[0].alpha, beta, original_gamma, dest_key), new_keys
148 |
149 |
150 | def create_forward_message(params, nodelist, keys, dest, msg, assoc=None):
151 | """Creates a forward Sphix message, ready to be processed by a first mix.
152 |
153 | It takes as parameters a node list of mix information, that will be provided to each mix, forming the path of the message;
154 | a list of public keys of all intermediate mixes; a destination and a message; and optinally an array of associated data (byte arrays)."""
155 |
156 | assert len(dest) <= params.dest_len
157 |
158 | p = params
159 | nu = len(nodelist)
160 | assert 0 < len(dest) < 128
161 | assert p.k + 1 + len(dest) + len(msg) < p.m
162 |
163 | # Compute the header and the secrets
164 | dest_key = urandom(16)
165 | dest_inner_key = params.derive_key(dest_key, b"dest_inner______")
166 | body_inner_key = params.derive_key(dest_key, b"body_inner______")
167 |
168 | # TODO: Encure that changing the body destroys the dest_key.
169 |
170 | enc_dest = p.xor_rho(dest_inner_key, dest)
171 | assert len(enc_dest) == len(dest)
172 |
173 | final = [ Route_pack((Dest_flag, enc_dest)) ]
174 | header, secrets = create_header(params, nodelist + final, keys, assoc, dest_key = dest_key)
175 |
176 | payload = pad_body(p.m - p.k, encode(msg))
177 | mac = p.mu(secrets[nu-1], payload)
178 | body = mac + payload
179 |
180 | # Compute the delta values
181 | delta = p.pi(body_inner_key, body)
182 | delta = p.aes_cbc_dec(secrets[nu-1], delta)
183 | for i in range(nu-2, -1, -1):
184 | delta = p.aes_cbc_dec(secrets[i], delta)
185 |
186 | return header, delta
187 |
188 | def create_surb(params, nodelist, keys, dest, assoc=None):
189 | """Creates a Ultrix single use reply block (SURB) using a set of parameters;
190 | a sequence of mix identifiers; a pki mapping names of mixes to keys; and a final
191 | destination. An array of associated data, for each mix on the path, may optionally
192 | be passed in.
193 |
194 | Returns:
195 | - A triplet (surbid, surbkeytuple, nymtuple). Where the surbid can be
196 | used as an index to store the secrets surbkeytuple; nymtuple is the actual
197 | SURB that needs to be sent to the receiver.
198 |
199 | """
200 | p = params
201 | nu = len(nodelist)
202 | xid = urandom(p.k)
203 |
204 | # Compute the header and the secrets
205 |
206 | enc_dest = params.xor_rho(xid, dest)
207 |
208 | final = [ Route_pack((Surb_flag, enc_dest)) ]
209 | header, secrets = create_header(params, nodelist + final, keys, assoc, dest_key = xid )
210 |
211 | ktilde = urandom(p.k)
212 | keytuple = [ktilde]
213 | keytuple.extend( secrets)
214 | return xid, keytuple, (nodelist[0], header, ktilde)
215 |
216 | def package_surb(params, nymtuple, message):
217 | """Packages a message to be sent with a SURB. The message has to be bytes,
218 | and the nymtuple is the structure returned by the create_surb call.
219 |
220 | Returns a header and a body to pass to the first mix.
221 | """
222 | n0, header0, ktilde = nymtuple
223 |
224 | message = pad_body(params.m - params.k, message)
225 | mac = params.mu(ktilde, message)
226 | body = params.xor_rho(ktilde, mac + message )
227 | return (header0, body)
228 |
229 |
230 | def receive_forward(params, header, mac_key, routing, delta):
231 | """ Decodes the body of a forward message, and checks its MAC tag."""
232 |
233 | _, _, _, dest_key = header
234 | _, dest = routing
235 |
236 | dest_inner_key = params.derive_key(dest_key, b"dest_inner______")
237 | body_inner_key = params.derive_key(dest_key, b"body_inner______")
238 |
239 | # TODO: Encure that changing the body destroys the dest_key.
240 |
241 | dest = params.xor_rho(dest_inner_key, dest)
242 | delta = params.pii(body_inner_key, delta)
243 |
244 | if delta[:params.k] != params.mu(mac_key, delta[params.k:]):
245 | raise SphinxException("Modified Body")
246 |
247 | delta = unpad_body(delta[params.k:])
248 | return dest, decode(delta)
249 |
250 | def receive_surb(params, keytuple, delta):
251 | """Processes a SURB body to extract the reply. The keytuple was provided at the time of
252 | SURB creation, and can be indexed by the SURB id, which is also returned to the receiving user.
253 |
254 | Returns the decoded message.
255 | """
256 | p = params
257 |
258 | ktilde = keytuple.pop(0)
259 | nu = len(keytuple)
260 | for i in range(nu-1, -1, -1):
261 | delta = p.aes_cbc_dec(keytuple[i], delta)
262 | delta = p.xor_rho(ktilde, delta)
263 |
264 | if delta[:p.k] == p.mu(ktilde, delta[p.k:]):
265 | msg = unpad_body(delta[p.k:])
266 | else:
267 | raise SphinxException("Modified SURB Body")
268 |
269 | return msg
270 |
271 | def decode_surb(params, header, enc_dest):
272 | """ Decode the destination address of the SURB. """
273 | (_, _, _, xid) = header
274 | dest = params.xor_rho(xid, enc_dest)
275 | return dest
276 |
277 | # TESTS
278 |
279 | from nacl.bindings import crypto_scalarmult_base
280 |
281 |
282 | def profile_ultrix_c25519(rep=100, payload_size=1024 * 10):
283 | r = 5
284 |
285 | from .SphinxParamsC25519 import Group_C25519
286 | from .UltrixNode import ultrix_process
287 |
288 | group = Group_C25519()
289 | params = SphinxParams(group=group, header_len = 32+50, body_len=payload_size, assoc_len=4)
290 |
291 | pkiPriv = {}
292 | pkiPub = {}
293 |
294 | for i in range(10):
295 | nid = pack("b", i)
296 | x = params.group.gensecret()
297 | y = crypto_scalarmult_base(x)
298 | pkiPriv[nid] = pki_entry(nid, x, y)
299 | pkiPub[nid] = pki_entry(nid, None, y)
300 |
301 |
302 | # The simplest path selection algorithm and message packaging
303 | use_nodes = rand_subset(pkiPub.keys(), r)
304 | nodes_routing = list(map(Nenc, use_nodes))
305 | node_keys = [pkiPub[n].y for n in use_nodes]
306 |
307 | assoc = [b"XXXX"] * len(nodes_routing)
308 |
309 | import time
310 | ta = time.time()
311 |
312 |
313 | t0 = time.time()
314 | for _ in range(rep):
315 | header, delta = create_forward_message(params, nodes_routing, node_keys, b"dest", b"this is a test", assoc)
316 | t1 = time.time()
317 | print("Time per mix encoding: %.2fms" % ((t1-t0)*1000.0/rep))
318 |
319 |
320 | t0 = time.time()
321 | for _ in range(rep):
322 | x = pkiPriv[use_nodes[0]].x
323 | ultrix_process(params, x, header, delta, b"XXXX")
324 | t1 = time.time()
325 | print("Time per mix processing: %.2fms" % ((t1-t0)*1000.0/rep))
326 |
327 | tb = time.time()
328 |
329 | print("Total (for %d repeats): %.2fms" % (rep, (tb-ta)*1000.0))
330 |
331 | def test_ultrix_c25519(rep=100, payload_size=1024 * 10):
332 | r = 5
333 | from .SphinxParamsC25519 import Group_C25519
334 |
335 | group = Group_C25519()
336 | params = SphinxParams(group=group, header_len = 32+50, body_len=payload_size, assoc_len=4)
337 |
338 | pkiPriv = {}
339 | pkiPub = {}
340 |
341 | for i in range(10):
342 | nid = pack("b", i)
343 | x = params.group.gensecret()
344 | y = crypto_scalarmult_base(x)
345 | pkiPriv[nid] = pki_entry(nid, x, y)
346 | pkiPub[nid] = pki_entry(nid, None, y)
347 |
348 |
349 | # The simplest path selection algorithm and message packaging
350 | use_nodes = rand_subset(pkiPub.keys(), r)
351 | nodes_routing = list(map(Nenc, use_nodes))
352 | node_keys = [pkiPub[n].y for n in use_nodes]
353 | assoc = [b"XXXX"] * len(nodes_routing)
354 |
355 | print()
356 | import time
357 | t0 = time.time()
358 | for _ in range(rep):
359 | header, delta = create_forward_message(params, nodes_routing, node_keys, b"dest", b"this is a test", assoc)
360 | t1 = time.time()
361 | print("Time per mix encoding: %.2fms" % ((t1-t0)*1000.0/rep))
362 | T_package = (t1-t0)/rep
363 |
364 | from .UltrixNode import ultrix_process
365 |
366 | t0 = time.time()
367 | for _ in range(rep):
368 | x = pkiPriv[use_nodes[0]].x
369 | ultrix_process(params, x, header, delta, b"XXXX")
370 | t1 = time.time()
371 | print("Time per mix processing: %.2fms" % ((t1-t0)*1000.0/rep))
372 | T_process = (t1-t0)/rep
373 |
374 | return T_package, T_process
375 |
376 | def test_minimal_ultrix():
377 | r = 5
378 | params = SphinxParams(header_len = 32+4*8+32, assoc_len=4)
379 |
380 | # The minimal PKI involves names of nodes and keys
381 |
382 | pkiPriv = {}
383 | pkiPub = {}
384 |
385 | for i in range(10):
386 | nid = pack("b", i) # Nenc(params, bytes([i]))
387 | x = params.group.gensecret()
388 | y = params.group.expon(params.group.g, [ x ])
389 | pkiPriv[nid] = pki_entry(nid, x, y)
390 | pkiPub[nid] = pki_entry(nid, None, y)
391 |
392 | # The simplest path selection algorithm and message packaging
393 | use_nodes = rand_subset(pkiPub.keys(), r)
394 | nodes_routing = list(map(Nenc, use_nodes))
395 | node_keys = [pkiPub[n].y for n in use_nodes]
396 | dest = b"bob"
397 | message = b"this is a test"
398 | X = [b'A', b'B', b'C', b'D', b'E'] * 2
399 | assoc = [b"XXX" + X[i] for i in range( len(nodes_routing) )]
400 |
401 | assoc_copy = assoc[:]
402 |
403 |
404 | header, delta = create_forward_message(params, nodes_routing, node_keys, dest, message, assoc=assoc)
405 |
406 | # Test encoding and decoding
407 |
408 | bin_message = pack_message(params, (header, delta))
409 | param_dict = { (params.max_len, params.m):params }
410 |
411 | px, (header1, delta1) = unpack_message(param_dict, bin_message)
412 | assert px == params
413 | assert header == tuple(header1)
414 | assert delta == delta1
415 |
416 | # Process message by the sequence of mixes
417 | from .UltrixNode import ultrix_process
418 | x = pkiPriv[use_nodes[0]].x
419 |
420 | i = 0
421 | while True:
422 | assoc_data = assoc_copy.pop(0)
423 |
424 | ret = ultrix_process(params, x, header, delta, assoc=assoc_data)
425 | (tag, B, (header, delta), mac_key) = ret
426 | routing = PFdecode(params, B)
427 |
428 | print("round %d" % i)
429 | i += 1
430 |
431 | # print("Type: %s" % typex)
432 | if routing[0] == Relay_flag:
433 | addr = routing[1]
434 | x = pkiPriv[addr].x
435 | elif routing[0] == Dest_flag:
436 | assert len(routing) == 2
437 | # assert delta[:16] == b"\x00" * params.k
438 | dec_dest, dec_msg = receive_forward(params, header, mac_key, routing, delta)
439 | assert dec_dest == dest
440 | assert dec_msg == message
441 |
442 | break
443 | else:
444 | print("Error")
445 | assert False
446 | break
447 |
448 | # Test the nym creation
449 | surbid, surbkeytuple, nymtuple = create_surb(params, nodes_routing, node_keys, b"myself", assoc=assoc)
450 |
451 | message = b"This is a reply"
452 | header, delta = package_surb(params, nymtuple, message)
453 |
454 | x = pkiPriv[use_nodes[0]].x
455 | assoc_copy = assoc[:]
456 |
457 | while True:
458 | assoc_data = assoc_copy.pop(0)
459 |
460 | ret = ultrix_process(params, x, header, delta, assoc=assoc_data)
461 | (tag, B, (header, delta), mac_key) = ret
462 | routing = PFdecode(params, B)
463 |
464 | if routing[0] == Relay_flag:
465 | flag, addr = routing
466 | x = pkiPriv[addr].x
467 | elif routing[0] == Surb_flag:
468 | flag, dest = routing
469 | dest = decode_surb(params, header, dest)
470 | assert dest == b"myself"
471 | myid = header[-1]
472 | assert myid == surbid
473 | break
474 |
475 | received = receive_surb(params, surbkeytuple, delta)
476 | assert received == message
477 |
--------------------------------------------------------------------------------
/sphinxmix/UltrixNode.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | # Copyright 2011 Ian Goldberg
4 | # Copyright 2017 George Danezis (UCL InfoSec Group)
5 | #
6 | # This file is part of Sphinx.
7 | #
8 | # Sphinx is free software: you can redistribute it and/or modify
9 | # it under the terms of version 3 of the GNU Lesser General Public
10 | # License as published by the Free Software Foundation.
11 | #
12 | # Sphinx is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU Lesser General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU Lesser General Public
18 | # License along with Sphinx. If not, see
19 | # .
20 |
21 |
22 | from . import SphinxException
23 |
24 | _master = b"_master_________"
25 | _fragile = b"_fragile________"
26 |
27 | # Core Process function -- devoid of any chrome
28 | def ultrix_process(params, secret, header, delta, assoc=b''):
29 | """ The heart of a Ultrix server, that processes incoming messages.
30 | It takes a set of parameters, the secret of the server,
31 | and an incoming message header and body. Optinally some Associated
32 | data may also be passed in to check their integrity.
33 |
34 | """
35 | p = params
36 | alpha, beta, gamma, dest_key = header
37 |
38 | if params.assoc_len != len(assoc):
39 | raise SphinxException("Associated data length mismatch: expected %s and got %s." % (params.assoc_len, len(assoc)))
40 |
41 | # Check that alpha is in the group
42 | if not p.group.in_group(alpha):
43 | raise SphinxException("Alpha not in Group.")
44 |
45 | # Compute the shared secret
46 | s = p.group.expon(alpha, [ secret ])
47 | aes_s = p.get_aes_key(s)
48 | (header_enc_key, round_mac_key, tag, b_factor) = p.derive_user_keys(k=aes_s, iv = _master, number = 4)
49 | b = p.group.makeexp(b_factor)
50 |
51 | assert len(beta) == p.max_len - 32
52 |
53 | # Compute the secrets based on the header too
54 | inner_mac = p.mu(round_mac_key, assoc + gamma + beta)
55 | root_K, body_K, gamma = p.derive_user_keys(k=inner_mac, iv = _fragile, number = 3)
56 |
57 | # Decrypt the header
58 | beta_pad = beta + p.zero_pad
59 | B = p.xor_rho(header_enc_key, beta_pad)
60 |
61 | length = B[0]
62 | routing = B[1:1+length]
63 | rest = B[1+length:]
64 |
65 | # Recode the alpha and beta
66 | alpha = p.group.expon(alpha, [ b ])
67 | beta = rest[:(p.max_len - 32)]
68 |
69 | # Decode the delta
70 | dest_key = p.small_perm(root_K, dest_key)
71 | delta = p.aes_cbc_enc(body_K, delta)
72 |
73 | # Package packet and keys
74 | ret = (tag, routing, ((alpha, beta, gamma, dest_key), delta), body_K)
75 | return ret
76 |
77 |
--------------------------------------------------------------------------------
/sphinxmix/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """The ``sphinxmix`` package implements the Sphinx mix packet format core cryptographic functions.
3 |
4 | The paper describing sphinx may be found here:
5 |
6 | * George Danezis and Ian Goldberg. Sphinx: A Compact and Provably Secure Mix Format. IEEE Symposium on Security and Privacy 2009. [`link `_]
7 |
8 |
9 | All the ``sphinxmix`` cryptography is encapsulated and within a ``SphinxParams`` object that
10 | is used by all subsequent functions. To make ``sphinxmix`` use different cryptographic
11 | primitives simply extend this class, or re-implement it. The default cryptographic primitives
12 | are ``NIST/SEGS-p224`` curves, ``AES`` and ``SHA256``.
13 |
14 | Sending Sphinx messages
15 | -----------------------
16 |
17 | To package or process sphinx messages create a new ``SphinxParams`` object:
18 |
19 | >>> # Instantiate a the crypto parameters for Sphinx.
20 | >>> from sphinxmix.SphinxParams import SphinxParams
21 | >>> params = SphinxParams()
22 |
23 | The ``sphinxmix`` package requires some rudimentary Public Key Information: mix nodes need
24 | an identifier created by ``Nenc`` and the PKI consists of a dictionary mapping node names
25 | to ``pki_entry`` records. Those include secret keys (derived using ``gensecret``) and public
26 | keys (derived using ``expon``).
27 |
28 | >>> # The minimal PKI involves names of nodes and keys
29 | >>> from sphinxmix.SphinxClient import pki_entry, Nenc
30 | >>> pkiPriv = {}
31 | >>> pkiPub = {}
32 | >>> for i in range(10):
33 | ... nid = i
34 | ... x = params.group.gensecret()
35 | ... y = params.group.expon(params.group.g, [ x ])
36 | ... pkiPriv[nid] = pki_entry(nid, x, y)
37 | ... pkiPub[nid] = pki_entry(nid, None, y)
38 |
39 | A client may package a message using the Sphinx format to relay over a number of mix servers.
40 | The function ``rand_subset`` may be used to select a random number of node identifiers; the function
41 | ``create_forward_message`` can then be used to package the message, ready to be sent to the
42 | first mix. Note both destination and message need to be ``bytes``.
43 |
44 | >>> # The simplest path selection algorithm and message packaging
45 | >>> from sphinxmix.SphinxClient import rand_subset, \\
46 | ... create_forward_message
47 | >>> use_nodes = rand_subset(pkiPub.keys(), 5)
48 | >>> nodes_routing = list(map(Nenc, use_nodes))
49 | >>> keys_nodes = [pkiPub[n].y for n in use_nodes]
50 | >>> dest = b"bob"
51 | >>> message = b"this is a test"
52 | >>> header, delta = create_forward_message(params, nodes_routing, \\
53 | ... keys_nodes, dest, message)
54 |
55 | The client may specify any information in the ``nodes_routing`` list, that will
56 | be passed to intermediate mixes. At a minimum this should include information about
57 | the next mix.
58 |
59 | Processing Sphinx messages at a mix
60 | -----------------------------------
61 |
62 | The heart of a Sphinx mix server is the ``sphinx_process`` function, that takes the server
63 | secret and decodes incoming messages. In this example the message encode above, is decoded
64 | by the sequence of mixes.
65 |
66 | >>> # Process message by the sequence of mixes
67 | >>> from sphinxmix.SphinxClient import PFdecode, Relay_flag, Dest_flag, Surb_flag, receive_forward
68 | >>> from sphinxmix.SphinxNode import sphinx_process
69 | >>> x = pkiPriv[use_nodes[0]].x
70 | >>> while True:
71 | ... ret = sphinx_process(params, x, header, delta)
72 | ... (tag, info, (header, delta), mac_key) = ret
73 | ... routing = PFdecode(params, info)
74 | ... if routing[0] == Relay_flag:
75 | ... flag, addr = routing
76 | ... x = pkiPriv[addr].x
77 | ... elif routing[0] == Dest_flag:
78 | ... assert receive_forward(params, mac_key, delta) == [dest, message]
79 | ... break
80 |
81 | It is the responsibility of a mix to record ``tags`` of messages to prevent
82 | replay attacks. The ``PFdecode`` function may be used to recover routing Information
83 | including the next mix, or any other user specified information.
84 |
85 | Single use reply Blocks
86 | -----------------------
87 |
88 | A facility provided by Sphinx is the creation and use of Single Use Reply Blocks (SURB)
89 | to route messages back to an anonymous receipient. First a receiver needs to create
90 | a SURB using ``create_surb`` and passes on the ``nymtuple`` structure to the sender, and
91 | storing ``surbkeytuple`` keyed by the identifier ``surbid``:
92 |
93 | >>> from sphinxmix.SphinxClient import create_surb, package_surb
94 | >>> surbid, surbkeytuple, nymtuple = create_surb(params, nodes_routing, keys_nodes, b"myself")
95 |
96 | Using the ``nymtuple`` a sender can package a message to be sent through the network,
97 | starting at the ``nymtuple[0]`` router:
98 |
99 | >>> message = b"This is a reply"
100 | >>> header, delta = package_surb(params, nymtuple, message)
101 |
102 | The network processes the SURB as any other message, until it is received
103 | by the last mix in the path:
104 |
105 | >>> x = pkiPriv[use_nodes[0]].x
106 | >>> while True:
107 | ... ret = sphinx_process(params, x, header, delta)
108 | ... (tag, B, (header, delta), mac_key) = ret
109 | ... routing = PFdecode(params, B)
110 | ...
111 | ... if routing[0] == Relay_flag:
112 | ... flag, addr = routing
113 | ... x = pkiPriv[addr].x
114 | ... elif routing[0] == Surb_flag:
115 | ... flag, dest, myid = routing
116 | ... break
117 |
118 | The final mix server must sent the ``myid`` and ``delta`` to the destination
119 | ``dest``, where it may be decoded using the ``surbkeytuple``.
120 |
121 | >>> from sphinxmix.SphinxClient import receive_surb
122 | >>> received = receive_surb(params, surbkeytuple, delta)
123 | >>> assert received == message
124 |
125 | Embedding arbitrary information for mixes
126 | -----------------------------------------
127 |
128 | A sender may embed arbitrary information to mix nodes, as demonstrated
129 | by embedding ``b'info'`` to each mix, and ``b'final_info'`` to the final
130 | mix:
131 |
132 | >>> use_nodes = rand_subset(pkiPub.keys(), 5)
133 | >>> nodes_routing = [Nenc((n, b'info')) for n in use_nodes]
134 | >>> keys_nodes = [pkiPub[n].y for n in use_nodes]
135 | >>> dest = (b"bob", b"final_info")
136 | >>> message = b"this is a test"
137 | >>> header, delta = create_forward_message(params, nodes_routing, \\
138 | ... keys_nodes, dest, message)
139 |
140 | Mixes decode the arbitrary structure passed by the clients, and can interpret
141 | it to implement more complex mixing strategies:
142 |
143 | >>> x = pkiPriv[use_nodes[0]].x
144 | >>> while True:
145 | ... ret = sphinx_process(params, x, header, delta)
146 | ... (tag, info, (header, delta), mac_key) = ret
147 | ... routing = PFdecode(params, info)
148 | ... if routing[0] == Relay_flag:
149 | ... flag, (addr, additional_info) = routing
150 | ... assert additional_info == b'info'
151 | ... x = pkiPriv[addr].x
152 | ... elif routing[0] == Dest_flag:
153 | ... [[dest, additional_info], msg] = receive_forward(params, mac_key, delta)
154 | ... assert additional_info == b'final_info'
155 | ... assert dest == b'bob'
156 | ... break
157 |
158 |
159 | Packaging mix messages to byte strings:
160 | ---------------------------------------
161 |
162 | The `sphinxmix` package provides functions `pack_message` and `unpack_message` to
163 | serialize and deserialize mix messages using `msgpack`. Some meta-data about the
164 | parameter length are passed along the message any may be used to select an appropriate
165 | parameter environment for the decoding of the message.
166 |
167 | >>> from sphinxmix.SphinxClient import pack_message, unpack_message
168 | >>> bin_message = pack_message(params, (header, delta))
169 | >>> param_dict = { (params.max_len, params.m):params }
170 | >>> px, (header1, delta1) = unpack_message(param_dict, bin_message)
171 |
172 |
173 | """
174 |
175 | VERSION = "0.0.7"
176 |
177 | class SphinxException(Exception):
178 | pass
--------------------------------------------------------------------------------
/timings.py:
--------------------------------------------------------------------------------
1 | # Run as: python -OO -m cProfile -s tottime timings.py > prof.txt
2 |
3 | if __name__ == "__main__":
4 | from sphinxmix.SphinxClient import test_timing
5 | test_timing()
--------------------------------------------------------------------------------
/timings_ultrix.py:
--------------------------------------------------------------------------------
1 | # Run as: python -OO -m cProfile -s tottime timings_ultrix.py > prof.txt
2 |
3 | if __name__ == "__main__":
4 | from sphinxmix.UltrixClient import profile_ultrix_c25519
5 |
6 | # profile = LineProfiler(profile_ultrix_c25519)
7 |
8 | deb = False
9 | if deb:
10 | import cProfile, pstats
11 | pr = cProfile.Profile()
12 | pr.enable()
13 |
14 | profile_ultrix_c25519(rep=1000, payload_size=1024)
15 |
16 | if deb:
17 | pr.disable()
18 | ps = pstats.Stats(pr).strip_dirs().sort_stats('time')
19 | ps.print_callers()
20 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | # Tox (http://tox.testrun.org/) is a tool for running tests
2 | # in multiple virtualenvs. This configuration file will run the
3 | # test suite on all supported python versions. To use it, "pip install tox"
4 | # and then run "tox" from this directory.
5 |
6 | [tox]
7 | envlist = py27, py35
8 |
9 | [testenv]
10 | commands =
11 | py.test -sv --doctest-modules sphinxmix/__init__.py sphinxmix/SphinxClient.py sphinxmix/SphinxParams.py sphinxmix/SphinxNode.py sphinxmix/UltrixNode.py sphinxmix/UltrixClient.py
12 |
13 | [testenv:py27]
14 | commands =
15 | py.test -sv --doctest-modules sphinxmix/__init__.py sphinxmix/SphinxClient.py sphinxmix/SphinxParams.py sphinxmix/SphinxNode.py sphinxmix/UltrixNode.py sphinxmix/UltrixClient.py
16 | coverage run --source=sphinxmix setup.py test
17 |
18 | deps =
19 | -r{toxinidir}/requirements.txt
20 |
--------------------------------------------------------------------------------