├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── crypter.py
├── ctSESAM.py
├── docs
├── Makefile
├── conf.py
├── index.rst
├── make.bat
├── passwordGeneration.rst
├── settings.rst
├── synchronisation.rst
└── tools.rst
├── domain_extractor.py
├── kgk_manager.py
├── packer.py
├── password_generator.py
├── password_setting.py
├── password_settings_manager.py
├── preference_manager.py
├── requirements.txt
├── setup.py
├── sync.py
├── sync_manager.py
└── tests
├── __init__.py
├── test_Crypter.py
├── test_KgkManager.py
├── test_Packer.py
├── test_PasswordGenerator.py
├── test_PasswordSetting.py
├── test_PasswordSettingsManager.py
├── test_Sync.py
└── test_domainExtractor.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 |
5 | # C extensions
6 | *.so
7 |
8 | # Distribution / packaging
9 | .Python
10 | env/
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | *.egg-info/
23 | .installed.cfg
24 | *.egg
25 |
26 | # PyInstaller
27 | # Usually these files are written by a python script from a template
28 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
29 | *.manifest
30 | *.spec
31 |
32 | # Installer logs
33 | pip-log.txt
34 | pip-delete-this-directory.txt
35 |
36 | # Unit test / coverage reports
37 | htmlcov/
38 | .tox/
39 | .coverage
40 | .coverage.*
41 | .cache
42 | nosetests.xml
43 | coverage.xml
44 | *,cover
45 |
46 | # Translations
47 | *.mo
48 | *.pot
49 |
50 | # Django stuff:
51 | *.log
52 |
53 | # Sphinx documentation
54 | docs/_build/
55 |
56 | # PyBuilder
57 | target/
58 |
59 | # PyCharm
60 | .idea/
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 | python:
3 | - "3.4"
4 | - "3.5"
5 | - "3.6"
6 | - "nightly"
7 | # command to install dependencies
8 | install: "pip install -r requirements.txt"
9 | # command to run tests
10 | script: nosetests
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
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 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
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 | {project} Copyright (C) {year} {fullname}
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 |
676 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | This is a command line Python version of the c't password manager which is extended to save password settings locally.
2 |
3 | [](http://choosealicense.com/licenses/gpl-3.0/)
4 | [](http://ctsesam-python-memorizing.readthedocs.org/en/latest)
5 | [](https://travis-ci.org/pinae/ctSESAM-python-memorizing)
6 | [](https://landscape.io/github/pinae/ctSESAM-python-memorizing/master)
7 |
8 |
9 | What is c't SESAM?
10 | ==================
11 |
12 | c't SESAM is a password manager which calculates passwords from masterpasswords and domains using PBKDF2. There
13 | are compatible versions of this software for different platforms. This is the the console
14 | version written in Python.
15 |
16 | Dependencies
17 | ------------
18 |
19 | If you want to use a virtual environment execute the following commands in the source directory:
20 |
21 | ```shell script
22 | python3 -m venv env
23 | source env/bin/activate
24 | pip install -U pip wheel
25 | ```
26 |
27 | In all cases install the dependencie named in `requirements.txt`:
28 |
29 | ```shell script
30 | pip install -r requirements.txt
31 | ```
32 |
33 | Usage
34 | -----
35 |
36 | Get Usage instructions with `--help`:
37 |
38 | ```shell script
39 | $ python ctSESAM.py --help
40 | usage: ctSESAM.py [-h] [-n] [-u] [--master-password MASTER_PASSWORD]
41 | [-d DOMAIN] [-q]
42 |
43 | Generate domain passwords from your masterpassword.
44 |
45 | optional arguments:
46 | -h, --help show this help message and exit
47 | -n, --no-sync Do not synchronize with a server.
48 | -u, --update-sync-settings
49 | Ask for server settings before synchronization.
50 | --master-password MASTER_PASSWORD
51 | If not specified it will be prompted.
52 | -d DOMAIN, --domain DOMAIN
53 | If not specified it will be prompted.
54 | -q, --quiet Display only prompts (if necessary) and the plain
55 | password
56 | ```
57 |
58 | Start normally with:
59 |
60 | ```shell script
61 | python ctSESAM.py
62 | ```
63 |
64 | Running tests
65 | -------------
66 |
67 | First install `pytest`:
68 |
69 | ```shell script
70 | pip install pytest
71 | ```
72 |
73 | Run the tests with:
74 |
75 | ```shell script
76 | python3 -m pytest
77 | ```
78 |
--------------------------------------------------------------------------------
/crypter.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Encryption and decryption module.
5 | """
6 |
7 | from Crypto.Cipher import AES
8 | from hashlib import pbkdf2_hmac
9 | import os
10 |
11 |
12 | class Crypter(object):
13 | """
14 | Encrypt and decrypt with AES in CBC mode with PKCS7 padding. The constructor calculates the key from the given
15 | password and salt with PBKDF2 using HMAC with SHA512 and 32768 iterations.
16 | """
17 | def __init__(self, key_iv):
18 | if len(key_iv) == 48:
19 | self.key = key_iv[:32]
20 | self.iv = key_iv[32:]
21 | else:
22 | raise ValueError("Wrong key_iv length.")
23 |
24 | @staticmethod
25 | def create_key(password, salt, iterations=1024):
26 | """
27 | Creates a key for encrypting/decrypting settings.
28 |
29 | :param password: this is the kgk
30 | :type password: bytes
31 | :param salt: the salt2
32 | :type salt: bytes
33 | :param iterations: an iteration count
34 | :type iterations: int
35 | :return: a key
36 | :rtype: bytes
37 | """
38 | return pbkdf2_hmac('sha256', password, salt, iterations)
39 |
40 | @staticmethod
41 | def createIvKey(password, salt, iterations=32768):
42 | """
43 | Creates a key for encrypting/decrypting kgk blocks.
44 |
45 | :param password: this is the kgk
46 | :type password: bytes
47 | :param salt: the salt2
48 | :type salt: bytes
49 | :param iterations: an iteration count
50 | :type iterations: int
51 | :return: a key
52 | :rtype: bytes
53 | """
54 | return pbkdf2_hmac('sha384', password, salt, iterations)
55 |
56 | @staticmethod
57 | def createSalt():
58 | """
59 | Create a new salt.
60 |
61 | :return: a salt with 32 bytes
62 | :rtype: bytes
63 | """
64 | return os.urandom(32)
65 |
66 | @staticmethod
67 | def createIv():
68 | """
69 | Create a new ivj
70 |
71 | :return: an iv with 16 bytes
72 | :rtype: bytes
73 | """
74 | return os.urandom(16)
75 |
76 | @staticmethod
77 | def add_pkcs7_padding(data):
78 | """
79 | Adds PKCS7 padding so it can be divided into full blocks of 16 bytes.
80 |
81 | :param bytes data: data without padding
82 | :return: padded data
83 | :rtype: bytes
84 | """
85 | length = 16 - (len(data) % 16)
86 | data += bytes([length])*length
87 | return data
88 |
89 | def encrypt(self, data):
90 | """
91 | Encrypts with AES in CBC mode with PKCS7 padding.
92 |
93 | :param bytes data: data for encryption
94 | :return: encrypted data
95 | :rtype: bytes
96 | """
97 | aes_object = AES.new(self.key, AES.MODE_CBC, self.iv)
98 | return aes_object.encrypt(self.add_pkcs7_padding(data))
99 |
100 | def encrypt_unpadded(self, data):
101 | """
102 | Encrypts with AES in CBC mode without padding. The data has to fit into blocks of 16 bytes.
103 |
104 | :param bytes data: data for encryption
105 | :return: encrypted data
106 | :rtype: bytes
107 | """
108 | aes_object = AES.new(self.key, AES.MODE_CBC, self.iv)
109 | return aes_object.encrypt(data)
110 |
111 | @staticmethod
112 | def remove_pkcs7_padding(data):
113 | """
114 | Removes the PKCS7 padding.
115 |
116 | :param bytes data: padded data
117 | :return: data without padding
118 | :rtype: bytes
119 | """
120 | return data[:-data[-1]]
121 |
122 | def decrypt(self, encrypted_data):
123 | """
124 | Decrypts with AES in CBC mode with PKCS7 padding.
125 |
126 | :param bytes encrypted_data: encrypted data
127 | :return: decrypted data
128 | :rtype: bytes
129 | """
130 | aes_object = AES.new(self.key, AES.MODE_CBC, self.iv)
131 | return self.remove_pkcs7_padding(aes_object.decrypt(encrypted_data))
132 |
133 | def decrypt_unpadded(self, encrypted_data):
134 | """
135 | Decrypts with AES in CBC mode without padding. The data has to fit into blocks of 16 bytes.
136 |
137 | :param bytes encrypted_data: encrypted data
138 | :return: decrypted data
139 | :rtype: bytes
140 | """
141 | aes_object = AES.new(self.key, AES.MODE_CBC, self.iv)
142 | return aes_object.decrypt(encrypted_data)
143 |
--------------------------------------------------------------------------------
/ctSESAM.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Main file for c't SESAM.
5 | """
6 |
7 | from password_generator import CtSesam
8 | from preference_manager import PreferenceManager
9 | from kgk_manager import KgkManager
10 | from password_settings_manager import PasswordSettingsManager
11 | from base64 import b64decode
12 | import argparse
13 | import getpass
14 | import sys
15 |
16 |
17 | def create_settings_manager(kgk_mng):
18 | preference_mng = PreferenceManager()
19 | kgk_mng.set_preference_manager(preference_mng)
20 | kgk_mng.decrypt_kgk(preference_mng.get_kgk_block(),
21 | password=master_password.encode('utf-8'),
22 | salt=preference_mng.get_salt())
23 | return PasswordSettingsManager(preference_mng), preference_mng
24 |
25 |
26 | def decrypt_remote_settings(kgk_mng, settings_mng):
27 | remote_kgk_manager = KgkManager()
28 | remote_kgk_manager.update_from_blob(master_password.encode('utf-8'), b64decode(data))
29 | kgk_exists = len(settings_manager.preference_manager.get_kgk_block()) == 112
30 | if kgk_exists and remote_kgk_manager.has_kgk() and kgk_mng.has_kgk() and \
31 | kgk_mng.get_kgk() != remote_kgk_manager.get_kgk():
32 | print("Lokal und auf dem Server gibt es unterschiedliche KGKs. Das ist ein Problem!")
33 | else:
34 | if not kgk_exists:
35 | kgk_mng = remote_kgk_manager
36 | kgk_mng.set_preference_manager(preference_manager)
37 | kgk_mng.store_local_kgk_block()
38 | settings_mng.update_from_export_data(remote_kgk_manager, b64decode(data))
39 | print("Verbindung erfolgreich getestet.")
40 | return kgk_mng, settings_mng
41 |
42 |
43 | def get_domain(cmd_opt_domain):
44 | if cmd_opt_domain:
45 | domain = cmd_opt_domain
46 | else:
47 | domain = input('Domain: ')
48 | while len(domain) < 1:
49 | print('Bitte gib eine Domain an, für die das Passwort generiert werden soll.')
50 | domain = input('Domain: ')
51 | password_setting_found = False
52 | if domain in [dom[:len(domain)] for dom in settings_manager.get_domain_list()]:
53 | if domain in settings_manager.get_domain_list():
54 | password_setting_found = True
55 | if not args.quiet:
56 | print("Die Einstellungen für " + domain + " wurden geladen.")
57 | else:
58 | for dom in settings_manager.get_domain_list():
59 | if dom[:len(domain)] == domain:
60 | print("Für die Domain '" + dom + "' wurden Einstellungen gefunden.")
61 | answer = input("Sollen sie geladen werden [J/n]? ")
62 | if answer not in ["n", "N", "Nein", "nein", "NEIN", "NO", "No", "no", "nay", "not", "Not", "NOT"]:
63 | domain = dom
64 | password_setting_found = True
65 | return settings_manager.get_setting(domain), password_setting_found
66 |
67 |
68 | def print_legacy_password(password_setting, quiet):
69 | if quiet:
70 | print(password_setting.get_legacy_password())
71 | else:
72 | print("klassisches Passwort: " + password_setting.get_legacy_password())
73 |
74 |
75 | def print_generated_password(password_setting, kgk, quiet):
76 | sesam = CtSesam(password_setting.get_domain(),
77 | password_setting.get_username(),
78 | kgk,
79 | password_setting.get_salt(),
80 | password_setting.get_iterations())
81 | password = sesam.generate(password_setting)
82 | if quiet:
83 | print(password)
84 | else:
85 | print('Passwort: ' + password)
86 |
87 |
88 | if __name__ == "__main__":
89 | parser = argparse.ArgumentParser(description="Generate domain passwords from your masterpassword.")
90 | parser.add_argument('-n', '--no-sync',
91 | action='store_const', const=True,
92 | help="Do not synchronize with a server.")
93 | parser.add_argument('-u', '--update-sync-settings',
94 | action='store_const', const=True,
95 | help="Ask for server settings before synchronization.")
96 | parser.add_argument('--master-password', help="If not specified it will be prompted.")
97 | parser.add_argument('-d', '--domain', help="If not specified it will be prompted.")
98 | parser.add_argument('-q', '--quiet',
99 | action='store_const', const=True,
100 | help="Display only prompts (if necessary) and the plain password")
101 | args = parser.parse_args()
102 | if args.master_password:
103 | master_password = args.master_password
104 | else:
105 | master_password = getpass.getpass(prompt='Masterpasswort: ')
106 | kgk_manager = KgkManager()
107 | settings_manager, preference_manager = create_settings_manager(kgk_manager)
108 | try:
109 | settings_manager.load_settings(kgk_manager, master_password, args.no_sync)
110 | if not args.no_sync and (args.update_sync_settings or not settings_manager.sync_manager.has_settings()):
111 | settings_manager.sync_manager.ask_for_sync_settings()
112 | print("Teste die Verbindung...")
113 | pull_successful, data = settings_manager.sync_manager.pull()
114 | if pull_successful and len(data) > 0:
115 | kgk_manager, settings_manager = decrypt_remote_settings(kgk_manager, settings_manager)
116 | else:
117 | print("Es konnte keine Verbindung aufgebaut werden.")
118 | except ValueError:
119 | print("Falsches Masterpasswort. Es wurden keine Einstellungen geladen.")
120 | sys.exit(1)
121 | setting, setting_found = get_domain(args.domain)
122 | if not setting_found:
123 | setting.ask_for_input()
124 | if setting_found and setting.has_username() and not args.quiet:
125 | print("Benutzername: " + setting.get_username())
126 | settings_manager.set_setting(setting)
127 | settings_manager.store_settings(kgk_manager)
128 | if setting_found and setting.has_legacy_password():
129 | print_legacy_password(setting, args.quiet)
130 | else:
131 | print_generated_password(setting, kgk_manager.get_kgk(), args.quiet)
132 |
--------------------------------------------------------------------------------
/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/ctSESAM-python.qhcp"
91 | @echo "To view the help file:"
92 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ctSESAM-python.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/ctSESAM-python"
108 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ctSESAM-python"
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 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | #
4 | # c't SESAM - python documentation build configuration file, created by
5 | # sphinx-quickstart on Fri Aug 21 16:25:36 2015.
6 | #
7 | # This file is execfile()d with the current directory set to its
8 | # containing dir.
9 | #
10 | # Note that not all possible configuration values are present in this
11 | # autogenerated file.
12 | #
13 | # All configuration values have a default; values that are commented out
14 | # serve to show the default.
15 |
16 | import sys
17 | import os
18 | import shlex
19 | from recommonmark.parser import CommonMarkParser
20 |
21 | # If extensions (or modules to document with autodoc) are in another directory,
22 | # add these directories to sys.path here. If the directory is relative to the
23 | # documentation root, use os.path.abspath to make it absolute, like shown here.
24 | sys.path.insert(0, os.path.abspath('..'))
25 |
26 | # -- General configuration ------------------------------------------------
27 |
28 | # If your documentation needs a minimal Sphinx version, state it here.
29 | #needs_sphinx = '1.0'
30 |
31 | # Add any Sphinx extension module names here, as strings. They can be
32 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
33 | # ones.
34 | extensions = [
35 | 'sphinx.ext.autodoc',
36 | 'sphinx.ext.viewcode',
37 | ]
38 |
39 | # Add any paths that contain templates here, relative to this directory.
40 | templates_path = ['_templates']
41 |
42 | source_parsers = {
43 | '.md': CommonMarkParser,
44 | }
45 |
46 | # The suffix(es) of source filenames.
47 | # You can specify multiple suffix as a list of string:
48 | source_suffix = ['.rst', '.md']
49 |
50 | # The encoding of source files.
51 | #source_encoding = 'utf-8-sig'
52 |
53 | # The master toctree document.
54 | master_doc = 'index'
55 |
56 | # General information about the project.
57 | project = 'c\'t SESAM - python'
58 | copyright = '2015, Johannes Merkert'
59 | author = 'Johannes Merkert'
60 |
61 | # The version info for the project you're documenting, acts as replacement for
62 | # |version| and |release|, also used in various other places throughout the
63 | # built documents.
64 | #
65 | # The short X.Y version.
66 | version = '2.0'
67 | # The full version, including alpha/beta/rc tags.
68 | release = '2.0-beta1'
69 |
70 | # The language for content autogenerated by Sphinx. Refer to documentation
71 | # for a list of supported languages.
72 | #
73 | # This is also used if you do content translation via gettext catalogs.
74 | # Usually you set "language" from the command line for these cases.
75 | language = None
76 |
77 | # There are two options for replacing |today|: either, you set today to some
78 | # non-false value, then it is used:
79 | #today = ''
80 | # Else, today_fmt is used as the format for a strftime call.
81 | #today_fmt = '%B %d, %Y'
82 |
83 | # List of patterns, relative to source directory, that match files and
84 | # directories to ignore when looking for source files.
85 | exclude_patterns = ['_build']
86 |
87 | # The reST default role (used for this markup: `text`) to use for all
88 | # documents.
89 | #default_role = None
90 |
91 | # If true, '()' will be appended to :func: etc. cross-reference text.
92 | #add_function_parentheses = True
93 |
94 | # If true, the current module name will be prepended to all description
95 | # unit titles (such as .. function::).
96 | #add_module_names = True
97 |
98 | # If true, sectionauthor and moduleauthor directives will be shown in the
99 | # output. They are ignored by default.
100 | #show_authors = False
101 |
102 | # The name of the Pygments (syntax highlighting) style to use.
103 | pygments_style = 'sphinx'
104 |
105 | # A list of ignored prefixes for module index sorting.
106 | #modindex_common_prefix = []
107 |
108 | # If true, keep warnings as "system message" paragraphs in the built documents.
109 | #keep_warnings = False
110 |
111 | # If true, `todo` and `todoList` produce output, else they produce nothing.
112 | todo_include_todos = False
113 |
114 |
115 | # -- Options for HTML output ----------------------------------------------
116 |
117 | # The theme to use for HTML and HTML Help pages. See the documentation for
118 | # a list of builtin themes.
119 | html_theme = 'sphinx_rtd_theme'
120 |
121 | # Theme options are theme-specific and customize the look and feel of a theme
122 | # further. For a list of options available for each theme, see the
123 | # documentation.
124 | #html_theme_options = {}
125 |
126 | # Add any paths that contain custom themes here, relative to this directory.
127 | #html_theme_path = []
128 |
129 | # The name for this set of Sphinx documents. If None, it defaults to
130 | # " v documentation".
131 | #html_title = None
132 |
133 | # A shorter title for the navigation bar. Default is the same as html_title.
134 | #html_short_title = None
135 |
136 | # The name of an image file (relative to this directory) to place at the top
137 | # of the sidebar.
138 | #html_logo = None
139 |
140 | # The name of an image file (within the static path) to use as favicon of the
141 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
142 | # pixels large.
143 | #html_favicon = None
144 |
145 | # Add any paths that contain custom static files (such as style sheets) here,
146 | # relative to this directory. They are copied after the builtin static files,
147 | # so a file named "default.css" will overwrite the builtin "default.css".
148 | html_static_path = ['_static']
149 |
150 | # Add any extra paths that contain custom files (such as robots.txt or
151 | # .htaccess) here, relative to this directory. These files are copied
152 | # directly to the root of the documentation.
153 | #html_extra_path = []
154 |
155 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
156 | # using the given strftime format.
157 | #html_last_updated_fmt = '%b %d, %Y'
158 |
159 | # If true, SmartyPants will be used to convert quotes and dashes to
160 | # typographically correct entities.
161 | #html_use_smartypants = True
162 |
163 | # Custom sidebar templates, maps document names to template names.
164 | #html_sidebars = {}
165 |
166 | # Additional templates that should be rendered to pages, maps page names to
167 | # template names.
168 | #html_additional_pages = {}
169 |
170 | # If false, no module index is generated.
171 | #html_domain_indices = True
172 |
173 | # If false, no index is generated.
174 | #html_use_index = True
175 |
176 | # If true, the index is split into individual pages for each letter.
177 | #html_split_index = False
178 |
179 | # If true, links to the reST sources are added to the pages.
180 | #html_show_sourcelink = True
181 |
182 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
183 | #html_show_sphinx = True
184 |
185 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
186 | #html_show_copyright = True
187 |
188 | # If true, an OpenSearch description file will be output, and all pages will
189 | # contain a tag referring to it. The value of this option must be the
190 | # base URL from which the finished HTML is served.
191 | #html_use_opensearch = ''
192 |
193 | # This is the file name suffix for HTML files (e.g. ".xhtml").
194 | #html_file_suffix = None
195 |
196 | # Language to be used for generating the HTML full-text search index.
197 | # Sphinx supports the following languages:
198 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
199 | # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr'
200 | #html_search_language = 'en'
201 |
202 | # A dictionary with options for the search language support, empty by default.
203 | # Now only 'ja' uses this config value
204 | #html_search_options = {'type': 'default'}
205 |
206 | # The name of a javascript file (relative to the configuration directory) that
207 | # implements a search results scorer. If empty, the default will be used.
208 | #html_search_scorer = 'scorer.js'
209 |
210 | # Output file base name for HTML help builder.
211 | htmlhelp_basename = 'ctSESAM-pythondoc'
212 |
213 | # -- Options for LaTeX output ---------------------------------------------
214 |
215 | latex_elements = {
216 | # The paper size ('letterpaper' or 'a4paper').
217 | #'papersize': 'letterpaper',
218 |
219 | # The font size ('10pt', '11pt' or '12pt').
220 | #'pointsize': '10pt',
221 |
222 | # Additional stuff for the LaTeX preamble.
223 | #'preamble': '',
224 |
225 | # Latex figure (float) alignment
226 | #'figure_align': 'htbp',
227 | }
228 |
229 | # Grouping the document tree into LaTeX files. List of tuples
230 | # (source start file, target name, title,
231 | # author, documentclass [howto, manual, or own class]).
232 | latex_documents = [
233 | (master_doc, 'ctSESAM-python.tex', 'c\'t SESAM - python Documentation',
234 | 'Johannes Merkert', 'manual'),
235 | ]
236 |
237 | # The name of an image file (relative to this directory) to place at the top of
238 | # the title page.
239 | #latex_logo = None
240 |
241 | # For "manual" documents, if this is true, then toplevel headings are parts,
242 | # not chapters.
243 | #latex_use_parts = False
244 |
245 | # If true, show page references after internal links.
246 | #latex_show_pagerefs = False
247 |
248 | # If true, show URL addresses after external links.
249 | #latex_show_urls = False
250 |
251 | # Documents to append as an appendix to all manuals.
252 | #latex_appendices = []
253 |
254 | # If false, no module index is generated.
255 | #latex_domain_indices = True
256 |
257 |
258 | # -- Options for manual page output ---------------------------------------
259 |
260 | # One entry per manual page. List of tuples
261 | # (source start file, name, description, authors, manual section).
262 | man_pages = [
263 | (master_doc, 'ctsesam-python', 'c\'t SESAM - python Documentation',
264 | [author], 1)
265 | ]
266 |
267 | # If true, show URL addresses after external links.
268 | #man_show_urls = False
269 |
270 |
271 | # -- Options for Texinfo output -------------------------------------------
272 |
273 | # Grouping the document tree into Texinfo files. List of tuples
274 | # (source start file, target name, title, author,
275 | # dir menu entry, description, category)
276 | texinfo_documents = [
277 | (master_doc, 'ctSESAM-python', 'c\'t SESAM - python Documentation',
278 | author, 'ctSESAM-python', 'One line description of project.',
279 | 'Miscellaneous'),
280 | ]
281 |
282 | # Documents to append as an appendix to all manuals.
283 | #texinfo_appendices = []
284 |
285 | # If false, no module index is generated.
286 | #texinfo_domain_indices = True
287 |
288 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
289 | #texinfo_show_urls = 'footnote'
290 |
291 | # If true, do not generate a @detailmenu in the "Top" node's menu.
292 | #texinfo_no_detailmenu = False
293 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | .. c't SESAM - python documentation master file, created by
2 | sphinx-quickstart on Fri Aug 21 16:25:36 2015.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | Welcome to c't SESAM - python's documentation!
7 | ==============================================
8 |
9 | c't SESAM is a password manager which calculates passwords from masterpasswords and domains using PBKDF2. There
10 | are compatible versions of this software for different platforms. This is the documentation for the console
11 | version written in Python.
12 |
13 | Contents:
14 |
15 | .. toctree::
16 | :maxdepth: 2
17 |
18 | passwordGeneration
19 | settings
20 | synchronisation
21 | tools
22 |
23 |
24 |
25 | Indices and tables
26 | ==================
27 |
28 | * :ref:`genindex`
29 | * :ref:`modindex`
30 | * :ref:`search`
31 |
32 |
--------------------------------------------------------------------------------
/docs/make.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | REM Command file for Sphinx documentation
4 |
5 | if "%SPHINXBUILD%" == "" (
6 | set SPHINXBUILD=sphinx-build
7 | )
8 | set BUILDDIR=_build
9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
10 | set I18NSPHINXOPTS=%SPHINXOPTS% .
11 | if NOT "%PAPER%" == "" (
12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
14 | )
15 |
16 | if "%1" == "" goto help
17 |
18 | if "%1" == "help" (
19 | :help
20 | echo.Please use `make ^` where ^ is one of
21 | echo. html to make standalone HTML files
22 | echo. dirhtml to make HTML files named index.html in directories
23 | echo. singlehtml to make a single large HTML file
24 | echo. pickle to make pickle files
25 | echo. json to make JSON files
26 | echo. htmlhelp to make HTML files and a HTML help project
27 | echo. qthelp to make HTML files and a qthelp project
28 | echo. devhelp to make HTML files and a Devhelp project
29 | echo. epub to make an epub
30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
31 | echo. text to make text files
32 | echo. man to make manual pages
33 | echo. texinfo to make Texinfo files
34 | echo. gettext to make PO message catalogs
35 | echo. changes to make an overview over all changed/added/deprecated items
36 | echo. xml to make Docutils-native XML files
37 | echo. pseudoxml to make pseudoxml-XML files for display purposes
38 | echo. linkcheck to check all external links for integrity
39 | echo. doctest to run all doctests embedded in the documentation if enabled
40 | echo. coverage to run coverage check of the documentation if enabled
41 | goto end
42 | )
43 |
44 | if "%1" == "clean" (
45 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
46 | del /q /s %BUILDDIR%\*
47 | goto end
48 | )
49 |
50 |
51 | REM Check if sphinx-build is available and fallback to Python version if any
52 | %SPHINXBUILD% 2> nul
53 | if errorlevel 9009 goto sphinx_python
54 | goto sphinx_ok
55 |
56 | :sphinx_python
57 |
58 | set SPHINXBUILD=python -m sphinx.__init__
59 | %SPHINXBUILD% 2> nul
60 | if errorlevel 9009 (
61 | echo.
62 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
63 | echo.installed, then set the SPHINXBUILD environment variable to point
64 | echo.to the full path of the 'sphinx-build' executable. Alternatively you
65 | echo.may add the Sphinx directory to PATH.
66 | echo.
67 | echo.If you don't have Sphinx installed, grab it from
68 | echo.http://sphinx-doc.org/
69 | exit /b 1
70 | )
71 |
72 | :sphinx_ok
73 |
74 |
75 | if "%1" == "html" (
76 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
77 | if errorlevel 1 exit /b 1
78 | echo.
79 | echo.Build finished. The HTML pages are in %BUILDDIR%/html.
80 | goto end
81 | )
82 |
83 | if "%1" == "dirhtml" (
84 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
85 | if errorlevel 1 exit /b 1
86 | echo.
87 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
88 | goto end
89 | )
90 |
91 | if "%1" == "singlehtml" (
92 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
93 | if errorlevel 1 exit /b 1
94 | echo.
95 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
96 | goto end
97 | )
98 |
99 | if "%1" == "pickle" (
100 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
101 | if errorlevel 1 exit /b 1
102 | echo.
103 | echo.Build finished; now you can process the pickle files.
104 | goto end
105 | )
106 |
107 | if "%1" == "json" (
108 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
109 | if errorlevel 1 exit /b 1
110 | echo.
111 | echo.Build finished; now you can process the JSON files.
112 | goto end
113 | )
114 |
115 | if "%1" == "htmlhelp" (
116 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
117 | if errorlevel 1 exit /b 1
118 | echo.
119 | echo.Build finished; now you can run HTML Help Workshop with the ^
120 | .hhp project file in %BUILDDIR%/htmlhelp.
121 | goto end
122 | )
123 |
124 | if "%1" == "qthelp" (
125 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
126 | if errorlevel 1 exit /b 1
127 | echo.
128 | echo.Build finished; now you can run "qcollectiongenerator" with the ^
129 | .qhcp project file in %BUILDDIR%/qthelp, like this:
130 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\ctSESAM-python.qhcp
131 | echo.To view the help file:
132 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\ctSESAM-python.ghc
133 | goto end
134 | )
135 |
136 | if "%1" == "devhelp" (
137 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
138 | if errorlevel 1 exit /b 1
139 | echo.
140 | echo.Build finished.
141 | goto end
142 | )
143 |
144 | if "%1" == "epub" (
145 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
146 | if errorlevel 1 exit /b 1
147 | echo.
148 | echo.Build finished. The epub file is in %BUILDDIR%/epub.
149 | goto end
150 | )
151 |
152 | if "%1" == "latex" (
153 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
154 | if errorlevel 1 exit /b 1
155 | echo.
156 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
157 | goto end
158 | )
159 |
160 | if "%1" == "latexpdf" (
161 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
162 | cd %BUILDDIR%/latex
163 | make all-pdf
164 | cd %~dp0
165 | echo.
166 | echo.Build finished; the PDF files are in %BUILDDIR%/latex.
167 | goto end
168 | )
169 |
170 | if "%1" == "latexpdfja" (
171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
172 | cd %BUILDDIR%/latex
173 | make all-pdf-ja
174 | cd %~dp0
175 | echo.
176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex.
177 | goto end
178 | )
179 |
180 | if "%1" == "text" (
181 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
182 | if errorlevel 1 exit /b 1
183 | echo.
184 | echo.Build finished. The text files are in %BUILDDIR%/text.
185 | goto end
186 | )
187 |
188 | if "%1" == "man" (
189 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
190 | if errorlevel 1 exit /b 1
191 | echo.
192 | echo.Build finished. The manual pages are in %BUILDDIR%/man.
193 | goto end
194 | )
195 |
196 | if "%1" == "texinfo" (
197 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
198 | if errorlevel 1 exit /b 1
199 | echo.
200 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
201 | goto end
202 | )
203 |
204 | if "%1" == "gettext" (
205 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
206 | if errorlevel 1 exit /b 1
207 | echo.
208 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
209 | goto end
210 | )
211 |
212 | if "%1" == "changes" (
213 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
214 | if errorlevel 1 exit /b 1
215 | echo.
216 | echo.The overview file is in %BUILDDIR%/changes.
217 | goto end
218 | )
219 |
220 | if "%1" == "linkcheck" (
221 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
222 | if errorlevel 1 exit /b 1
223 | echo.
224 | echo.Link check complete; look for any errors in the above output ^
225 | or in %BUILDDIR%/linkcheck/output.txt.
226 | goto end
227 | )
228 |
229 | if "%1" == "doctest" (
230 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
231 | if errorlevel 1 exit /b 1
232 | echo.
233 | echo.Testing of doctests in the sources finished, look at the ^
234 | results in %BUILDDIR%/doctest/output.txt.
235 | goto end
236 | )
237 |
238 | if "%1" == "coverage" (
239 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage
240 | if errorlevel 1 exit /b 1
241 | echo.
242 | echo.Testing of coverage in the sources finished, look at the ^
243 | results in %BUILDDIR%/coverage/python.txt.
244 | goto end
245 | )
246 |
247 | if "%1" == "xml" (
248 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
249 | if errorlevel 1 exit /b 1
250 | echo.
251 | echo.Build finished. The XML files are in %BUILDDIR%/xml.
252 | goto end
253 | )
254 |
255 | if "%1" == "pseudoxml" (
256 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
257 | if errorlevel 1 exit /b 1
258 | echo.
259 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
260 | goto end
261 | )
262 |
263 | :end
264 |
--------------------------------------------------------------------------------
/docs/passwordGeneration.rst:
--------------------------------------------------------------------------------
1 |
2 | Password generation
3 | ===================
4 |
5 | c't SESAM uses an encrypted secret to generate your passwords: the kgk (Key-Generation-Key). This trick enables you
6 | to change your masterpassword and makes sure that the secret used for the calculation of passwords is 64 bytes.
7 |
8 | The kgk is stored and decrypted in the ``KgkManager`` class:
9 |
10 | .. default-domain:: py
11 | .. automodule:: kgk_manager
12 | :members:
13 |
14 | The encrypted kgk, and the settings are stored in the hidden file ``.ctSESAM.pws`` in your home directory. Reading
15 | and writing of this file is handled by the ``PreferenceManager``:
16 |
17 | .. automodule:: preference_manager
18 | :members:
19 |
20 | Passwords are generated with the ``PasswordManager`` class:
21 |
22 | .. automodule:: password_generator
23 | :members:
--------------------------------------------------------------------------------
/docs/settings.rst:
--------------------------------------------------------------------------------
1 |
2 | Managing settings
3 | =================
4 |
5 | Settings are stored as ``PasswordSetting`` objects.
6 |
7 | .. default-domain:: py
8 | .. automodule:: password_setting
9 | :members:
10 |
11 | The ``PasswordSettingsManager`` saves and manages the ``PasswordSetting`` objects.
12 |
13 | .. automodule:: password_settings_manager
14 | :members:
15 |
16 | It uses a ``Packer`` to compress data for storage and a ``Crypter`` to encrypt it.
17 |
18 | .. automodule:: packer
19 | :members:
20 |
21 | .. automodule:: crypter
22 | :members:
23 |
--------------------------------------------------------------------------------
/docs/synchronisation.rst:
--------------------------------------------------------------------------------
1 |
2 | Synchronisation
3 | ===============
4 |
5 | ctSESAM can synchronize your password settings with a ctSESAM-Server_. The exact protocol is specified in the Wiki_.
6 |
7 | .. _ctSESAM-Server: https://github.com/ola-ct/ctSESAM-server
8 | .. _Wiki: https://github.com/ola-ct/ctSESAM-server/wiki
9 |
10 | Basic communication part is implemented in the ``Sync`` class.
11 |
12 | .. automodule:: sync
13 | :members:
14 |
15 | This class is wrapped by a ``SyncManager`` which handles the settings management for the server connection.
16 |
17 | .. automodule:: sync_manager
18 | :members:
19 |
--------------------------------------------------------------------------------
/docs/tools.rst:
--------------------------------------------------------------------------------
1 |
2 | Tools
3 | =====
4 |
5 | .. automodule:: domain_extractor
6 | :members:
--------------------------------------------------------------------------------
/domain_extractor.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Functions for extracting domains.
5 | """
6 |
7 | import re
8 |
9 |
10 | def extract_top_domain(url):
11 | """
12 | Extracts the domain from an url. Subdomains are ignored
13 |
14 | :param url: Url with https:// and /some/path
15 | :type url: str
16 | :return: domain name without protocol, subdomains or path
17 | :rtype: str
18 | """
19 | pattern = re.compile("(?:https?://)?(\w+\.)+(co\.\w+).*")
20 | matches = pattern.match(url)
21 | if matches and len(matches.groups()) >= 2:
22 | return matches.group(len(matches.groups()) - 1) + matches.group(len(matches.groups()))
23 | pattern = re.compile("(?:https?://)?(\w+\.)+(\w+).*")
24 | matches = pattern.match(url)
25 | if matches and len(matches.groups()) >= 2:
26 | return matches.group(len(matches.groups()) - 1) + matches.group(len(matches.groups()))
27 | else:
28 | return url
29 |
30 |
31 | def extract_full_domain(url):
32 | """
33 | Extracts the domain from an url
34 |
35 | :param url: Url with https:// and /some/path
36 | :type url: str
37 | :return: domain name without protocol or path
38 | :rtype: str
39 | """
40 | pattern = re.compile("(?:https?://)?((?:\w+\.)*)(\w+).*")
41 | matches = pattern.match(url)
42 | if matches and len(matches.groups()) >= 2:
43 | return "".join(matches.groups())
44 | else:
45 | return url
46 |
--------------------------------------------------------------------------------
/kgk_manager.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | The KGK manager stores the kgk and manages storage and encryption of kgk blocks.
5 | """
6 |
7 | from preference_manager import PreferenceManager
8 | from crypter import Crypter
9 | from binascii import hexlify
10 | import os
11 |
12 |
13 | class KgkManager(object):
14 | """
15 | New KgkManagers are uninitialized and need either a new kgk or get one by decrypting an existing one.
16 | """
17 | def __init__(self):
18 | self.preference_manager = None
19 | self.kgk = b''
20 | self.iv2 = None
21 | self.salt2 = None
22 | self.kgk_crypter = None
23 | self.salt = b''
24 |
25 | def __str__(self):
26 | attr = ["KGK: " + str(hexlify(self.kgk), encoding='utf-8'),
27 | "salt: " + str(hexlify(self.salt), encoding='utf-8')]
28 | if self.iv2:
29 | attr.append("iv2: " + str(hexlify(self.iv2), encoding='utf-8'))
30 | if self.salt2:
31 | attr.append("salt2: " + str(hexlify(self.salt2), encoding='utf-8'))
32 | return "<" + ", ".join(attr) + ">"
33 |
34 | def set_preference_manager(self, preference_manager):
35 | """
36 | Pass a preference manager to load and store settings locally
37 |
38 | :param preference_manager:
39 | :type preference_manager: PreferenceManager
40 | """
41 | if type(preference_manager) != PreferenceManager:
42 | raise TypeError
43 | self.preference_manager = preference_manager
44 |
45 | def get_kgk_crypter_salt(self):
46 | """
47 | Loads the public salt. If there is none it is created and stored.
48 |
49 | :return:
50 | """
51 | self.salt = self.preference_manager.get_salt()
52 | if len(self.salt) != 32:
53 | self.salt = Crypter.createSalt()
54 | self.store_salt(self.salt)
55 | return self.salt
56 |
57 | def store_salt(self, salt):
58 | """
59 | Stores the salt using the preference manager.
60 |
61 | :param salt: the salt
62 | :type salt: bytes
63 | """
64 | if type(salt) == bytes:
65 | self.salt = salt
66 | if self.preference_manager:
67 | self.preference_manager.store_salt(salt)
68 | else:
69 | raise TypeError("There is no salt to be saved")
70 |
71 | def get_kgk_crypter(self, password, salt):
72 | """
73 | Creates a kgk crypter for the given credentials. This is a very expensive operation.
74 |
75 | :param password:
76 | :type password: bytes
77 | :param salt:
78 | :type salt: bytes
79 | :return: a kgk crypter
80 | :rtype: Crypter
81 | """
82 | self.kgk_crypter = Crypter(Crypter.createIvKey(password=password, salt=salt))
83 | self.store_salt(salt=salt)
84 | return self.kgk_crypter
85 |
86 | def create_new_kgk(self):
87 | """
88 | Creates a new kgk. This overwrites the previous one.
89 |
90 | :return: the new kgk
91 | :rtype: bytes
92 | """
93 | self.kgk = os.urandom(64)
94 | self.iv2 = Crypter.createIv()
95 | self.salt2 = Crypter.createSalt()
96 | return self.kgk
97 |
98 | def decrypt_kgk(self, encrypted_kgk, kgk_crypter=None, password=b'', salt=b''):
99 | """
100 | Decrypts kgk blobs. If a crypter is passed it is used. If none is passed a new crypter is created with
101 | the salt and password. This takes relatively long. If the encrypted_kgk has a wrong length a new kgk is
102 | created.
103 |
104 | :param encrypted_kgk:
105 | :type encrypted_kgk: bytes
106 | :param kgk_crypter:
107 | :type kgk_crypter: Crypter
108 | :param password:
109 | :type password: bytes
110 | :param salt:
111 | :type salt: bytes
112 | """
113 | if kgk_crypter:
114 | self.kgk_crypter = kgk_crypter
115 | else:
116 | if len(salt) < 32:
117 | salt = Crypter.createSalt()
118 | self.get_kgk_crypter(password, salt)
119 | if len(encrypted_kgk) == 112:
120 | kgk_block = self.kgk_crypter.decrypt_unpadded(encrypted_kgk)
121 | self.salt2 = kgk_block[:32]
122 | self.iv2 = kgk_block[32:48]
123 | self.kgk = kgk_block[48:112]
124 | else:
125 | self.create_new_kgk()
126 |
127 | def get_kgk(self):
128 | """
129 | Returns the kgk.
130 |
131 | :return: the kgk
132 | :rtype: bytes
133 | """
134 | return self.kgk
135 |
136 | def has_kgk(self):
137 | """
138 | Returns true if there is a kgk and a crypter.
139 |
140 | :return: kgk state
141 | :rtype: bool
142 | """
143 | return not not self.kgk and len(self.kgk) == 64 and self.kgk_crypter
144 |
145 | def get_salt2(self):
146 | """
147 | Returns the salt2
148 |
149 | :return: salt2
150 | :rtype: bytes
151 | """
152 | return self.salt2
153 |
154 | def get_iv2(self):
155 | """
156 | Returns the iv2
157 |
158 | :return: iv2
159 | :rtype: bytes
160 | """
161 | return self.iv2
162 |
163 | def fresh_salt2(self):
164 | """
165 | Creates a fresh salt for the settings encryption (salt2).
166 | """
167 | self.salt2 = Crypter.createSalt()
168 |
169 | def fresh_iv2(self):
170 | """
171 | Creates a fresh iv for the settings encryption (iv2).
172 | """
173 | self.iv2 = Crypter.createIv()
174 |
175 | def get_encrypted_kgk(self):
176 | """
177 | Returns an encrypted kgk block.
178 |
179 | :return: kgk block
180 | :rtype: bytes
181 | """
182 | return self.kgk_crypter.encrypt_unpadded(self.salt2 + self.iv2 + self.kgk)
183 |
184 | def get_fresh_encrypted_kgk(self):
185 | """
186 | Returns a new encrypted kgk block with fresh salt2 and iv2. This does not create a new kgk.
187 |
188 | :return: kgk block
189 | :rtype: bytes
190 | """
191 | self.fresh_iv2()
192 | self.fresh_salt2()
193 | return self.get_encrypted_kgk()
194 |
195 | def create_and_save_new_kgk_block(self, kgk_crypter=None):
196 | """
197 | Creates a fresh kgk block and saves it.
198 |
199 | :param kgk_crypter:
200 | :type kgk_crypter: Crypter
201 | :return: kgk block
202 | :rtype: bytes
203 | """
204 | self.salt = Crypter.createSalt()
205 | self.store_salt(self.salt)
206 | if kgk_crypter:
207 | self.kgk_crypter = kgk_crypter
208 | kgk_block = self.get_fresh_encrypted_kgk()
209 | self.preference_manager.store_kgk_block(kgk_block)
210 | return kgk_block
211 |
212 | def update_from_blob(self, password, blob):
213 | """
214 | Updates the kgk from a remote data blob.
215 |
216 | :param password: the masterpassword
217 | :type password: bytes
218 | :param blob: the encrypted data
219 | :type blob: bytes
220 | """
221 | if blob[0] != 1 or len(blob) < 145:
222 | raise ValueError("Version error: Wrong data format. Could not import anything.")
223 | salt = blob[1:33]
224 | kgk_block = blob[33:145]
225 | self.decrypt_kgk(encrypted_kgk=kgk_block, password=password, salt=salt)
226 |
227 | def store_local_kgk_block(self):
228 | """
229 | Stores the local kgk block.
230 | """
231 | if self.preference_manager:
232 | self.preference_manager.store_kgk_block(self.get_encrypted_kgk())
233 | if len(self.salt) == 32:
234 | self.store_salt(self.salt)
235 | else:
236 | raise ValueError("The salt has to be 32 bytes.")
237 |
238 | def reset(self):
239 | """
240 | Resets the kgk manager.
241 | """
242 | self.salt = b''
243 | self.iv2 = None
244 | self.salt2 = None
245 | self.kgk = b''
246 | self.kgk_crypter = None
247 |
--------------------------------------------------------------------------------
/packer.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Compression with DEFLATE.
5 | """
6 |
7 | import zlib
8 | import struct
9 |
10 |
11 | class Packer(object):
12 | """
13 | You do not need to create instances of this class because compress and decompress are both static methods.
14 | """
15 |
16 | @staticmethod
17 | def compress(data):
18 | """
19 | Compresses the given data with the DEFLATE algorithm. The first four bytes contain the length of the
20 | uncompressed data.
21 |
22 | :param data: uncompressed data
23 | :type data: bytes or str
24 | :return: compressed data
25 | :rtype: bytes
26 | """
27 | compress_object = zlib.compressobj(
28 | zlib.Z_BEST_COMPRESSION,
29 | zlib.DEFLATED,
30 | zlib.MAX_WBITS,
31 | zlib.DEF_MEM_LEVEL,
32 | zlib.Z_DEFAULT_STRATEGY)
33 | if type(data) == str:
34 | compressed_data = compress_object.compress(data.encode('utf-8'))
35 | compressed_data += compress_object.flush()
36 | return struct.pack('!I', len(data.encode('utf-8'))) + compressed_data
37 | elif type(data) == bytes:
38 | compressed_data = compress_object.compress(data)
39 | compressed_data += compress_object.flush()
40 | return struct.pack('!I', len(data)) + compressed_data
41 | else:
42 | raise TypeError("Please pass a str or bytes to the packer.")
43 |
44 | @staticmethod
45 | def decompress(compressed_data):
46 | """
47 | Decompresses the given data. Please be aware that the first four bytes are the length of the uncompressed
48 | data.
49 |
50 | :param compressed_data: compressed data
51 | :type compressed_data: bytes
52 | :return: uncompressed data
53 | :rtype: bytes
54 | """
55 | if type(compressed_data) == bytes:
56 | try:
57 | return zlib.decompress(compressed_data[4:])
58 | except zlib.error:
59 | raise ValueError("The compressed data is in a wrong format.")
60 | else:
61 | raise TypeError("Please pass bytes to the packer.")
62 |
--------------------------------------------------------------------------------
/password_generator.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Password manager. It's name is CtSesam because it produces passwords which are compatible to those created by other
5 | c't SESAM implementations.
6 | """
7 |
8 | from hashlib import pbkdf2_hmac
9 |
10 |
11 | class CtSesam(object):
12 | """
13 | Calculates passwords from masterpasswords and domain names. You may set the salt and iteration count to
14 | something of your liking. If not set default values will be used.
15 |
16 | :param domain: the domain str
17 | :type domain: str
18 | :param username: the username str
19 | :type username: str
20 | :param kgk: the kgk
21 | :type kgk: bytes
22 | :param salt: the salt
23 | :type salt: bytes
24 | :param iterations: iteration count (should be 1 or higher, default is 4096)
25 | :type iterations: int
26 | """
27 | def __init__(self, domain, username, kgk, salt="pepper".encode('utf-8'), iterations=4096):
28 | start_value = domain.encode('utf-8') + username.encode('utf-8') + kgk
29 | if iterations <= 0:
30 | print("Iteration count was below 1. Hashing 4096 times instead.")
31 | iterations = 4096
32 | self.hash_value = pbkdf2_hmac('sha512', start_value, salt, iterations)
33 |
34 | def generate(self, setting):
35 | """
36 | Generates a password string.
37 |
38 | :param setting: a setting object
39 | :type setting: PasswordSetting
40 | :return: password
41 | :rtype: str
42 | """
43 | number = int.from_bytes(self.hash_value, byteorder='big')
44 | password = ""
45 | character_set = setting.get_character_set()
46 | digits_set = setting.get_digits_character_set()
47 | lower_set = setting.get_lower_case_character_set()
48 | upper_set = setting.get_upper_case_character_set()
49 | extra_set = setting.get_extra_character_set()
50 | template = setting.get_template()
51 | for t in template:
52 | if number > 0:
53 | if t == 'a':
54 | current_set = lower_set
55 | elif t == 'A':
56 | current_set = upper_set
57 | elif t == 'n':
58 | current_set = digits_set
59 | elif t == 'o':
60 | current_set = extra_set
61 | else:
62 | current_set = character_set
63 | if len(current_set) > 0:
64 | password = password + current_set[number % len(current_set)]
65 | number //= len(current_set)
66 | return password
67 |
--------------------------------------------------------------------------------
/password_setting.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Sets of password settings for a domain.
5 | """
6 |
7 | from datetime import datetime
8 | import getpass
9 | import string
10 | import re
11 | import binascii
12 | from base64 import b64encode, b64decode
13 | from random import shuffle
14 | from crypter import Crypter
15 |
16 | DEFAULT_CHARACTER_SET_LOWER_CASE = string.ascii_lowercase
17 | DEFAULT_CHARACTER_SET_UPPER_CASE = string.ascii_uppercase
18 | DEFAULT_CHARACTER_SET_DIGITS = string.digits
19 | DEFAULT_CHARACTER_SET_EXTRA = '#!"§$%&/()[]{}=-_+*<>;:.'
20 |
21 |
22 | class PasswordSetting(object):
23 | """
24 | This saves one set of settings for a certain domain. Use a PasswordSettingsManager to save the settings to a file.
25 | """
26 | def __init__(self, domain):
27 | self.domain = domain
28 | self.url = None
29 | self.username = None
30 | self.legacy_password = None
31 | self.notes = None
32 | self.iterations = 4096
33 | self.salt = Crypter.createSalt()
34 | self.creation_date = datetime.now()
35 | self.modification_date = self.creation_date
36 | self.extra_characters = DEFAULT_CHARACTER_SET_EXTRA
37 | self.template = 'x'*10
38 | self.calculate_template(True, True, True, True)
39 | self.synced = False
40 |
41 | def __str__(self):
42 | output = "<" + self.domain + ": ("
43 | if self.username:
44 | output += "username: " + str(self.username) + ", "
45 | if self.legacy_password:
46 | output += "legacy password: " + str(self.legacy_password) + ", "
47 | if self.notes:
48 | output += "notes: " + str(self.notes) + ", "
49 | output += "iterations: " + str(self.iterations) + ", "
50 | output += "salt: " + str(binascii.hexlify(self.salt)) + ", "
51 | output += "template: " + str(self.template) + ", "
52 | output += "modification date: " + self.get_modification_date() + ", "
53 | output += "creation date: " + self.get_creation_date() + ", "
54 | if self.extra_characters:
55 | output += "extra characters: \"" + self.extra_characters + "\", "
56 | if self.synced:
57 | output += "synced"
58 | else:
59 | output += "not synced"
60 | output += ")>"
61 | return output
62 |
63 | def get_domain(self):
64 | """
65 | Returns the domain name or another string used in the domain field.
66 |
67 | :return: the domain
68 | :rtype: str
69 | """
70 | return self.domain
71 |
72 | def set_domain(self, domain):
73 | """
74 | Change the domain string.
75 |
76 | :param domain: the domain
77 | :type domain: str
78 | """
79 | self.domain = domain
80 | self.synced = False
81 |
82 | def has_username(self):
83 | """
84 | Returns True if the username is set.
85 |
86 | :return:
87 | :rtype: bool
88 | """
89 | return self.username and len(str(self.username)) > 0
90 |
91 | def get_username(self):
92 | """
93 | Returns the username or an empty string if there was no username.
94 |
95 | :return: the username
96 | :rtype: str
97 | """
98 | if self.username:
99 | return self.username
100 | else:
101 | return ""
102 |
103 | def set_username(self, username):
104 | """
105 | Set the username.
106 |
107 | :param username: the username
108 | :type username: str
109 | """
110 | if username != self.username:
111 | self.synced = False
112 | self.username = username
113 |
114 | def has_legacy_password(self):
115 | """
116 | Returns True if the legacy password is set.
117 |
118 | :return:
119 | :rtype: bool
120 | """
121 | return self.legacy_password and len(str(self.legacy_password)) > 0
122 |
123 | def get_legacy_password(self):
124 | """
125 | Returns the legacy password if set or an empty string otherwise.
126 |
127 | :return: the legacy password
128 | :rtype: str
129 | """
130 | if self.legacy_password:
131 | return self.legacy_password
132 | else:
133 | return ""
134 |
135 | def set_legacy_password(self, legacy_password):
136 | """
137 | Set a legacy password.
138 |
139 | :param legacy_password: a legacy password
140 | :type legacy_password: str
141 | """
142 | if legacy_password != self.legacy_password:
143 | self.synced = False
144 | self.legacy_password = legacy_password
145 |
146 | @staticmethod
147 | def get_default_character_set():
148 | """
149 | Returns the default character set.
150 |
151 | :return: the default character set
152 | :rtype: str
153 | """
154 | return DEFAULT_CHARACTER_SET_DIGITS + DEFAULT_CHARACTER_SET_LOWER_CASE + DEFAULT_CHARACTER_SET_UPPER_CASE + \
155 | DEFAULT_CHARACTER_SET_EXTRA
156 |
157 | @staticmethod
158 | def get_lower_case_character_set():
159 | """
160 | Returns the lower case character set.
161 |
162 | :return: the lower case character set
163 | :rtype: str
164 | """
165 | return DEFAULT_CHARACTER_SET_LOWER_CASE
166 |
167 | @staticmethod
168 | def get_upper_case_character_set():
169 | """
170 | Returns the upper case character set.
171 |
172 | :return: the upper case character set
173 | :rtype: str
174 | """
175 | return DEFAULT_CHARACTER_SET_UPPER_CASE
176 |
177 | @staticmethod
178 | def get_digits_character_set():
179 | """
180 | Returns the digits character set.
181 |
182 | :return: the digits character set
183 | :rtype: str
184 | """
185 | return DEFAULT_CHARACTER_SET_DIGITS
186 |
187 | def get_character_set(self):
188 | """
189 | Returns the character set as a string.
190 |
191 | :return: character set
192 | :rtype: str
193 | """
194 | used_characters = ""
195 | if 'n' in self.get_template():
196 | used_characters += DEFAULT_CHARACTER_SET_DIGITS
197 | if 'a' in self.get_template():
198 | used_characters += DEFAULT_CHARACTER_SET_LOWER_CASE
199 | if 'A' in self.get_template():
200 | used_characters += DEFAULT_CHARACTER_SET_UPPER_CASE
201 | if 'o' in self.get_template():
202 | used_characters += self.get_extra_character_set()
203 | return used_characters
204 |
205 | def get_extra_character_set(self):
206 | """
207 | Returns the set of special characters.
208 |
209 | :return: set of special characters
210 | :rtype: str
211 | """
212 | return self.extra_characters
213 |
214 | def set_extra_character_set(self, extra_set):
215 | """
216 | Sets the set of special characters. This function does not check if these characters are in the whole
217 | character set.
218 |
219 | :param extra_set: string of special characters
220 | :type extra_set: str
221 | """
222 | if extra_set is None or len(extra_set) <= 0:
223 | self.extra_characters = DEFAULT_CHARACTER_SET_EXTRA
224 | else:
225 | self.extra_characters = extra_set
226 |
227 | def get_salt(self):
228 | """
229 | Returns the salt.
230 |
231 | :return: the salt
232 | :rtype: bytes
233 | """
234 | return self.salt
235 |
236 | def set_salt(self, salt):
237 | """
238 | You should normally pass bytes as a salt. For convenience this method also accepts strings which get
239 | UTF-8 encoded and stored in binary format. If in doubt pass bytes.
240 |
241 | :param salt:
242 | :type salt: bytes or str
243 | """
244 | if type(salt) == bytes:
245 | if self.salt != salt:
246 | self.synced = False
247 | self.salt = salt
248 | elif type(salt) == str:
249 | if self.salt != salt.encode('utf-8'):
250 | self.synced = False
251 | self.salt = salt.encode('utf-8')
252 | else:
253 | raise TypeError("The salt should be bytes.")
254 |
255 | def new_salt(self):
256 | """
257 | Creates a new salt for the setting.
258 | """
259 | self.salt = Crypter.createSalt()
260 |
261 | def get_length(self):
262 | """
263 | Returns the desired password length.
264 |
265 | :return: length
266 | :rtype: int
267 | """
268 | return len(self.get_template())
269 |
270 | def get_iterations(self):
271 | """
272 | Returns the iteration count which is to be used.
273 |
274 | :return: iteration count
275 | :rtype: int
276 | """
277 | return self.iterations
278 |
279 | def set_iterations(self, iterations):
280 | """
281 | Sets the iteration count integer.
282 |
283 | :param iterations:
284 | :type iterations: int
285 | """
286 | if self.iterations != iterations:
287 | self.synced = False
288 | self.iterations = iterations
289 |
290 | def get_c_date(self):
291 | """
292 | Returns the creation date as a datetime object.
293 |
294 | :return: the creation date
295 | :rtype: datetime
296 | """
297 | return self.creation_date
298 |
299 | def get_creation_date(self):
300 | """
301 | Returns the creation date as string.
302 |
303 | :return: the creation date
304 | :rtype: str
305 | """
306 | return self.create_ISO_date(self.creation_date)
307 |
308 | def set_creation_date(self, creation_date):
309 | """
310 | Sets the creation date passed as string.
311 |
312 | :param creation_date:
313 | :type creation_date: str
314 | """
315 | if self.creation_date != creation_date:
316 | self.synced = False
317 | try:
318 | self.creation_date = self.convert_ISO_date(creation_date)
319 | except ValueError:
320 | print("This date has a wrong format: " + creation_date)
321 | if self.modification_date < self.creation_date:
322 | self.modification_date = self.creation_date
323 |
324 | def get_m_date(self):
325 | """
326 | Returns the modification date as a datetime object.
327 |
328 | :return: the modification date
329 | :rtype: datetime
330 | """
331 | return self.modification_date
332 |
333 | def get_modification_date(self):
334 | """
335 | Returns the modification date as string.
336 |
337 | :return: the modification date
338 | :rtype: str
339 | """
340 | return self.create_ISO_date(self.modification_date)
341 |
342 | def set_modification_date(self, modification_date=None):
343 | """
344 | Sets the modification date passed as string.
345 |
346 | :param modification_date:
347 | :type modification_date: str
348 | """
349 | if modification_date and self.modification_date != modification_date:
350 | self.synced = False
351 | if type(modification_date) == str:
352 | try:
353 | self.modification_date = self.convert_ISO_date(modification_date)
354 | except ValueError:
355 | print("This date has a wrong format: " + modification_date)
356 | else:
357 | self.modification_date = datetime.now()
358 | if self.modification_date < self.creation_date:
359 | print("The modification date was before the creation Date. " +
360 | "Setting the creation date to the earlier date.")
361 | self.creation_date = self.modification_date
362 |
363 | def get_notes(self):
364 | """
365 | Returns the notes.
366 |
367 | :return: the notes
368 | :rtype: str
369 | """
370 | if self.notes:
371 | return self.notes
372 | else:
373 | return ""
374 |
375 | def set_notes(self, notes):
376 | """
377 | Sets some note. This overwrites existing notes.
378 |
379 | :param notes:
380 | :type notes: str
381 | """
382 | if notes != self.notes:
383 | self.synced = False
384 | self.notes = notes
385 |
386 | def get_url(self):
387 | """
388 | Returns a url if there is one.
389 |
390 | :return: the url
391 | :rtype: str
392 | """
393 | if self.url:
394 | return self.url
395 | else:
396 | return ""
397 |
398 | def set_url(self, url):
399 | """
400 | Sets a url.
401 |
402 | :param url: the url
403 | :type url: str
404 | """
405 | if url != self.url:
406 | self.synced = False
407 | else:
408 | return self.url
409 |
410 | def get_full_template(self):
411 | """
412 | Constructs a template string with digit and semicolon.
413 |
414 | :return: template string
415 | :rtype: str
416 | """
417 | complexity = self.get_complexity()
418 | if complexity >= 0:
419 | return str(complexity) + ";" + self.get_template()
420 | else:
421 | return self.get_template()
422 |
423 | def calculate_template(self, use_lower_case=None, use_upper_case=None, use_digits=None, use_extra=None):
424 | """
425 | Calculates a new template based on the character set configuration and the length.
426 |
427 | :param use_extra: Gets this setting from the current template if None.
428 | :type use_extra: bool
429 | :param use_digits: Gets this setting from the current template if None.
430 | :type use_digits: bool
431 | :param use_upper_case: Gets this setting from the current template if None.
432 | :type use_upper_case: bool
433 | :param use_lower_case: Gets this setting from the current template if None.
434 | :type use_lower_case: bool
435 | """
436 | if use_lower_case is None:
437 | use_lower_case = 'a' in self.get_template()
438 | if use_upper_case is None:
439 | use_upper_case = 'A' in self.get_template()
440 | if use_digits is None:
441 | use_digits = 'n' in self.get_template()
442 | if use_extra is None:
443 | use_extra = 'o' in self.get_template()
444 | l = []
445 | inserted_lower = False
446 | inserted_upper = False
447 | inserted_digit = False
448 | inserted_extra = False
449 | for _ in range(self.get_length()):
450 | if use_lower_case and not inserted_lower:
451 | l.append('a')
452 | inserted_lower = True
453 | elif use_upper_case and not inserted_upper:
454 | l.append('A')
455 | inserted_upper = True
456 | elif use_digits and not inserted_digit:
457 | l.append('n')
458 | inserted_digit = True
459 | elif use_extra and not inserted_extra:
460 | l.append('o')
461 | inserted_extra = True
462 | else:
463 | l.append('x')
464 | shuffle(l)
465 | self.template = ''.join(l)
466 |
467 | def get_template(self):
468 | """
469 | Returns the template without digit and semicolon.
470 |
471 | :return: template
472 | :rtype: str
473 | """
474 | return self.template
475 |
476 | def set_template(self, full_template):
477 | """
478 | Sets a template from a complete template string with digit and semicolon. This also preferences the template
479 | so other settings might get ignored.
480 |
481 | :param full_template: complete template string
482 | :type full_template: str
483 | """
484 | matches = re.compile("(([01234567]);)?([aAnox]+)").match(full_template)
485 | if matches and len(matches.groups()) >= 3:
486 | if matches.group(2):
487 | self.set_complexity(int(matches.group(2)))
488 | self.template = matches.group(3)
489 |
490 | def set_complexity(self, complexity):
491 | """
492 | Sets the complexity by activating the appropriate character groups.
493 |
494 | :param complexity: 0, 1, 2, 3, 4, 5, 6 or 7
495 | :type complexity: int
496 | """
497 | if not 0 <= complexity <= 7:
498 | ValueError("The complexity must be in the range 0 to 7.")
499 |
500 | def get_complexity(self):
501 | """
502 | Returns the complexity as a digit from 0 to 6. If the character selection does not match a complexity
503 | group -1 is returned.
504 |
505 | :return: a digit from 0 to 6 or -1
506 | :rtype: int
507 | """
508 | if 'n' in self.get_template() and 'a' not in self.get_template() and \
509 | 'A' not in self.get_template() and 'o' not in self.get_template():
510 | return 0
511 | elif 'n' not in self.get_template() and 'a' in self.get_template() and \
512 | 'A' not in self.get_template() and 'o' not in self.get_template():
513 | return 1
514 | elif 'n' not in self.get_template() and 'a' not in self.get_template() and \
515 | 'A' in self.get_template() and 'o' not in self.get_template():
516 | return 2
517 | elif 'n' in self.get_template() and 'a' in self.get_template() and \
518 | 'A' not in self.get_template() and 'o' not in self.get_template():
519 | return 3
520 | elif 'n' not in self.get_template() and 'a' in self.get_template() and \
521 | 'A' in self.get_template() and 'o' not in self.get_template():
522 | return 4
523 | elif 'n' in self.get_template() and 'a' in self.get_template() and \
524 | 'A' in self.get_template() and 'o' not in self.get_template():
525 | return 5
526 | elif 'n' in self.get_template() and 'a' in self.get_template() and \
527 | 'A' in self.get_template() and 'o' in self.get_template():
528 | return 6
529 | elif 'n' not in self.get_template() and 'a' not in self.get_template() and \
530 | 'A' not in self.get_template() and 'o' in self.get_template():
531 | return 7
532 | else:
533 | return -1
534 |
535 | def is_synced(self):
536 | """
537 | Query if the synced flag is set. The flag switches to false if settings are changed.
538 |
539 | :return: is synced?
540 | :rtype: bool
541 | """
542 | return self.synced
543 |
544 | def set_synced(self, is_synced=True):
545 | """
546 | Sets the synced state. Call this after syncing.
547 |
548 | :param is_synced:
549 | :type is_synced: bool
550 | """
551 | self.synced = is_synced
552 |
553 | def to_dict(self):
554 | """
555 | Returns a dictionary with settings to be saved.
556 |
557 | :return: a dictionary with settings to be saved
558 | :rtype: dict
559 | """
560 | domain_object = {"domain": self.get_domain()}
561 | if self.get_url():
562 | domain_object["url"] = self.get_url()
563 | if self.get_username():
564 | domain_object["username"] = self.get_username()
565 | if self.get_legacy_password():
566 | domain_object["legacyPassword"] = self.get_legacy_password()
567 | if self.notes:
568 | domain_object["notes"] = self.get_notes()
569 | domain_object["iterations"] = self.get_iterations()
570 | if self.salt:
571 | domain_object["salt"] = str(b64encode(self.get_salt()), encoding='utf-8')
572 | domain_object["cDate"] = self.get_creation_date()
573 | domain_object["mDate"] = self.get_modification_date()
574 | domain_object["extras"] = self.get_extra_character_set()
575 | domain_object["passwordTemplate"] = self.get_template()
576 | return domain_object
577 |
578 | def load_from_dict(self, loaded_setting):
579 | """
580 | Loads the setting from a dictionary.
581 |
582 | :param loaded_setting:
583 | :type loaded_setting: dict
584 | """
585 | if "url" in loaded_setting:
586 | self.set_url(loaded_setting["url"])
587 | if "username" in loaded_setting:
588 | self.set_username(loaded_setting["username"])
589 | if "legacyPassword" in loaded_setting:
590 | self.set_legacy_password(loaded_setting["legacyPassword"])
591 | if "notes" in loaded_setting:
592 | self.set_notes(loaded_setting["notes"])
593 | if "iterations" in loaded_setting:
594 | self.set_iterations(loaded_setting["iterations"])
595 | if "salt" in loaded_setting:
596 | self.set_salt(b64decode(loaded_setting["salt"]))
597 | if "cDate" in loaded_setting:
598 | self.set_creation_date(loaded_setting["cDate"])
599 | if "mDate" in loaded_setting:
600 | self.set_modification_date(loaded_setting["mDate"])
601 | if "extras" in loaded_setting:
602 | self.set_extra_character_set(loaded_setting["extras"])
603 | if "passwordTemplate" in loaded_setting:
604 | self.set_template(loaded_setting["passwordTemplate"])
605 | if "length" in loaded_setting and "usedCharacters" in loaded_setting and \
606 | "passwordTemplate" not in loaded_setting:
607 | self.template = "o"*int(loaded_setting["length"])
608 | self.set_extra_character_set(loaded_setting["usedCharacters"])
609 | self.calculate_template(False, False, False, True)
610 |
611 | def ask_for_input(self):
612 | """
613 | Displays some input prompts for the settings properties.
614 | """
615 | self.set_username(input('Benutzername: '))
616 | wants_legacy_password = input('Möchten Sie ein Passwort generieren (Alternative: nur speichern)? [J/n] ')
617 | if wants_legacy_password in ['n', 'N', 'speichern', 'save', 'no', 'nein', 'Nein', 'No', 'Nay']:
618 | self.set_legacy_password(getpass.getpass('klassisches Passwort: '))
619 | else:
620 | length_str = input('Passwortlänge [' + str(self.get_length()) + ']: ')
621 | try:
622 | length = int(length_str)
623 | if length <= 0:
624 | length = self.get_length()
625 | except ValueError:
626 | length = self.get_length()
627 | self.set_template("6;" + "x"*length)
628 | self.calculate_template(True, True, True, True)
629 | iterations_str = input('Iterationszahl [' + str(self.get_iterations()) + ']: ')
630 | try:
631 | iterations = int(iterations_str)
632 | if iterations <= 0:
633 | iterations = self.get_iterations()
634 | except ValueError:
635 | iterations = self.get_iterations()
636 | self.set_iterations(iterations)
637 |
638 | @staticmethod
639 | def convert_ISO_date(date_str):
640 | """
641 | Converts an ISO date with or without microseconds
642 |
643 | :param date_str:
644 | :type date_str: str
645 | :return: converted datetime
646 | :rtype: datetime
647 | """
648 | if re.match(r'^(?P\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}).(?P\d*)$', date_str):
649 | return datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%f")
650 | else:
651 | return datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S")
652 |
653 | @staticmethod
654 | def create_ISO_date(date):
655 | """
656 | Creates a string in ISO format with microsends (3 digits).
657 |
658 | :param date:
659 | :type date: datetime
660 | :return: datetime as a string in ISO format with microseconds
661 | :rtype: str
662 | """
663 | return date.strftime("%Y-%m-%dT%H:%M:%S") + ".{0:03d}".format(date.microsecond)
664 |
--------------------------------------------------------------------------------
/password_settings_manager.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | The PasswordSettingsManager handles the settings and manages storage and synchronization.
5 | """
6 |
7 | import json
8 | import struct
9 | from datetime import datetime
10 | from password_setting import PasswordSetting
11 | from crypter import Crypter
12 | from packer import Packer
13 | from sync_manager import SyncManager
14 | from base64 import b64decode, b64encode
15 | from kgk_manager import KgkManager
16 |
17 |
18 | class PasswordSettingsManager(object):
19 | """
20 | Use this class to manage password settings. It can save the settings locally to the settings file and it can
21 | export them to be sent to a sync server.
22 |
23 | :param preference_manager: a PreferenceManager object
24 | :type preference_manager: PreferenceManager
25 | """
26 | def __init__(self, preference_manager):
27 | self.preference_manager = preference_manager
28 | self.remote_data = None
29 | self.settings = []
30 | self.sync_manager = SyncManager()
31 | self.update_remote = False
32 |
33 | @staticmethod
34 | def get_settings_crypter(kgk_manager):
35 | """
36 | Creates a settings crypter
37 |
38 | :param kgk_manager: a kgk manager
39 | :type kgk_manager: KgkManager
40 | :return: Crypter for settings
41 | :rtype: Crypter
42 | """
43 | return Crypter(Crypter.create_key(kgk_manager.get_kgk(), kgk_manager.get_salt2()) + kgk_manager.get_iv2())
44 |
45 | def load_local_settings(self, kgk_manager):
46 | """
47 | This loads the saved settings. It is a good idea to call this method the minute you have a kgk manager.
48 |
49 | :param kgk_manager: kgk manager
50 | :type kgk_manager: KgkManager
51 | """
52 | encrypted_settings = self.preference_manager.get_settings_data()
53 | if len(encrypted_settings) < 40:
54 | return
55 | settings_crypter = PasswordSettingsManager.get_settings_crypter(kgk_manager)
56 | decrypted_settings = settings_crypter.decrypt(encrypted_settings)
57 | sync_settings_len = struct.unpack('!I', decrypted_settings[0:4])[0]
58 | if sync_settings_len > 0:
59 | self.sync_manager.load_binary_sync_settings(decrypted_settings[4:4+sync_settings_len])
60 | if len(decrypted_settings) < sync_settings_len+44:
61 | raise ValueError("The decrypted settings are too short.")
62 | decompressed_settings = Packer.decompress(decrypted_settings[4+sync_settings_len:])
63 | if len(decompressed_settings) <= 0:
64 | raise PermissionError("Wrong password: The settings could not decompress.")
65 | saved_settings = json.loads(str(decompressed_settings, encoding='utf-8'))
66 | for domain_name in saved_settings['settings'].keys():
67 | data_set = saved_settings['settings'][domain_name]
68 | found = False
69 | i = 0
70 | while i < len(self.settings):
71 | setting = self.settings[i]
72 | if setting.get_domain() == domain_name:
73 | found = True
74 | if PasswordSetting.create_ISO_date(data_set['mDate']) > setting.get_m_date():
75 | setting.load_from_dict(data_set)
76 | setting.set_synced(setting.get_domain() in saved_settings['synced'])
77 | i += 1
78 | if not found:
79 | new_setting = PasswordSetting(domain_name)
80 | new_setting.load_from_dict(data_set)
81 | new_setting.set_synced(new_setting.get_domain() in saved_settings['synced'])
82 | self.settings.append(new_setting)
83 |
84 | def store_local_settings(self, kgk_manager):
85 | """
86 | This actually saves the settings to a file on the disk. The file is encrypted so you need to supply the
87 | password.
88 |
89 | :param kgk_manager: kgk manager
90 | :type kgk_manager: KgkManager
91 | """
92 | kgk_manager.fresh_salt2()
93 | kgk_manager.fresh_iv2()
94 | settings_crypter = PasswordSettingsManager.get_settings_crypter(kgk_manager)
95 | sync_settings = self.sync_manager.get_binary_sync_settings()
96 | self.preference_manager.store_settings_data(settings_crypter.encrypt(
97 | struct.pack('!I', len(sync_settings)) + sync_settings +
98 | Packer.compress(json.dumps(self.get_settings_as_dict()))))
99 | kgk_manager.store_local_kgk_block()
100 |
101 | def load_settings(self, kgk_manager, password, no_sync=False):
102 | """
103 | Loads settings from local file and from a sync server if possible.
104 |
105 | :param kgk_manager: kgk manager
106 | :type kgk_manager: KgkManager
107 | :param password: the masterpassword
108 | :type password: str
109 | :param no_sync: skip the sync update?
110 | :type no_sync: bool
111 | """
112 | self.load_local_settings(kgk_manager)
113 | if not no_sync:
114 | if self.sync_manager.has_settings():
115 | pull_successful, data = self.sync_manager.pull()
116 | if pull_successful and len(data) > 0:
117 | remote_kgk_manager = KgkManager()
118 | remote_kgk_manager.update_from_blob(password.encode('utf-8'), b64decode(data))
119 | if remote_kgk_manager.has_kgk() and kgk_manager.get_kgk() != remote_kgk_manager.get_kgk():
120 | raise ValueError("KGK mismatch! This are not your settings!")
121 | self.update_from_export_data(remote_kgk_manager, b64decode(data))
122 | else:
123 | print("Sync failed: No connection to the server.")
124 |
125 | def get_setting(self, domain):
126 | """
127 | This function always returns a setting. If no setting was stored for the given domain a new PasswordSetting
128 | object is created.
129 |
130 | :param domain: The "domain" is the identifier of a settings object.
131 | :type domain: str
132 | :return: a setting object
133 | :rtype: PasswordSetting
134 | """
135 | for setting in self.settings:
136 | if setting.get_domain() == domain:
137 | return setting
138 | setting = PasswordSetting(domain)
139 | self.settings.append(setting)
140 | return setting
141 |
142 | def set_setting(self, setting):
143 | """
144 | This saves the supplied setting only in memory. Call save_settings_to_file if you want to have it saved to
145 | disk.
146 |
147 | :param PasswordSetting setting: the setting which should be saved
148 | """
149 | for i, existing_setting in enumerate(self.settings):
150 | if existing_setting.get_domain() == setting.get_domain():
151 | self.settings.pop(i)
152 | self.settings.append(setting)
153 | self.update_remote = True
154 |
155 | def delete_setting(self, setting):
156 | """
157 | This removes the setting from the internal list. Call save_settings_to_file if you want to have the change
158 | saved to disk.
159 |
160 | :param setting: PasswordSetting object
161 | :type setting: PasswordSetting
162 | """
163 | i = 0
164 | while i < len(self.settings):
165 | existing_setting = self.settings[i]
166 | if existing_setting.get_domain() == setting.get_domain():
167 | self.settings.pop(i)
168 | else:
169 | i += 1
170 |
171 | def get_domain_list(self):
172 | """
173 | This gives you a list of saved domains.
174 |
175 | :return: a list of domain names
176 | :rtype: [str]
177 | """
178 | return [setting.get_domain() for setting in self.settings]
179 |
180 | def get_settings_as_dict(self):
181 | """
182 | Constructs a dictionary with a list of settings (no PasswordSetting objects but dicts) and a list of
183 | domain names of synced domains.
184 |
185 | :return: a dictionary
186 | :rtype: dict
187 | """
188 | settings_dict = {'settings': {}, 'synced': []}
189 | for setting in self.settings:
190 | settings_dict['settings'][setting.get_domain()] = setting.to_dict()
191 | if setting.is_synced():
192 | settings_dict['synced'].append(setting.get_domain())
193 | return settings_dict
194 |
195 | def get_export_data(self, kgk_manager):
196 | """
197 | This gives you a base64 encoded string of encrypted settings data (the blob).
198 |
199 | :param kgk_manager: kgk manager
200 | :type kgk_manager: KgkManager
201 | :return: encrypted settings blob
202 | :rtype: str
203 | """
204 | kgk_block = kgk_manager.get_fresh_encrypted_kgk()
205 | settings_list = self.get_settings_as_dict()['settings']
206 | if self.remote_data:
207 | for domain_name in self.remote_data.keys():
208 | data_set = self.remote_data[domain_name]
209 | if 'deleted' in data_set and data_set['deleted']:
210 | for i, setting_dict in enumerate(settings_list):
211 | if setting_dict['domain'] == setting_dict['domain'] and \
212 | PasswordSetting.convert_ISO_date(data_set['mDate']) > \
213 | PasswordSetting.convert_ISO_date(setting_dict['mDate']):
214 | settings_list[i] = data_set
215 | if domain_name not in settings_list.keys():
216 | settings_list[domain_name] = {
217 | 'mDate': datetime.now(),
218 | 'deleted': True
219 | }
220 | settings_crypter = self.get_settings_crypter(kgk_manager)
221 | return b64encode(b'\x01' + kgk_manager.get_kgk_crypter_salt() + kgk_block + settings_crypter.encrypt(
222 | Packer.compress(json.dumps(settings_list))))
223 |
224 | def update_from_export_data(self, kgk_manager, blob):
225 | """
226 | Call this method to pull settings from the sync server.
227 |
228 | :param kgk_manager: the kgk manager used for the decryption
229 | :type kgk_manager: KgkManager
230 | :param blob: the export data
231 | :type blob: bytes
232 | """
233 | if not blob[0] == 1:
234 | print("Version error: Wrong data format. Could not import anything.")
235 | return True
236 | settings_crypter = self.get_settings_crypter(kgk_manager)
237 | decrypted_settings = settings_crypter.decrypt(blob[145:])
238 | if len(decrypted_settings) <= 0:
239 | print("Wrong password.")
240 | return False
241 | self.remote_data = json.loads(str(Packer.decompress(decrypted_settings), encoding='utf-8'))
242 | self.update_remote = False
243 | for domain_name in self.remote_data.keys():
244 | data_set = self.remote_data[domain_name]
245 | found = False
246 | i = 0
247 | while i < len(self.settings):
248 | setting = self.settings[i]
249 | if setting.get_domain() == domain_name:
250 | found = True
251 | if 'mDate' in data_set:
252 | last_modification_date = data_set['mDate']
253 | else:
254 | last_modification_date = data_set['cDate']
255 | if PasswordSetting.convert_ISO_date(last_modification_date) > setting.get_m_date():
256 | if 'deleted' in data_set and data_set['deleted']:
257 | self.settings.pop(i)
258 | else:
259 | setting.load_from_dict(data_set)
260 | setting.set_synced(True)
261 | self.update_remote = True
262 | i += 1
263 | else:
264 | i += 1
265 | else:
266 | i += 1
267 | if not found:
268 | new_setting = PasswordSetting(domain_name)
269 | new_setting.load_from_dict(data_set)
270 | new_setting.set_synced(True)
271 | self.settings.append(new_setting)
272 | for setting in self.settings:
273 | found = False
274 | for domain_name in self.remote_data.keys():
275 | data_set = self.remote_data[domain_name]
276 | if setting.get_domain() == domain_name:
277 | found = True
278 | if 'mDate' in data_set:
279 | last_modification_date = data_set['mDate']
280 | else:
281 | last_modification_date = data_set['cDate']
282 | if setting.get_m_date() >= PasswordSetting.convert_ISO_date(last_modification_date):
283 | self.update_remote = True
284 | if not found:
285 | self.update_remote = True
286 | self.store_local_settings(kgk_manager)
287 | return self.update_remote
288 |
289 | def store_settings(self, kgk_manager):
290 | """
291 | Stores settings locally and remotely.
292 |
293 | :param kgk_manager: the kgk manager used for the encryption
294 | :type kgk_manager: KgkManager
295 | """
296 | self.store_local_settings(kgk_manager)
297 | self.update_sync_server_if_necessary(kgk_manager)
298 |
299 | def update_sync_server_if_necessary(self, kgk_manager):
300 | """
301 | Checks if the sync server needs to be updated. If necessary it does a push.
302 |
303 | :param kgk_manager: the kgk manager used for the encryption
304 | :type kgk_manager: KgkManager
305 | """
306 | if self.update_remote:
307 | if self.sync_manager.push(self.get_export_data(kgk_manager)):
308 | self.set_all_settings_to_synced()
309 |
310 | def set_all_settings_to_synced(self):
311 | """
312 | Convenience function for marking all saved settings as synced. Call this after a successful update at the
313 | sync server.
314 | """
315 | for setting in self.settings:
316 | setting.set_synced(True)
317 |
--------------------------------------------------------------------------------
/preference_manager.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | The preference manager handles the access to the settings file.
5 | """
6 | import os
7 |
8 | PASSWORD_SETTINGS_FILE = os.path.expanduser('~/.config/ct/ctSESAM.pws')
9 |
10 |
11 | class PreferenceManager(object):
12 | """
13 |
14 |
15 | :param settings_file: Filename of the settings file. Defaults to PASSWORD_SETTINGS_FILE as defined in the source
16 | :type settings_file: str
17 | """
18 | def __init__(self, settings_file=PASSWORD_SETTINGS_FILE):
19 | self.data = b''
20 | self.settings_file = settings_file
21 | self.read_file()
22 |
23 | def read_file(self):
24 | """
25 | Read the settings file.
26 | """
27 | if os.path.isfile(self.settings_file):
28 | with open(self.settings_file, 'rb') as f:
29 | self.data = f.read()
30 |
31 | def get_salt(self):
32 | """
33 | Reads the salt.
34 |
35 | :return: the salt
36 | :rtype: bytes
37 | """
38 | return self.data[:32]
39 |
40 | def store_salt(self, salt):
41 | """
42 | Writes the salt into the first 32 bytes of the file.
43 |
44 | :param salt: 32 bytes salt
45 | :type salt: bytes
46 | """
47 | if type(salt) != bytes:
48 | raise TypeError("The salt must be bytes.")
49 | if len(salt) != 32:
50 | raise ValueError("The salt has to be 32 bytes.")
51 | if os.path.isfile(self.settings_file):
52 | with open(self.settings_file, 'rb+') as f:
53 | f.seek(0)
54 | f.write(salt)
55 | else:
56 | if not os.path.exists(os.path.dirname(self.settings_file)):
57 | os.makedirs(os.path.dirname(self.settings_file))
58 | with open(self.settings_file, 'wb') as f:
59 | f.write(salt)
60 | self.data = salt + self.data[32:]
61 | self.set_hidden()
62 |
63 | def get_kgk_block(self):
64 | """
65 | Reads the kgk_block.
66 |
67 | :return: 112 bytes of kgk data
68 | :rtype: bytes
69 | """
70 | return self.data[32:144]
71 |
72 | def store_kgk_block(self, kgk_block):
73 | """
74 | Writes the kgk_block into bytes 32 to 143.
75 |
76 | :param kgk_block: encrypted kgk data
77 | :type kgk_block: bytes
78 | """
79 | if type(kgk_block) != bytes:
80 | raise TypeError("The kgk_block must be bytes.")
81 | if len(kgk_block) != 112:
82 | raise ValueError("The kgk_block has to be 112 bytes.")
83 | if os.path.isfile(self.settings_file):
84 | with open(self.settings_file, 'rb+') as f:
85 | f.seek(32)
86 | f.write(kgk_block)
87 | else:
88 | if not os.path.exists(os.path.dirname(self.settings_file)):
89 | os.makedirs(os.path.dirname(self.settings_file))
90 | with open(self.settings_file, 'wb') as f:
91 | f.write(b'\x00'*32)
92 | f.write(kgk_block)
93 | self.data = self.data[:32] + kgk_block + self.data[144:]
94 | self.set_hidden()
95 |
96 | def get_settings_data(self):
97 | """
98 | Reads the settings data.
99 |
100 | :return: encrypted settings
101 | :rtype: bytes
102 | """
103 | return self.data[144:]
104 |
105 | def store_settings_data(self, settings_data):
106 | """
107 | Writes the settings data after byte 144.
108 |
109 | :param settings_data: encrypted settings data
110 | :type settings_data: bytes
111 | """
112 | if type(settings_data) != bytes:
113 | raise TypeError("The kgk_block must be bytes.")
114 | if os.path.isfile(self.settings_file):
115 | with open(self.settings_file, 'rb+') as f:
116 | f.seek(144)
117 | f.write(settings_data)
118 | f.truncate()
119 | else:
120 | if not os.path.exists(os.path.dirname(self.settings_file)):
121 | os.makedirs(os.path.dirname(self.settings_file))
122 | with open(self.settings_file, 'wb') as f:
123 | f.write(b'\x00'*144)
124 | f.write(settings_data)
125 | self.data = self.data[:144] + settings_data
126 | self.set_hidden()
127 |
128 | # noinspection PyUnresolvedReferences
129 | def set_hidden(self):
130 | """
131 | Hides the settings file if possible.
132 | """
133 | try:
134 | import win32con
135 | import win32api
136 | win32api.SetFileAttributes(self.settings_file, win32con.FILE_ATTRIBUTE_HIDDEN)
137 | except ImportError:
138 | pass
139 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pycrypto
2 | requests
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | from __future__ import division, print_function, unicode_literals
4 | # Noting to do here
5 |
--------------------------------------------------------------------------------
/sync.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | import requests
5 | import json
6 | import base64
7 | import os
8 |
9 |
10 | class Sync(object):
11 | """
12 | Sync connection wrapper.
13 |
14 | :param str server_url: https://my.server.domain/path/to/php/
15 | :param str username:
16 | :param str password:
17 | """
18 | def __init__(self, server_url, username, password, cert_filename=None):
19 | self.server_url = server_url
20 | self.username = username
21 | self.password = password
22 | self.certificate_filename = cert_filename
23 | self.headers = {
24 | 'content-type': 'application/x-www-form-urlencoded',
25 | 'Authorization': 'Basic ' + str(base64.b64encode(
26 | (self.username + ':' + self.password).encode('utf-8')
27 | ), encoding='utf-8')
28 | }
29 |
30 | def pull(self):
31 | """
32 | Read the base64 encoded data from the sync server.
33 |
34 | :return: base64 encoded data
35 | :rtype: str
36 | """
37 | if self.server_url[-1] == "/":
38 | url = self.server_url + "ajax/read.php"
39 | else:
40 | url = self.server_url + "/ajax/read.php"
41 | if self.certificate_filename is None:
42 | request = requests.post(url,
43 | data="",
44 | headers=self.headers)
45 | else:
46 | request = requests.post(url,
47 | data="",
48 | headers=self.headers,
49 | verify=os.path.join(os.path.dirname(os.path.realpath(__file__)),
50 | self.certificate_filename))
51 | if request.status_code == requests.codes.ok:
52 | received_data = json.loads(request.text)
53 | if 'status' in received_data and received_data['status']:
54 | if 'result' in received_data:
55 | return True, received_data['result']
56 | else:
57 | return True, ''
58 | else:
59 | return False, ''
60 | else:
61 | return False, ''
62 |
63 | def push(self, data):
64 | """
65 | Push data to the server. This overwrites data living there. Please pull and merge first.
66 |
67 | :param str data: base64 encoded data
68 | :return: was the push successful?
69 | :rtype: bool
70 | """
71 | if self.server_url[-1] == "/":
72 | url = self.server_url + "ajax/write.php"
73 | else:
74 | url = self.server_url + "/ajax/write.php"
75 | if self.certificate_filename is None:
76 | response = requests.post(url,
77 | data={'data': data},
78 | headers=self.headers)
79 | else:
80 | response = requests.post(url,
81 | data={'data': data},
82 | headers=self.headers,
83 | verify=os.path.join(os.path.dirname(os.path.realpath(__file__)),
84 | self.certificate_filename))
85 | if response.status_code == requests.codes.ok:
86 | return True
87 | else:
88 | return False
89 |
--------------------------------------------------------------------------------
/sync_manager.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Manages Sync connections.
5 | """
6 |
7 | from sync import Sync
8 | from packer import Packer
9 | from tempfile import NamedTemporaryFile
10 | import json
11 |
12 |
13 | class SyncManager(object):
14 | """
15 | Synchronization manager. This initializes and stores settings and handles the Sync object.
16 | """
17 | def __init__(self):
18 | self.server_address = ""
19 | self.username = ""
20 | self.password = ""
21 | self.certificate = None
22 | self.certificate_file = None
23 | self.sync = None
24 |
25 | def __del__(self):
26 | if self.certificate_file:
27 | self.certificate_file.close()
28 |
29 | def get_binary_sync_settings(self):
30 | """
31 | returns packed sync settings
32 |
33 | :return: binary settings
34 | :rtype: bytes
35 | """
36 | if self.sync:
37 | return Packer.compress(json.dumps({
38 | "server-address": self.server_address,
39 | "username": self.username,
40 | "password": self.password,
41 | "certificate": self.certificate if self.certificate is not None else ""
42 | }).encode('utf-8'))
43 | else:
44 | return b''
45 |
46 | def create_certificate_file_if_needed(self):
47 | """
48 | creates a temporary file with the certificate data if self.certificate is not None
49 | """
50 | if self.certificate_file:
51 | self.certificate_file.close()
52 | if self.certificate is not None:
53 | self.certificate_file = NamedTemporaryFile()
54 | self.certificate_file.write(self.certificate.encode('utf-8'))
55 | self.certificate_file.seek(0)
56 |
57 | def load_binary_sync_settings(self, data):
58 | """
59 | loads sync settings
60 |
61 | :param bytes data: packed json data of sync settings
62 | """
63 | settings_dict = json.loads(str(Packer.decompress(data), encoding='utf-8'))
64 | if "server-address" in settings_dict and \
65 | "username" in settings_dict and \
66 | "password" in settings_dict:
67 | self.server_address = settings_dict["server-address"]
68 | self.username = settings_dict["username"]
69 | self.password = settings_dict["password"]
70 | self.certificate = None
71 | if "certificate" in settings_dict:
72 | self.certificate = settings_dict["certificate"] if len(settings_dict["certificate"]) > 0 else None
73 | self.create_certificate_file_if_needed()
74 | self.create_sync()
75 |
76 | def ask_for_sync_settings(self):
77 | """
78 | Ask the user for sync settings: Asks for server-URL, username and password.
79 | """
80 | print("Bitte geben Sie die Einstellungen für Ihren Synchronisations-Server an...")
81 | self.server_address = input("URL: ")
82 | self.username = input("Benutzername: ")
83 | self.password = input("Passwort: ")
84 | print("Zertifikat oder Zertifikatskette im .pem-Format (beenden mit einer Leerzeile): ")
85 | line = input("Einfach mit Enter leer lassen, falls Ihr Sync-Server kein Self-Signed-Zetifikat benutzt " +
86 | "(Let's Encrypt zum Beispiel): ")
87 | self.certificate = ""
88 | while len(line) > 0:
89 | self.certificate += line + "\n"
90 | line = input("")
91 | self.certificate += line
92 | if len(self.certificate.strip()) == 0:
93 | self.certificate = None
94 | self.create_certificate_file_if_needed()
95 | self.create_sync()
96 |
97 | def set_server_address(self, url):
98 | """
99 | Sets the url without ajax folder and php file names but with https://
100 |
101 | :param url: the url
102 | :type url: str
103 | """
104 | self.server_address = url
105 |
106 | def set_username(self, username):
107 | """
108 | Sets the username.
109 |
110 | :param username: the username
111 | :type username: str
112 | """
113 | self.username = username
114 |
115 | def set_password(self, password):
116 | """
117 | Sets the password.
118 |
119 | :param password: the password
120 | :type password: str
121 | """
122 | self.password = password
123 |
124 | def set_certificate(self, certificate):
125 | """
126 | Sets the certificate from a string in PEM format.
127 |
128 | :param certificate: certificate in PEM format
129 | :type certificate: str
130 | """
131 | self.certificate = certificate
132 | if self.certificate_file:
133 | self.certificate_file.close()
134 | self.certificate_file = NamedTemporaryFile()
135 | self.certificate_file.write(self.certificate.encode('utf-8'))
136 | self.certificate_file.seek(0)
137 |
138 | def create_sync(self):
139 | """
140 | creates a sync object.
141 | """
142 | if self.certificate_file is None:
143 | self.sync = Sync(self.server_address, self.username, self.password)
144 | else:
145 | self.sync = Sync(self.server_address, self.username, self.password, self.certificate_file.name)
146 |
147 | def has_settings(self):
148 | """
149 | Returns true if pull or push are possible
150 |
151 | :return: Are there settings?
152 | :rtype: bool
153 | """
154 | return bool(self.sync)
155 |
156 | def pull(self):
157 | """
158 | pulls data from the sync server. Returns an empty string if no connection is possible.
159 |
160 | :return: pulled base64 data
161 | :rtype: str
162 | """
163 | if self.sync:
164 | return self.sync.pull()
165 | else:
166 | return False, ''
167 |
168 | def push(self, data):
169 | """
170 | pushes data to the sync server. If the push fails an error message is displayed.
171 |
172 | :param str data: base64 data
173 | """
174 | if self.sync:
175 | if not self.sync.push(data):
176 | print("Synchronisation fehlgeschlagen.")
177 | else:
178 | print("Sie haben keine gültigen Einstellungen für den sync server.")
179 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
--------------------------------------------------------------------------------
/tests/test_Crypter.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | import unittest
5 | from crypter import Crypter
6 | from base64 import b64encode, b64decode
7 |
8 |
9 | class TestCrypter(unittest.TestCase):
10 | def test_encrypt(self):
11 | message_string = "Important information with quite some length. " + \
12 | "This message is as long as this because otherwise only one cipher block would " + \
13 | "be encrypted. This long message insures that more than one block is needed."
14 | password = "secret"
15 | message = message_string.encode('utf-8')
16 | crypter = Crypter(Crypter.createIvKey(password.encode('utf-8'), "pepper".encode('utf-8'), iterations=3))
17 | ciphertext = crypter.encrypt(message)
18 | self.assertEqual(
19 | b'EFEgY5bexGnwjGSUQKK35TPD7fAjG66REq5m9N1eyFHrZQwzv+aLc7bVmJ9FzCyxbCnbyUnzDKiY505br' +
20 | b'oEb+KO41XKW668xJzh/JvOK0Cu/+bc4/zSFHZM6JsTYEVDIXgR39ZlypeB34jDVI2544w1ey+DmTWbe8n' +
21 | b'UbagjnmRkok6kOAq8Avsf9BVJMw3BnSn/4cCC+gOxOJY5fp4DecNDQnp0HyyUz2VMMh/JUYILS5+67fXq' +
22 | b'29CbIQ1DOTqDfqRPA62nkRVPY83cKIe/UXw==',
23 | b64encode(ciphertext))
24 |
25 | def test_decrypt(self):
26 | ciphertext = b'EFEgY5bexGnwjGSUQKK35TPD7fAjG66REq5m9N1eyFHrZQwzv+aLc7bVmJ9FzCyxbCnbyUnzDKiY505br' + \
27 | b'oEb+KO41XKW668xJzh/JvOK0Cu/+bc4/zSFHZM6JsTYEVDIXgR39ZlypeB34jDVI2544w1ey+DmTWbe8n' + \
28 | b'UbagjnmRkok6kOAq8Avsf9BVJMw3BnSn/4cCC+gOxOJY5fp4DecNDQnp0HyyUz2VMMh/JUYILS5+67fXq' + \
29 | b'29CbIQ1DOTqDfqRPA62nkRVPY83cKIe/UXw=='
30 | self.assertEqual(0, len(b64decode(ciphertext)) % 16)
31 | password = "secret"
32 | crypter = Crypter(Crypter.createIvKey(password.encode('utf-8'), "pepper".encode('utf-8'), iterations=3))
33 | self.assertEqual(b'Important information with quite some length. ' +
34 | b'This message is as long as this because otherwise only one cipher block would ' +
35 | b'be encrypted. This long message insures that more than one block is needed.',
36 | crypter.decrypt(b64decode(ciphertext)))
37 |
38 | if __name__ == '__main__':
39 | unittest.main()
40 |
--------------------------------------------------------------------------------
/tests/test_KgkManager.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | import unittest
5 | from kgk_manager import KgkManager
6 | from crypter import Crypter
7 |
8 |
9 | class TestKgkManager(unittest.TestCase):
10 | def test_str(self):
11 | kgkm = KgkManager()
12 | self.assertEqual("", str(kgkm))
13 | kgkm.salt2 = b"\x01"*32
14 | kgkm.iv2 = b"\x02"*16
15 | self.assertEqual("",
17 | str(kgkm))
18 | kgkm.salt = b"\x03"*32
19 | kgkm.kgk = b"\x04"*64
20 | self.assertEqual("",
25 | str(kgkm))
26 |
27 | def test_get_kgk_has_kgk(self):
28 | kgkm = KgkManager()
29 | self.assertEqual(b'', kgkm.get_kgk())
30 | self.assertFalse(kgkm.has_kgk())
31 | kgkm.kgk = b"\xE4"*64
32 | kgkm.kgk_crypter = Crypter(Crypter.createIvKey(b'1234', b'pepper', iterations=3))
33 | self.assertEqual(b"\xE4"*64, kgkm.get_kgk())
34 | self.assertTrue(kgkm.has_kgk())
35 |
36 | def test_get_iv2(self):
37 | kgkm = KgkManager()
38 | kgkm.iv2 = b"\x02"*16
39 | self.assertEqual(b"\x02"*16, kgkm.get_iv2())
40 |
41 | def test_get_salt2(self):
42 | kgkm = KgkManager()
43 | kgkm.salt2 = b"\x3A"*32
44 | self.assertEqual(b"\x3A"*32, kgkm.get_salt2())
45 |
46 | def test_fresh_iv2(self):
47 | kgkm = KgkManager()
48 | kgkm.iv2 = b"\x02"*16
49 | self.assertEqual(b"\x02"*16, kgkm.get_iv2())
50 | kgkm.fresh_iv2()
51 | self.assertNotEqual(b"\x02"*16, kgkm.get_iv2())
52 | self.assertEqual(16, len(kgkm.get_iv2()))
53 |
54 | def test_fresh_salt2(self):
55 | kgkm = KgkManager()
56 | kgkm.salt2 = b"\x3A"*32
57 | self.assertEqual(b"\x3A"*32, kgkm.get_salt2())
58 | kgkm.fresh_salt2()
59 | self.assertNotEqual(b"\x3A"*32, kgkm.get_salt2())
60 | self.assertEqual(32, len(kgkm.get_salt2()))
61 |
--------------------------------------------------------------------------------
/tests/test_Packer.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | import unittest
5 | from packer import Packer
6 | from base64 import b64decode, b64encode
7 |
8 |
9 | class TestPacker(unittest.TestCase):
10 | def test_compress(self):
11 | packed_data = Packer.compress("Some packable information")
12 | self.assertEqual(b'AAAAGXjaC87PTVUoSEzOTkzKSVXIzEvLL8pNLMnMzwMAedUJrg==', b64encode(packed_data))
13 |
14 | def test_decompress(self):
15 | self.assertEqual(
16 | b'Some packable information',
17 | Packer.decompress(b64decode("AAAAGXjaC87PTVUoSEzOTkzKSVXIzEvLL8pNLMnMzwMAedUJrg==")))
18 |
19 |
20 | if __name__ == '__main__':
21 | unittest.main()
22 |
--------------------------------------------------------------------------------
/tests/test_PasswordGenerator.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | Test for CtSESAM class.
4 | """
5 | import unittest
6 | from password_generator import CtSesam
7 | from password_setting import PasswordSetting
8 | from hashlib import pbkdf2_hmac
9 | from binascii import unhexlify
10 |
11 |
12 | class TestPBKDF2(unittest.TestCase):
13 | def test_pbkdf2(self):
14 | expected_hash = unhexlify("2646f9ccb58d21406815bafc62245771bf80aaa080a633ff1bdd660eb44f369a89da48fb" +
15 | "041c5551a118de20cfb8b96b92e7a9945425ba889e9ad645614522eb")
16 | self.assertEqual(expected_hash, pbkdf2_hmac('sha512', "message".encode('utf-8'), "pepper".encode('utf-8'), 3))
17 |
18 | def test_pbkdf2_empty_salt(self):
19 | expected_hash = unhexlify("b8ec13cfc9b9d49ca1143018ce8413a962c09c0063f30a466df802897475c57f268d91cc" +
20 | "568ac1b6a9f19b1a0db10f30058fb7a453b2675010ef2b5f96487ad3")
21 | self.assertEqual(expected_hash, pbkdf2_hmac('sha512', "message".encode('utf-8'), b"", 3))
22 |
23 | def test_pbkdf2_empty_message(self):
24 | expected_hash = unhexlify("9dd331fc67421e1dce619cbbb517170e2dc325491d3426425630c4c01fd0eca8d8f535d6" +
25 | "b0555a2aa43efbc9141e3dd7edaef8b1278ac34eabfc2db735d992ee")
26 | self.assertEqual(expected_hash, pbkdf2_hmac('sha512', b"", "pepper".encode('utf-8'), 3))
27 |
28 | def test_pbkdf2_long_message(self):
29 | expected_hash = unhexlify("efc8e734ed5b5657ac220046754b7d1dbea00983f13209b1ec1d0e418e98807cba1026d3" +
30 | "ed3fa2a09dfa43c074447bf4777e70e4999d29d2c2f84dc51502a195")
31 | long_message = "ThisMessageIsLongerThanSixtyFourCharactersWhichLeadsToTheSituationThatTheMessageHasTo" + \
32 | "BeHashedWhenCalculatingTheHmac"
33 | self.assertEqual(expected_hash,
34 | pbkdf2_hmac('sha512', long_message.encode('utf-8'), "pepper".encode('utf-8'), 3))
35 |
36 |
37 | class TestCtSesam(unittest.TestCase):
38 | def test_default(self):
39 | setting = PasswordSetting('some.domain')
40 | setting.set_salt('pepper'.encode('utf-8'))
41 | setting.set_template("xaxnxxAoxx")
42 | manager = CtSesam(domain=setting.get_domain(), username=setting.get_username(), kgk='foo'.encode('utf-8'))
43 | self.assertEqual("]ew26XW.X<", manager.generate(setting))
44 |
45 | def test_custom_character_set(self):
46 | setting = PasswordSetting('some.domain')
47 | setting.set_salt('pepper'.encode('utf-8'))
48 | setting.set_extra_character_set(
49 | 'abcdefghijklmnopqrstuvwxyzABCDUFGHJKLMNPQRTEVWXYZ0123456789#!"§$%&/()[]{}=-_+*<>;:.')
50 | setting.set_template("oxxxxxxxxx")
51 | manager = CtSesam(domain=setting.get_domain(), username=setting.get_username(), kgk='foo'.encode('utf-8'))
52 | self.assertEqual("5#%KiEvUU7", manager.generate(setting))
53 |
54 | def test_custom_salt(self):
55 | setting = PasswordSetting('some.domain')
56 | setting.set_salt(b'qanisaoerna56745678eornsiarteonstiaroenstiaeroh')
57 | setting.set_template("oxAxxaxxnx")
58 | manager = CtSesam(domain=setting.get_domain(), username=setting.get_username(), kgk='foo'.encode('utf-8'))
59 | self.assertEqual(")hN8ol<;6<", manager.generate(setting))
60 |
61 | def test_long(self):
62 | setting = PasswordSetting('some.domain')
63 | setting.set_salt('pepper'.encode('utf-8'))
64 | setting.set_template("Aanoxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
65 | manager = CtSesam(domain=setting.get_domain(), username=setting.get_username(), kgk='foo'.encode('utf-8'))
66 | self.assertEqual("Ba0=}#K.X<$/eS0AuGjRm>(\"dnDnvZCx", manager.generate(setting))
67 |
68 | def test_simple_password_1(self):
69 | setting = PasswordSetting('ct.de')
70 | setting.set_extra_character_set("abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRTUVWXYZ0123456789" +
71 | "#!\"§$%&/()[]{}=-_+*<>;:.")
72 | setting.set_iterations(4096)
73 | setting.set_template("oxxxxxxxxx")
74 | setting.set_salt('pepper'.encode('utf-8'))
75 | kgk = 'test'.encode('utf-8')
76 | manager = CtSesam(domain=setting.get_domain(), username=setting.get_username(), kgk=kgk,
77 | salt=setting.get_salt(), iterations=setting.get_iterations())
78 | self.assertEqual(unhexlify("f4d54b303b21ee3d8bff9c1eae6f66d90db58c0a5cc770eee322cc59d4dec65793bf8f5dec" +
79 | "717fd1404bbfacf59befa68c4ad9168bfeaa6a9e28b326a76a82bb"), manager.hash_value)
80 | self.assertEqual("YBVUH=sN/3", manager.generate(setting))
81 |
82 | def test_simple_password_2(self):
83 | setting = PasswordSetting('MyFavoriteDomain')
84 | setting.set_extra_character_set("abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRTUVWXYZ")
85 | setting.set_iterations(8192)
86 | setting.set_template("oxxxxxxxxxxxxxxx")
87 | setting.set_salt('pepper'.encode('utf-8'))
88 | kgk = 'foobar'.encode('utf-8')
89 | manager = CtSesam(domain=setting.get_domain(), username=setting.get_username(), kgk=kgk,
90 | salt=setting.get_salt(), iterations=setting.get_iterations())
91 | self.assertEqual(unhexlify("cb0ae7b2b7fc969770a9bfc1eef3a9afd02d2b28d6d8e9cb324f41a31392a0f800ea7e2e43" +
92 | "e847537ceb863a16a869d5e4dd6822cf3be0206440eff97dc2001c"), manager.hash_value)
93 | self.assertEqual("wLUwoQvKzBaYXbme", manager.generate(setting))
94 |
95 | def test_simple_password_1_tpl(self):
96 | setting = PasswordSetting('FooBar')
97 | setting.set_extra_character_set("#!\"$%&/()[]{}=-_+*<>;:.")
98 | setting.set_iterations(4096)
99 | setting.set_template("xxoxAxxxxxxxxxaxx")
100 | setting.set_salt('blahfasel'.encode('utf-8'))
101 | kgk = 'test'.encode('utf-8')
102 | manager = CtSesam(domain=setting.get_domain(), username=setting.get_username(), kgk=kgk,
103 | salt=setting.get_salt(), iterations=setting.get_iterations())
104 | self.assertEqual(unhexlify("4e9e2503556bda7ad06cf45cab4490213becd3473845a868900fb61fa17d1c448496d11987c4" +
105 | "446d8007562029cce7f176eda4157604012a44e42add594a524e"), manager.hash_value)
106 | self.assertEqual("pU)VUfgJ-Ws*wgzzE", manager.generate(setting))
107 |
108 | def test_simple_password_2_tpl(self):
109 | setting = PasswordSetting('FooBar')
110 | setting.set_iterations(8192)
111 | setting.set_template("xxaxxx")
112 | setting.set_salt('blahfasel'.encode('utf-8'))
113 | kgk = 'test'.encode('utf-8')
114 | manager = CtSesam(domain=setting.get_domain(), username=setting.get_username(), kgk=kgk,
115 | salt=setting.get_salt(), iterations=setting.get_iterations())
116 | self.assertEqual(unhexlify("309d504d68dc921dcece9d10c14b406673715f15782032d64229b4b42336c8ec860cd9b945" +
117 | "104824ce43720b3a088828843df4029fdb8b2314f8b5129c815949"), manager.hash_value)
118 | self.assertEqual("baeloh", manager.generate(setting))
119 |
120 | def test_simple_password_3_tpl(self):
121 | setting = PasswordSetting('FooBar')
122 | setting.set_iterations(8192)
123 | setting.set_template("xxAxxx")
124 | setting.set_salt('blahfasel'.encode('utf-8'))
125 | kgk = 'test'.encode('utf-8')
126 | manager = CtSesam(domain=setting.get_domain(), username=setting.get_username(), kgk=kgk,
127 | salt=setting.get_salt(), iterations=setting.get_iterations())
128 | self.assertEqual(unhexlify("309d504d68dc921dcece9d10c14b406673715f15782032d64229b4b42336c8ec860cd9b9451048" +
129 | "24ce43720b3a088828843df4029fdb8b2314f8b5129c815949"), manager.hash_value)
130 | self.assertEqual("BAELOH", manager.generate(setting))
131 |
132 | def test_simple_password_4_tpl(self):
133 | setting = PasswordSetting('FooBar')
134 | setting.set_iterations(8192)
135 | setting.set_extra_character_set("0123456789abcdef")
136 | setting.set_template("xxxxxxxxxxxxxxxxxxxxxxxoxxxx")
137 | setting.set_salt('SALT'.encode('utf-8'))
138 | kgk = 'MY_T0P_5ecr57_PA55W0RD ;-)'.encode('utf-8')
139 | manager = CtSesam(domain=setting.get_domain(), username=setting.get_username(), kgk=kgk,
140 | salt=setting.get_salt(), iterations=setting.get_iterations())
141 | self.assertEqual(unhexlify("4993fd21600977c6f56b833eed223dda9b1bd34294afd1db4925553099cce402abda7000a22d2c" +
142 | "fda152afcf8a3a142e55ce57a9597434a39d05ccd93a853626"), manager.hash_value)
143 | self.assertEqual("626358a39dcc50d93a4347959a75", manager.generate(setting))
144 |
145 | def test_pin(self):
146 | setting = PasswordSetting('Bank')
147 | setting.set_iterations(1)
148 | setting.set_extra_character_set("0123456789")
149 | setting.set_template("oxxx")
150 | setting.set_salt('pepper'.encode('utf-8'))
151 | kgk = 'reallysafe'.encode('utf-8')
152 | manager = CtSesam(domain=setting.get_domain(), username=setting.get_username(), kgk=kgk,
153 | salt=setting.get_salt(), iterations=setting.get_iterations())
154 | self.assertEqual(unhexlify("55b5f5cdd9bf2845e339650b4f6e1398cf7fe9ceed087eb5f5bc059882723579fc8ec27443417" +
155 | "cf33c9763bafac6277fbe991bf27dd0206e78f7d9dfd574167f"), manager.hash_value)
156 | self.assertEqual("7809", manager.generate(setting))
157 |
--------------------------------------------------------------------------------
/tests/test_PasswordSetting.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | import unittest
5 | from password_setting import PasswordSetting
6 | import json
7 | from base64 import b64encode
8 |
9 |
10 | class TestPasswordSetting(unittest.TestCase):
11 | def test_username(self):
12 | s = PasswordSetting("unit.test")
13 | self.assertEqual("", s.get_username())
14 | s.set_username("Hugo")
15 | self.assertEqual("Hugo", s.get_username())
16 |
17 | def test_legacy_password(self):
18 | s = PasswordSetting("unit.test")
19 | self.assertEqual("", s.get_legacy_password())
20 | s.set_legacy_password("K6x/vyG9(p")
21 | self.assertEqual("K6x/vyG9(p", s.get_legacy_password())
22 |
23 | def test_character_set(self):
24 | s = PasswordSetting("unit.test")
25 | self.assertEqual("0123456789" +
26 | "abcdefghijklmnopqrstuvwxyz" +
27 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
28 | "#!\"§$%&/()[]{}=-_+*<>;:.", s.get_character_set())
29 | s.set_extra_character_set("&=Oo0wWsS$#uUvVzZ")
30 | s.set_template("oxxxxxxxxx")
31 | self.assertEqual("&=Oo0wWsS$#uUvVzZ", s.get_character_set())
32 | s.set_extra_character_set(
33 | "abcdefghijklmnopqrstuvwxyz" +
34 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
35 | "0123456789" +
36 | "#!\"§$%&/()[]{}=-_+*<>;:.")
37 | self.assertEqual("abcdefghijklmnopqrstuvwxyz" +
38 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
39 | "0123456789" +
40 | "#!\"§$%&/()[]{}=-_+*<>;:.", s.get_character_set())
41 | s.set_template("noxxxxxxxx")
42 | s.set_extra_character_set("#!\"§$%&/()[]{}=-_+*<>;:.")
43 | self.assertEqual("0123456789#!\"§$%&/()[]{}=-_+*<>;:.", s.get_character_set())
44 | s.set_template("xaxxxAxxx")
45 | self.assertEqual("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", s.get_character_set())
46 |
47 | def test_get_character_set(self):
48 | s = PasswordSetting("unit.test")
49 | self.assertEqual("c", s.get_character_set()[12])
50 | s.set_extra_character_set("axFLp0")
51 | s.set_template("xox")
52 | self.assertEqual(6, len(s.get_character_set()))
53 | self.assertEqual("F", s.get_character_set()[2])
54 | self.assertEqual("0", s.get_character_set()[5])
55 |
56 | def test_salt(self):
57 | s = PasswordSetting("unit.test")
58 | self.assertEqual(32, len(s.get_salt()))
59 | s.set_salt("somethingelse".encode('utf-8'))
60 | expected = "somethingelse".encode('utf-8')
61 | self.assertEqual(len(expected), len(s.get_salt()))
62 | for i in range(len(expected)):
63 | self.assertEqual(expected[i], s.get_salt()[i])
64 |
65 | def test_set_creation_date(self):
66 | s = PasswordSetting("unit.test")
67 | s.set_modification_date("1995-01-01T01:14:12")
68 | s.set_creation_date("2001-01-01T02:14:12")
69 | self.assertEqual("2001-01-01T02:14:12.000", s.get_creation_date())
70 | self.assertEqual("2001-01-01T02:14:12.000", s.get_modification_date())
71 |
72 | def test_set_modification_date(self):
73 | s = PasswordSetting("unit.test")
74 | s.set_creation_date("2007-01-01T02:14:12")
75 | s.set_modification_date("2005-01-01T01:14:12")
76 | self.assertEqual("2005-01-01T01:14:12.000", s.get_creation_date())
77 | self.assertEqual("2005-01-01T01:14:12.000", s.get_modification_date())
78 |
79 | def test_notes(self):
80 | s = PasswordSetting("unit.test")
81 | self.assertEqual("", s.get_notes())
82 | s.set_notes("Beware of the password!")
83 | self.assertEqual("Beware of the password!", s.get_notes())
84 |
85 | def test_to_json(self):
86 | s = PasswordSetting("unit.test")
87 | s.set_modification_date("2005-01-01T01:14:12")
88 | s.set_creation_date("2001-01-01T02:14:12")
89 | s.set_salt("something".encode('utf-8'))
90 | s.set_iterations(213)
91 | s.set_template("xxxxxxxxxxoxxx")
92 | s.set_extra_character_set("XVLCWKHGFQUIAEOSNRTDYÜÖÄPZBMJ")
93 | s.set_notes("Some note.")
94 | self.assertIn("domain", s.to_dict())
95 | self.assertEqual("unit.test", s.to_dict()["domain"])
96 | self.assertIn("cDate", s.to_dict())
97 | self.assertEqual("2001-01-01T02:14:12.000", s.to_dict()["cDate"])
98 | self.assertIn("mDate", s.to_dict())
99 | self.assertEqual("2005-01-01T01:14:12.000", s.to_dict()["mDate"])
100 | self.assertIn("salt", s.to_dict())
101 | self.assertEqual(str(b64encode("something".encode('utf-8')), encoding='utf-8'), s.to_dict()["salt"])
102 | self.assertIn("iterations", s.to_dict())
103 | self.assertEqual(213, s.to_dict()["iterations"])
104 | self.assertIn("passwordTemplate", s.to_dict())
105 | self.assertEqual("xxxxxxxxxxoxxx", s.to_dict()["passwordTemplate"])
106 | self.assertIn("extras", s.to_dict())
107 | self.assertEqual("XVLCWKHGFQUIAEOSNRTDYÜÖÄPZBMJ", s.to_dict()["extras"])
108 | self.assertIn("notes", s.to_dict())
109 | self.assertEqual("Some note.", s.to_dict()["notes"])
110 |
111 | def test_load_from_json(self):
112 | json_str = "{\"domain\": \"unit.test\", \"username\": \"testilinius\", " +\
113 | "\"notes\": \"interesting note\", \"legacyPassword\": \"rtSr?bS,mi\", " +\
114 | "\"extras\": \"AEIOUaeiou\", \"iterations\": 5341, " +\
115 | "\"passwordTemplate\": \"7;xxxxoxxxxxxxxxxx\", \"salt\": \"ZmFzY2luYXRpbmc=\", " +\
116 | "\"cDate\": \"2001-01-01T02:14:12.000\", \"mDate\": \"2005-01-01T01:14:12.000\"}"
117 | s = PasswordSetting(json.loads(json_str)["domain"])
118 | s.load_from_dict(json.loads(json_str))
119 | self.assertEqual("unit.test", s.get_domain())
120 | self.assertEqual("testilinius", s.get_username())
121 | self.assertEqual("interesting note", s.get_notes())
122 | self.assertEqual("rtSr?bS,mi", s.get_legacy_password())
123 | self.assertEqual("AEIOUaeiou", s.get_character_set())
124 | self.assertEqual(5341, s.get_iterations())
125 | self.assertEqual("xxxxoxxxxxxxxxxx", s.get_template())
126 | expected_salt = "fascinating".encode('utf-8')
127 | self.assertEqual(len(expected_salt), len(s.get_salt()))
128 | for i in range(len(expected_salt)):
129 | self.assertEqual(expected_salt[i], s.get_salt()[i])
130 | self.assertEqual("2001-01-01T02:14:12.000", s.get_creation_date())
131 | self.assertEqual("2005-01-01T01:14:12.000", s.get_modification_date())
132 |
133 | def test_get_template(self):
134 | s = PasswordSetting("unit.test")
135 | s.set_template("xxxaxxxxxxx")
136 | self.assertEqual("xxxaxxxxxxx", s.get_template())
137 | s.set_template("6;xxxxxxoxxxnAxxxa")
138 | self.assertEqual("xxxxxxoxxxnAxxxa", s.get_template())
139 | self.assertEqual(16, len(s.get_template()))
140 |
141 |
142 | if __name__ == '__main__':
143 | unittest.main()
144 |
--------------------------------------------------------------------------------
/tests/test_PasswordSettingsManager.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | import unittest
5 | import os
6 | import json
7 | import struct
8 | from kgk_manager import KgkManager
9 | from preference_manager import PreferenceManager
10 | from password_settings_manager import PasswordSettingsManager
11 | from password_setting import PasswordSetting
12 | from crypter import Crypter
13 | from packer import Packer
14 | from base64 import b64encode, b64decode
15 |
16 |
17 | class MockSyncManager(object):
18 | """
19 | We do not really want to sync.
20 | """
21 | def __init__(self, kgk):
22 | self.kgk_manager = KgkManager()
23 | self.kgk_manager.set_preference_manager(PreferenceManager(os.path.expanduser('~/.ctSESAM_test_extra.pws')))
24 | self.kgk_manager.kgk = kgk
25 |
26 | def pull(self):
27 | """
28 | Returns some mock data tor the sync test.
29 |
30 | :return: base64 mock data blob
31 | :rtype: (bool, str)
32 | """
33 | remote_data = {
34 | 'unit.test': {
35 | 'domain': 'unit.test',
36 | 'length': 12,
37 | 'iterations': 5001,
38 | 'notes': 'another note!',
39 | 'salt': 'cGVwcGVy',
40 | 'usedCharacters': 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRTUVWXYZ0123456789',
41 | 'cDate': '2011-02-12T11:07:31',
42 | 'mDate': '2013-07-12T14:46:11'
43 | },
44 | 'some.domain': {
45 | 'domain': 'some.domain',
46 | 'length': 4,
47 | 'iterations': 4097,
48 | 'salt': 'cGVwcGVy',
49 | 'usedCharacters': '6478593021',
50 | 'cDate': '2013-06-17T04:03:41',
51 | 'mDate': '2014-08-02T10:37:11'
52 | },
53 | 'third.domain': {
54 | 'domain': 'third.domain',
55 | 'length': 10,
56 | 'iterations': 4098,
57 | 'salt': 'cGVwcGVy',
58 | 'usedCharacters': 'aeiou',
59 | 'cDate': '2013-06-17T04:03:41',
60 | 'mDate': '2014-08-02T10:37:11'
61 | }
62 | }
63 | salt = os.urandom(32)
64 | kgk_block = self.kgk_manager.create_and_save_new_kgk_block(self.kgk_manager.get_kgk_crypter(b'xyz', salt))
65 | settings_crypter = PasswordSettingsManager.get_settings_crypter(self.kgk_manager)
66 | return True, str(b64encode(b'\x01' + salt + kgk_block + settings_crypter.encrypt(
67 | Packer.compress(json.dumps(remote_data).encode('utf-8')))), encoding='utf-8')
68 |
69 | def get_binary_sync_settings(self):
70 | """
71 | :return:
72 | :rtype: bytes
73 | """
74 | return b''
75 |
76 | def has_settings(self):
77 | """
78 | :return:
79 | :rtype: bool
80 | """
81 | return True
82 |
83 |
84 | class TestPasswordSettingsManager(unittest.TestCase):
85 | def setUp(self):
86 | self.preference_manager = PreferenceManager(os.path.expanduser('~/.ctSESAM_test.pws'))
87 | self.manager = PasswordSettingsManager(self.preference_manager)
88 |
89 | # noinspection PyUnresolvedReferences
90 | def tearDown(self):
91 | file = os.path.expanduser('~/.ctSESAM_test.pws')
92 | if os.path.isfile(file):
93 | try:
94 | import win32con
95 | import win32api
96 | win32api.SetFileAttributes(file, win32con.FILE_ATTRIBUTE_NORMAL)
97 | except ImportError:
98 | pass
99 | os.remove(file)
100 |
101 | def test_get_setting(self):
102 | setting = self.manager.get_setting('abc.de')
103 | self.assertEqual(PasswordSetting, type(setting))
104 | self.assertEqual('abc.de', setting.get_domain())
105 | self.assertIn('abc.de', self.manager.get_domain_list())
106 |
107 | def test_store_local_settings(self):
108 | abc_setting = self.manager.get_setting('abc.de')
109 | abc_setting.set_template('xAxonaxxxx')
110 | self.manager.set_setting(abc_setting)
111 | new_setting = PasswordSetting('hugo.com')
112 | new_setting.set_template('xonxAxxaxxxx')
113 | self.manager.set_setting(new_setting)
114 | kgk_manager = KgkManager()
115 | kgk_manager.set_preference_manager(self.preference_manager)
116 | kgk_manager.create_new_kgk()
117 | salt = os.urandom(32)
118 | kgk_manager.create_and_save_new_kgk_block(Crypter(Crypter.createIvKey(b'xyz', salt, iterations=3)))
119 | self.manager.store_local_settings(kgk_manager)
120 | with open(os.path.expanduser('~/.ctSESAM_test.pws'), 'br') as f:
121 | data = f.read()
122 | settings_crypter = PasswordSettingsManager.get_settings_crypter(kgk_manager)
123 | decrypted_settings = settings_crypter.decrypt(data[144:])
124 | sync_settings_len = struct.unpack('!I', decrypted_settings[:4])[0]
125 | data = json.loads(Packer.decompress(decrypted_settings[4+sync_settings_len:]).decode('utf8'))
126 | self.assertEqual('abc.de', data['settings']['abc.de']['domain'])
127 | self.assertEqual('xAxonaxxxx', data['settings']['abc.de']['passwordTemplate'])
128 | self.assertEqual('hugo.com', data['settings']['hugo.com']['domain'])
129 | self.assertEqual('xonxAxxaxxxx', data['settings']['hugo.com']['passwordTemplate'])
130 |
131 | def test_load_settings_from_file(self):
132 | settings = {
133 | 'settings': {
134 | 'unit.test': {
135 | 'domain': 'unit.test',
136 | 'passwordTemplate': 'xxxxxxxxxxo',
137 | 'extras': '#OWspx6;3gov0/1',
138 | 'iterations': 5000,
139 | 'notes': 'Nice note!',
140 | 'cDate': '2011-02-12T11:07:31',
141 | 'mDate': '2011-02-12T11:07:32'
142 | },
143 | 'some.domain': {
144 | 'domain': 'some.domain',
145 | 'passwordTemplate': 'oxxx',
146 | 'extras': '6478593021',
147 | 'cDate': '2013-06-17T04:03:41',
148 | 'mDate': '2014-08-02T10:37:12'
149 | }
150 | },
151 | 'synced': []
152 | }
153 | salt = os.urandom(32)
154 | data = json.dumps(settings).encode('utf-8')
155 | kgk_manager = KgkManager()
156 | kgk_manager.set_preference_manager(self.preference_manager)
157 | kgk_manager.create_new_kgk()
158 | kgk_block = kgk_manager.create_and_save_new_kgk_block(Crypter(Crypter.createIvKey(b'xyz', salt, iterations=3)))
159 | crypter = PasswordSettingsManager.get_settings_crypter(kgk_manager)
160 | f = open(os.path.expanduser('~/.ctSESAM_test.pws'), 'bw')
161 | f.write(salt + kgk_block + crypter.encrypt(struct.pack('!I', 0) + Packer.compress(data)))
162 | f.close()
163 | self.preference_manager.read_file()
164 | self.manager.load_local_settings(kgk_manager)
165 | self.assertIn('unit.test', self.manager.get_domain_list())
166 | self.assertIn('some.domain', self.manager.get_domain_list())
167 | self.assertEqual('xxxxxxxxxxo', self.manager.get_setting('unit.test').get_template())
168 | self.assertEqual(5000, self.manager.get_setting('unit.test').get_iterations())
169 | self.assertEqual('Nice note!', self.manager.get_setting('unit.test').get_notes())
170 | self.assertEqual('oxxx', self.manager.get_setting('some.domain').get_template())
171 | self.assertEqual('6478593021', self.manager.get_setting('some.domain').get_character_set())
172 |
173 | def test_set_setting(self):
174 | setting = self.manager.get_setting('hugo.me')
175 | setting.set_template('xonxAa')
176 | self.manager.set_setting(setting)
177 | self.assertIn('hugo.me', self.manager.get_domain_list())
178 | self.assertEqual(6, self.manager.get_setting('hugo.me').get_length())
179 |
180 | def test_delete_setting(self):
181 | setting = self.manager.get_setting('hugo.me')
182 | setting.set_template('xonxAa')
183 | self.manager.set_setting(setting)
184 | self.assertIn('hugo.me', self.manager.get_domain_list())
185 | self.manager.delete_setting(setting)
186 | self.assertNotIn('hugo.me', self.manager.get_domain_list())
187 |
188 | def test_get_domain_list(self):
189 | settings = {
190 | 'settings': {
191 | 'unit.test': {
192 | 'domain': 'unit.test',
193 | 'extras': '#!"§$%&/()[]{}=-_+*<>;:.',
194 | 'passwordTemplate': 'xxxaoxxAxxn',
195 | 'iterations': 5000,
196 | 'notes': 'Nice note!',
197 | 'salt': 'cGVwcGVy',
198 | 'cDate': '2011-02-12T11:07:31.000',
199 | 'mDate': '2011-02-12T11:07:32.000'
200 | },
201 | 'some.domain': {
202 | 'domain': 'some.domain',
203 | 'extras': '#!"§$%&/()[]{}=-_+*<>;:.',
204 | 'passwordTemplate': 'xxxo',
205 | 'iterations': 4096,
206 | 'salt': 'cGVwcGVy',
207 | 'cDate': '2013-06-17T04:03:41.000',
208 | 'mDate': '2014-08-02T10:37:12.000'
209 | }
210 | },
211 | 'synced': []
212 | }
213 | salt = os.urandom(32)
214 | f = open(os.path.expanduser('~/.ctSESAM_test.pws'), 'bw')
215 | data = json.dumps(settings).encode('utf-8')
216 | kgk_manager = KgkManager()
217 | kgk_manager.set_preference_manager(self.preference_manager)
218 | kgk_manager.create_new_kgk()
219 | kgk_block = kgk_manager.create_and_save_new_kgk_block(Crypter(Crypter.createIvKey(b'xyz', salt, iterations=3)))
220 | crypter = PasswordSettingsManager.get_settings_crypter(kgk_manager)
221 | f.write(salt + kgk_block + crypter.encrypt(struct.pack('!I', 0) + Packer.compress(data)))
222 | f.close()
223 | self.preference_manager.read_file()
224 | self.manager.load_local_settings(kgk_manager)
225 | self.assertIn('settings', self.manager.get_settings_as_dict())
226 | self.assertIn('unit.test', self.manager.get_settings_as_dict()['settings'])
227 | self.assertEqual(settings['settings']['unit.test'],
228 | self.manager.get_settings_as_dict()['settings']['unit.test'])
229 | self.assertIn('some.domain', self.manager.get_settings_as_dict()['settings'])
230 | self.assertEqual(settings['settings']['some.domain'],
231 | self.manager.get_settings_as_dict()['settings']['some.domain'])
232 | self.assertEqual(settings, self.manager.get_settings_as_dict())
233 |
234 | def test_get_export_data(self):
235 | settings = {
236 | 'settings': {
237 | 'unit.test': {
238 | 'domain': 'unit.test',
239 | 'extras': '#!"§$%&/()[]{}=-_+*<>;:.',
240 | 'passwordTemplate': 'xnxoaAxxxx',
241 | 'iterations': 5000,
242 | 'notes': 'Nice note!',
243 | 'salt': 'cGVwcGVy',
244 | 'cDate': '2011-02-12T11:07:31.000',
245 | 'mDate': '2011-02-12T11:07:32.000'
246 | },
247 | 'some.domain': {
248 | 'domain': 'some.domain',
249 | 'extras': '6478593021',
250 | 'passwordTemplate': 'xnxoaA',
251 | 'iterations': 4096,
252 | 'salt': 'cGVwcGVy',
253 | 'cDate': '2013-06-17T04:03:41.000',
254 | 'mDate': '2014-08-02T10:37:12.000'
255 | }
256 | },
257 | 'synced': []
258 | }
259 | salt = os.urandom(32)
260 | kgk_manager = KgkManager()
261 | kgk_manager.set_preference_manager(self.preference_manager)
262 | kgk_manager.create_new_kgk()
263 | kgk_block = kgk_manager.create_and_save_new_kgk_block(Crypter(Crypter.createIvKey(b'xyz', salt, iterations=3)))
264 | crypter = PasswordSettingsManager.get_settings_crypter(kgk_manager)
265 | f = open(os.path.expanduser('~/.ctSESAM_test.pws'), 'bw')
266 | f.write(salt + kgk_block +
267 | crypter.encrypt(struct.pack('!I', 0) + Packer.compress(json.dumps(settings).encode('utf-8'))))
268 | f.close()
269 | self.preference_manager.read_file()
270 | self.manager.load_local_settings(kgk_manager)
271 | data = b64decode(self.manager.get_export_data(kgk_manager))
272 | self.assertEqual(b'\x01', data[:1])
273 | salt = data[1:33]
274 | kgk_crypter = Crypter(Crypter.createIvKey(b'xyz', salt, iterations=3))
275 | kgk_manager2 = KgkManager()
276 | kgk_manager2.set_preference_manager(self.preference_manager)
277 | kgk_manager2.decrypt_kgk(data[33:145], kgk_crypter)
278 | settings_crypter = PasswordSettingsManager.get_settings_crypter(kgk_manager2)
279 | self.assertEqual(
280 | settings['settings'],
281 | json.loads(str(Packer.decompress(settings_crypter.decrypt(data[145:])), encoding='utf-8')))
282 |
283 | def test_update_from_sync(self):
284 | settings = {
285 | 'settings': {
286 | 'unit.test': {
287 | 'domain': 'unit.test',
288 | 'passwordTemplate': 'xxaAnoxxxxx',
289 | 'iterations': 5000,
290 | 'notes': 'Nice note!',
291 | 'salt': 'cGVwcGVy',
292 | 'usedCharacters': 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRTUVWXYZ0123456789' +
293 | '#!"§$%&/()[]{}=-_+*<>;:.',
294 | 'cDate': '2011-02-12T11:07:31',
295 | 'mDate': '2011-02-12T11:07:32'
296 | },
297 | 'some.domain': {
298 | 'domain': 'some.domain',
299 | 'passwordTemplate': 'oanA',
300 | 'iterations': 4096,
301 | 'salt': 'cGVwcGVy',
302 | 'usedCharacters': '6478593021',
303 | 'cDate': '2013-06-17T04:03:41',
304 | 'mDate': '2014-08-02T10:37:12'
305 | },
306 | 'some.other.domain': {
307 | 'domain': 'some.other.domain',
308 | 'passwordTemplate': 'oanA',
309 | 'iterations': 4097,
310 | 'salt': 'cGVwcGVy',
311 | 'usedCharacters': '6478593021',
312 | 'cDate': '2013-06-17T04:03:41'
313 | }
314 | },
315 | 'synced': []
316 | }
317 | salt = os.urandom(32)
318 | kgk_manager = KgkManager()
319 | kgk_manager.set_preference_manager(self.preference_manager)
320 | kgk_manager.create_new_kgk()
321 | kgk_block = kgk_manager.create_and_save_new_kgk_block(
322 | Crypter(Crypter.createIvKey('xyz'.encode('utf-8'), salt)))
323 | crypter = PasswordSettingsManager.get_settings_crypter(kgk_manager)
324 | f = open(os.path.expanduser('~/.ctSESAM_test.pws'), 'bw')
325 | f.write(salt + kgk_block +
326 | crypter.encrypt(struct.pack('!I', 0) + Packer.compress(json.dumps(settings).encode('utf-8'))))
327 | f.close()
328 | self.preference_manager.read_file()
329 | self.manager.sync_manager = MockSyncManager(kgk_manager.get_kgk())
330 | self.manager.load_settings(kgk_manager, 'xyz')
331 | self.assertIn('unit.test', self.manager.get_domain_list())
332 | self.assertIn('some.domain', self.manager.get_domain_list())
333 | self.assertIn('some.other.domain', self.manager.get_domain_list())
334 | self.assertIn('third.domain', self.manager.get_domain_list())
335 | self.assertEqual(5001, self.manager.get_setting('unit.test').get_iterations())
336 | self.assertEqual(4096, self.manager.get_setting('some.domain').get_iterations())
337 | self.assertEqual(4097, self.manager.get_setting('some.other.domain').get_iterations())
338 | self.assertEqual(4098, self.manager.get_setting('third.domain').get_iterations())
339 | file = os.path.expanduser('~/.ctSESAM_test_extra.pws')
340 | if os.path.isfile(file):
341 | try:
342 | import win32con
343 | import win32api
344 | win32api.SetFileAttributes(file, win32con.FILE_ATTRIBUTE_NORMAL)
345 | except ImportError:
346 | pass
347 | os.remove(file)
348 |
--------------------------------------------------------------------------------
/tests/test_Sync.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | import unittest
5 | from unittest.mock import patch
6 | from sync import Sync
7 | from base64 import b64encode
8 | import json
9 |
10 |
11 | class MockResponse(object):
12 | """
13 | A response with a similar format as requests.post produces.
14 | """
15 | def __init__(self, blob=''):
16 | self.status_code = 200
17 | if len(blob) > 0:
18 | self.text = json.dumps({
19 | "status": "ok",
20 | "result": blob
21 | })
22 | else:
23 | self.text = json.dumps({
24 | "status": "ok"
25 | })
26 |
27 |
28 | def mock_requests_post_empty(url, data, headers, verify):
29 | """
30 | Returns a response with a similar format as requests.post produces.
31 |
32 | :param url:
33 | :param data:
34 | :param headers:
35 | :param verify:
36 | :return:
37 | :rtype: MockResponse
38 | """
39 | return MockResponse()
40 |
41 |
42 | def mock_requests_post(url, data, headers, verify):
43 | """
44 | Returns a response with a similar format as requests.post produces.
45 |
46 | :param url:
47 | :param data:
48 | :param headers:
49 | :param verify:
50 | :return:
51 | :rtype: MockResponse
52 | """
53 | return MockResponse(str(b64encode(b'Test'), encoding='utf-8'))
54 |
55 |
56 | class TestSync(unittest.TestCase):
57 | @patch('requests.post', mock_requests_post_empty)
58 | def test_pull_empty_request(self):
59 | sync = Sync("https://ersatzworld.net/ctpwdgen-server/", 'inter', 'op', 'file.pem')
60 | status, blob = sync.pull()
61 | self.assertTrue(status)
62 | self.assertEqual('', blob)
63 |
64 | @patch('requests.post', mock_requests_post)
65 | def test_pull(self):
66 | sync = Sync("https://ersatzworld.net/ctpwdgen-server/", 'inter', 'op', 'file.pem')
67 | status, blob = sync.pull()
68 | self.assertTrue(status)
69 | self.assertEqual(str(b64encode(b'Test'), encoding='utf-8'), blob)
70 |
71 | @patch('requests.post', mock_requests_post)
72 | def test_push(self):
73 | sync = Sync("https://ersatzworld.net/ctpwdgen-server/", 'inter', 'op', 'file.pem')
74 | self.assertTrue(sync.push(str(b64encode(b'Test'), encoding='utf-8')))
75 |
76 |
77 | if __name__ == '__main__':
78 | unittest.main()
79 |
--------------------------------------------------------------------------------
/tests/test_domainExtractor.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | import unittest
5 | from domain_extractor import extract_top_domain, extract_full_domain
6 |
7 |
8 | class TestDomainExtractor(unittest.TestCase):
9 | def test_extract_top_domain(self):
10 | self.assertEqual(
11 | "test.com",
12 | extract_top_domain("http://www.test.com/some/path/index.html"))
13 | self.assertEqual(
14 | "test.com",
15 | extract_top_domain("http://test.com/some/path/index.html"))
16 | self.assertEqual(
17 | "test.com",
18 | extract_top_domain("http://complicated.subdomain.structure.test.com/some/path/index.html"))
19 | self.assertEqual(
20 | "test.com",
21 | extract_top_domain("https://www.test.com/some/path/index.html"))
22 | self.assertEqual(
23 | "test.com",
24 | extract_top_domain("https://test.com/some/path/index.html"))
25 | self.assertEqual(
26 | "test.com",
27 | extract_top_domain("https://complicated.subdomain.structure.test.com/some/path/index.html"))
28 | self.assertEqual(
29 | "test.com",
30 | extract_top_domain("test.com"))
31 | self.assertEqual(
32 | "test.com",
33 | extract_top_domain("www.test.com"))
34 | self.assertEqual(
35 | "test.com",
36 | extract_top_domain("complicated.subdomain.structure.test.com"))
37 | self.assertEqual(
38 | "test.com",
39 | extract_top_domain("test.com/path/to/things"))
40 | self.assertEqual(
41 | "amazon.co.jp",
42 | extract_top_domain("www.amazon.co.jp/search=?some(characters)[strange]"))
43 | self.assertEqual(
44 | "english.co.uk",
45 | extract_top_domain("english.co.uk"))
46 | self.assertEqual(
47 | "noUrl",
48 | extract_top_domain("noUrl"))
49 |
50 | def test_extract_full_domain(self):
51 | self.assertEqual(
52 | "www.test.com",
53 | extract_full_domain("http://www.test.com/some/path/index.html"))
54 | self.assertEqual(
55 | "test.com",
56 | extract_full_domain("http://test.com/some/path/index.html"))
57 | self.assertEqual(
58 | "complicated.subdomain.structure.test.com",
59 | extract_full_domain("http://complicated.subdomain.structure.test.com/some/path/index.html"))
60 | self.assertEqual(
61 | "www.test.com",
62 | extract_full_domain("https://www.test.com/some/path/index.html"))
63 | self.assertEqual(
64 | "test.com",
65 | extract_full_domain("https://test.com/some/path/index.html"))
66 | self.assertEqual(
67 | "complicated.subdomain.structure.test.com",
68 | extract_full_domain("https://complicated.subdomain.structure.test.com/some/path/index.html"))
69 | self.assertEqual(
70 | "test.com",
71 | extract_full_domain("test.com"))
72 | self.assertEqual(
73 | "www.test.com",
74 | extract_full_domain("www.test.com"))
75 | self.assertEqual(
76 | "complicated.subdomain.structure.test.com",
77 | extract_full_domain("complicated.subdomain.structure.test.com"))
78 | self.assertEqual(
79 | "test.com",
80 | extract_full_domain("test.com/path/to/things"))
81 | self.assertEqual(
82 | "www.amazon.co.jp",
83 | extract_full_domain("www.amazon.co.jp/search=?some(characters)[strange]"))
84 | self.assertEqual(
85 | "english.co.uk",
86 | extract_full_domain("english.co.uk"))
87 | self.assertEqual(
88 | "noUrl",
89 | extract_full_domain("noUrl"))
90 |
91 |
92 | if __name__ == '__main__':
93 | unittest.main()
94 |
--------------------------------------------------------------------------------