├── .gitignore
├── LICENSE
├── README.md
├── TemporaryExposureKeyExportV1_1_pb2.py
├── TemporaryExposureKeyExportV1_5_pb2.py
├── count_keys.py
├── create_demo_key_set.py
├── derive_aem_key.py
├── derive_rpi_key.py
├── doc
└── algorithm.md
├── lib
├── __init__.py
├── contact_records_pb2.py
├── conversions.py
├── count_users.py
├── count_users_v1_5.py
├── crypto.py
├── diagnosis_key.py
├── diagnosis_keys.py
├── diagnosis_keys_write.py
├── ramble_rpis.py
├── rpis_in_db.py
└── scanned_rpis.py
├── parse_keys.py
├── parse_keys_json.py
└── requirements.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | venv/*
3 | __pycache__
4 | TemporaryExposureKeyExport*.proto
5 | testExport*.zip
6 | *.zip
7 | *.csv
8 | app_contact-tracing-*
9 | *.tar.gz
10 | *.ods*
11 | *.bin
12 | *.sig
13 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # diagnosis-keys
2 | Tools for working with Diagnosis Keys from the COVID-19 Exposure Notification / Corona-Warn-App system
3 |
4 | Copyright (C) 2020 Michael Huebler and other contributors
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU Affero General Public License as published
8 | by the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU Affero General Public License for more details.
15 |
16 | You should have received a copy of the GNU Affero General Public License
17 | along with this program. If not, see .
18 |
19 | ## Installation
20 | % git clone https://github.com/mh-/diagnosis-keys
21 | % cd diagnosis-keys
22 | % pip3 install -r requirements.txt
23 |
24 | ## Use
25 | ```
26 | % ./parse_keys.py -d testExport-2-records-1-of-1.zip
27 | Exposure Notification Diagnosis Key Parser
28 | This script parses published Diagnosis Keys.
29 |
30 | File 'testExport-2-records-1-of-1.zip' read.
31 | - Time window: 2020-05-22 15:00:00 UTC - 2020-05-23 15:00:00 UTC
32 | - Region: US
33 | - Batch: 1 of 1
34 | - Signature Info:
35 | verification_key_version: "1"
36 | verification_key_id: "some_id"
37 | signature_algorithm: "1.2.840.10045.4.3.2"
38 |
39 | Diagnosis Keys:
40 | 1: TEK: 172fc480e598490c34177604339b1543, Transmission Risk Level: 8, Validity: 2020-05-20 15:20:00 UTC - 2020-05-20 15:30:00 UTC (2649980, 1)
41 | 2: TEK: 2b63053ac483238de176169e861f3dcd, Transmission Risk Level: 1, Validity: 2020-05-19 20:20:00 UTC - 2020-05-20 15:20:00 UTC (2649866, 114)
42 | ```
43 |
44 | You can download an example Diagnosis Keys file here:
45 | https://github.com/google/exposure-notifications-server/blob/master/examples/export/testExport-2-records-1-of-1.zip
46 | (This file was generated from https://github.com/google/exposure-notifications-server/blob/master/examples/export/keys.json,
47 | using Google's [export-generate](https://github.com/google/exposure-notifications-server/tree/master/examples/export) tool.)
48 |
49 | Another example run:
50 | ```
51 | % ./parse_keys.py -c app_contact-tracing-contact-record-db/ -d tekExport.zip -l -s
52 | Exposure Notification Diagnosis Key Parser
53 | This script parses published Diagnosis Keys.
54 |
55 | File 'tekExport.zip' read.
56 | - Time window: 2020-06-12 13:25:31 CEST - 2020-06-13 13:25:31 CEST
57 | - Region: US
58 | - Batch: 1 of 1
59 | - Signature Info:
60 | verification_key_version: "1"
61 | verification_key_id: "some_id"
62 | signature_algorithm: "1.2.840.10045.4.3.2"
63 |
64 | Diagnosis Keys:
65 | 1: TEK: b534b9654ba21dcd60a9b3e17d620443, Transmission Risk Level: 5, Validity: 2020-06-13 02:00:00 CEST - 2020-06-14 02:00:00 CEST (2653344, 144)
66 | FOUND MATCH!
67 | RPI Validity: 2020-06-13 12:40:00 CEST - 2020-06-13 12:50:00 CEST (Interval number: 2653408, RPI: 1b013a80678747f73b140e8e3e46a3aa)
68 | 2020-06-13 12:44:12 CEST Attenuation: 43dB (RSSI: -57dBm, AEM: 919c3296, Metadata: 40f20000)
69 | (...)
70 | FOUND MATCH!
71 | RPI Validity: 2020-06-13 12:50:00 CEST - 2020-06-13 13:00:00 CEST (Interval number: 2653409, RPI: 99b8e671e0759ca9532a25ea3f992a8b)
72 | 2020-06-13 12:54:41 CEST Attenuation: 34dB (RSSI: -58dBm, AEM: 36563b98, Metadata: 40e80000)
73 | (...)
74 | FOUND MATCH!
75 | RPI Validity: 2020-06-13 13:00:00 CEST - 2020-06-13 13:10:00 CEST (Interval number: 2653410, RPI: f357370f15be3f7ec06030ca34899223)
76 | 2020-06-13 13:07:20 CEST Attenuation: 34dB (RSSI: -58dBm, AEM: 9be98c37, Metadata: 40e80000)
77 | (...)
78 | ```
79 |
80 | ## Used by
81 | This tool is used by a number of CWA diagnosis key visualisation projects such as:
82 |
83 | - https://ctt.pfstr.de/
84 | - https://micb25.github.io/dka/
85 | - https://covid-19.sledilnik.org/en/ostanizdrav
86 |
87 |
--------------------------------------------------------------------------------
/TemporaryExposureKeyExportV1_1_pb2.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # Generated by the protocol buffer compiler. DO NOT EDIT!
3 | # source: TemporaryExposureKeyExportV1_1.proto
4 |
5 | from google.protobuf import descriptor as _descriptor
6 | from google.protobuf import message as _message
7 | from google.protobuf import reflection as _reflection
8 | from google.protobuf import symbol_database as _symbol_database
9 | # @@protoc_insertion_point(imports)
10 |
11 | _sym_db = _symbol_database.Default()
12 |
13 |
14 |
15 |
16 | DESCRIPTOR = _descriptor.FileDescriptor(
17 | name='TemporaryExposureKeyExportV1_1.proto',
18 | package='',
19 | syntax='proto2',
20 | serialized_options=None,
21 | create_key=_descriptor._internal_create_key,
22 | serialized_pb=b'\n TemporaryExposureKeyExportV1_1.proto\"\xd1\x01\n\x1aTemporaryExposureKeyExport\x12\x17\n\x0fstart_timestamp\x18\x01 \x01(\x06\x12\x15\n\rend_timestamp\x18\x02 \x01(\x06\x12\x0e\n\x06region\x18\x03 \x01(\t\x12\x11\n\tbatch_num\x18\x04 \x01(\x05\x12\x12\n\nbatch_size\x18\x05 \x01(\x05\x12\'\n\x0fsignature_infos\x18\x06 \x03(\x0b\x32\x0e.SignatureInfo\x12#\n\x04keys\x18\x07 \x03(\x0b\x32\x15.TemporaryExposureKey\"\x9b\x01\n\rSignatureInfo\x12\x15\n\rapp_bundle_id\x18\x01 \x01(\t\x12\x17\n\x0f\x61ndroid_package\x18\x02 \x01(\t\x12 \n\x18verification_key_version\x18\x03 \x01(\t\x12\x1b\n\x13verification_key_id\x18\x04 \x01(\t\x12\x1b\n\x13signature_algorithm\x18\x05 \x01(\t\"\x8d\x01\n\x14TemporaryExposureKey\x12\x10\n\x08key_data\x18\x01 \x01(\x0c\x12\x1f\n\x17transmission_risk_level\x18\x02 \x01(\x05\x12%\n\x1drolling_start_interval_number\x18\x03 \x01(\x05\x12\x1b\n\x0erolling_period\x18\x04 \x01(\x05:\x03\x31\x34\x34'
23 | )
24 |
25 |
26 |
27 |
28 | _TEMPORARYEXPOSUREKEYEXPORT = _descriptor.Descriptor(
29 | name='TemporaryExposureKeyExport',
30 | full_name='TemporaryExposureKeyExport',
31 | filename=None,
32 | file=DESCRIPTOR,
33 | containing_type=None,
34 | create_key=_descriptor._internal_create_key,
35 | fields=[
36 | _descriptor.FieldDescriptor(
37 | name='start_timestamp', full_name='TemporaryExposureKeyExport.start_timestamp', index=0,
38 | number=1, type=6, cpp_type=4, label=1,
39 | has_default_value=False, default_value=0,
40 | message_type=None, enum_type=None, containing_type=None,
41 | is_extension=False, extension_scope=None,
42 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
43 | _descriptor.FieldDescriptor(
44 | name='end_timestamp', full_name='TemporaryExposureKeyExport.end_timestamp', index=1,
45 | number=2, type=6, cpp_type=4, label=1,
46 | has_default_value=False, default_value=0,
47 | message_type=None, enum_type=None, containing_type=None,
48 | is_extension=False, extension_scope=None,
49 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
50 | _descriptor.FieldDescriptor(
51 | name='region', full_name='TemporaryExposureKeyExport.region', index=2,
52 | number=3, type=9, cpp_type=9, label=1,
53 | has_default_value=False, default_value=b"".decode('utf-8'),
54 | message_type=None, enum_type=None, containing_type=None,
55 | is_extension=False, extension_scope=None,
56 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
57 | _descriptor.FieldDescriptor(
58 | name='batch_num', full_name='TemporaryExposureKeyExport.batch_num', index=3,
59 | number=4, type=5, cpp_type=1, label=1,
60 | has_default_value=False, default_value=0,
61 | message_type=None, enum_type=None, containing_type=None,
62 | is_extension=False, extension_scope=None,
63 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
64 | _descriptor.FieldDescriptor(
65 | name='batch_size', full_name='TemporaryExposureKeyExport.batch_size', index=4,
66 | number=5, type=5, cpp_type=1, label=1,
67 | has_default_value=False, default_value=0,
68 | message_type=None, enum_type=None, containing_type=None,
69 | is_extension=False, extension_scope=None,
70 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
71 | _descriptor.FieldDescriptor(
72 | name='signature_infos', full_name='TemporaryExposureKeyExport.signature_infos', index=5,
73 | number=6, type=11, cpp_type=10, label=3,
74 | has_default_value=False, default_value=[],
75 | message_type=None, enum_type=None, containing_type=None,
76 | is_extension=False, extension_scope=None,
77 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
78 | _descriptor.FieldDescriptor(
79 | name='keys', full_name='TemporaryExposureKeyExport.keys', index=6,
80 | number=7, type=11, cpp_type=10, label=3,
81 | has_default_value=False, default_value=[],
82 | message_type=None, enum_type=None, containing_type=None,
83 | is_extension=False, extension_scope=None,
84 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
85 | ],
86 | extensions=[
87 | ],
88 | nested_types=[],
89 | enum_types=[
90 | ],
91 | serialized_options=None,
92 | is_extendable=False,
93 | syntax='proto2',
94 | extension_ranges=[],
95 | oneofs=[
96 | ],
97 | serialized_start=37,
98 | serialized_end=246,
99 | )
100 |
101 |
102 | _SIGNATUREINFO = _descriptor.Descriptor(
103 | name='SignatureInfo',
104 | full_name='SignatureInfo',
105 | filename=None,
106 | file=DESCRIPTOR,
107 | containing_type=None,
108 | create_key=_descriptor._internal_create_key,
109 | fields=[
110 | _descriptor.FieldDescriptor(
111 | name='app_bundle_id', full_name='SignatureInfo.app_bundle_id', index=0,
112 | number=1, type=9, cpp_type=9, label=1,
113 | has_default_value=False, default_value=b"".decode('utf-8'),
114 | message_type=None, enum_type=None, containing_type=None,
115 | is_extension=False, extension_scope=None,
116 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
117 | _descriptor.FieldDescriptor(
118 | name='android_package', full_name='SignatureInfo.android_package', index=1,
119 | number=2, type=9, cpp_type=9, label=1,
120 | has_default_value=False, default_value=b"".decode('utf-8'),
121 | message_type=None, enum_type=None, containing_type=None,
122 | is_extension=False, extension_scope=None,
123 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
124 | _descriptor.FieldDescriptor(
125 | name='verification_key_version', full_name='SignatureInfo.verification_key_version', index=2,
126 | number=3, type=9, cpp_type=9, label=1,
127 | has_default_value=False, default_value=b"".decode('utf-8'),
128 | message_type=None, enum_type=None, containing_type=None,
129 | is_extension=False, extension_scope=None,
130 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
131 | _descriptor.FieldDescriptor(
132 | name='verification_key_id', full_name='SignatureInfo.verification_key_id', index=3,
133 | number=4, type=9, cpp_type=9, label=1,
134 | has_default_value=False, default_value=b"".decode('utf-8'),
135 | message_type=None, enum_type=None, containing_type=None,
136 | is_extension=False, extension_scope=None,
137 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
138 | _descriptor.FieldDescriptor(
139 | name='signature_algorithm', full_name='SignatureInfo.signature_algorithm', index=4,
140 | number=5, type=9, cpp_type=9, label=1,
141 | has_default_value=False, default_value=b"".decode('utf-8'),
142 | message_type=None, enum_type=None, containing_type=None,
143 | is_extension=False, extension_scope=None,
144 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
145 | ],
146 | extensions=[
147 | ],
148 | nested_types=[],
149 | enum_types=[
150 | ],
151 | serialized_options=None,
152 | is_extendable=False,
153 | syntax='proto2',
154 | extension_ranges=[],
155 | oneofs=[
156 | ],
157 | serialized_start=249,
158 | serialized_end=404,
159 | )
160 |
161 |
162 | _TEMPORARYEXPOSUREKEY = _descriptor.Descriptor(
163 | name='TemporaryExposureKey',
164 | full_name='TemporaryExposureKey',
165 | filename=None,
166 | file=DESCRIPTOR,
167 | containing_type=None,
168 | create_key=_descriptor._internal_create_key,
169 | fields=[
170 | _descriptor.FieldDescriptor(
171 | name='key_data', full_name='TemporaryExposureKey.key_data', index=0,
172 | number=1, type=12, cpp_type=9, label=1,
173 | has_default_value=False, default_value=b"",
174 | message_type=None, enum_type=None, containing_type=None,
175 | is_extension=False, extension_scope=None,
176 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
177 | _descriptor.FieldDescriptor(
178 | name='transmission_risk_level', full_name='TemporaryExposureKey.transmission_risk_level', index=1,
179 | number=2, type=5, cpp_type=1, label=1,
180 | has_default_value=False, default_value=0,
181 | message_type=None, enum_type=None, containing_type=None,
182 | is_extension=False, extension_scope=None,
183 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
184 | _descriptor.FieldDescriptor(
185 | name='rolling_start_interval_number', full_name='TemporaryExposureKey.rolling_start_interval_number', index=2,
186 | number=3, type=5, cpp_type=1, label=1,
187 | has_default_value=False, default_value=0,
188 | message_type=None, enum_type=None, containing_type=None,
189 | is_extension=False, extension_scope=None,
190 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
191 | _descriptor.FieldDescriptor(
192 | name='rolling_period', full_name='TemporaryExposureKey.rolling_period', index=3,
193 | number=4, type=5, cpp_type=1, label=1,
194 | has_default_value=True, default_value=144,
195 | message_type=None, enum_type=None, containing_type=None,
196 | is_extension=False, extension_scope=None,
197 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
198 | ],
199 | extensions=[
200 | ],
201 | nested_types=[],
202 | enum_types=[
203 | ],
204 | serialized_options=None,
205 | is_extendable=False,
206 | syntax='proto2',
207 | extension_ranges=[],
208 | oneofs=[
209 | ],
210 | serialized_start=407,
211 | serialized_end=548,
212 | )
213 |
214 | _TEMPORARYEXPOSUREKEYEXPORT.fields_by_name['signature_infos'].message_type = _SIGNATUREINFO
215 | _TEMPORARYEXPOSUREKEYEXPORT.fields_by_name['keys'].message_type = _TEMPORARYEXPOSUREKEY
216 | DESCRIPTOR.message_types_by_name['TemporaryExposureKeyExport'] = _TEMPORARYEXPOSUREKEYEXPORT
217 | DESCRIPTOR.message_types_by_name['SignatureInfo'] = _SIGNATUREINFO
218 | DESCRIPTOR.message_types_by_name['TemporaryExposureKey'] = _TEMPORARYEXPOSUREKEY
219 | _sym_db.RegisterFileDescriptor(DESCRIPTOR)
220 |
221 | TemporaryExposureKeyExport = _reflection.GeneratedProtocolMessageType('TemporaryExposureKeyExport', (_message.Message,), {
222 | 'DESCRIPTOR' : _TEMPORARYEXPOSUREKEYEXPORT,
223 | '__module__' : 'TemporaryExposureKeyExport_pb2'
224 | # @@protoc_insertion_point(class_scope:TemporaryExposureKeyExport)
225 | })
226 | _sym_db.RegisterMessage(TemporaryExposureKeyExport)
227 |
228 | SignatureInfo = _reflection.GeneratedProtocolMessageType('SignatureInfo', (_message.Message,), {
229 | 'DESCRIPTOR' : _SIGNATUREINFO,
230 | '__module__' : 'TemporaryExposureKeyExport_pb2'
231 | # @@protoc_insertion_point(class_scope:SignatureInfo)
232 | })
233 | _sym_db.RegisterMessage(SignatureInfo)
234 |
235 | TemporaryExposureKey = _reflection.GeneratedProtocolMessageType('TemporaryExposureKey', (_message.Message,), {
236 | 'DESCRIPTOR' : _TEMPORARYEXPOSUREKEY,
237 | '__module__' : 'TemporaryExposureKeyExport_pb2'
238 | # @@protoc_insertion_point(class_scope:TemporaryExposureKey)
239 | })
240 | _sym_db.RegisterMessage(TemporaryExposureKey)
241 |
242 |
243 | # @@protoc_insertion_point(module_scope)
244 |
--------------------------------------------------------------------------------
/TemporaryExposureKeyExportV1_5_pb2.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # Generated by the protocol buffer compiler. DO NOT EDIT!
3 | # source: TemporaryExposureKeyExportV1_5.proto
4 |
5 | from google.protobuf import descriptor as _descriptor
6 | from google.protobuf import message as _message
7 | from google.protobuf import reflection as _reflection
8 | from google.protobuf import symbol_database as _symbol_database
9 | # @@protoc_insertion_point(imports)
10 |
11 | _sym_db = _symbol_database.Default()
12 |
13 |
14 |
15 |
16 | DESCRIPTOR = _descriptor.FileDescriptor(
17 | name='TemporaryExposureKeyExportV1_5.proto',
18 | package='',
19 | syntax='proto2',
20 | serialized_options=None,
21 | create_key=_descriptor._internal_create_key,
22 | serialized_pb=b'\n$TemporaryExposureKeyExportV1_5.proto\"\xfe\x01\n\x1aTemporaryExposureKeyExport\x12\x17\n\x0fstart_timestamp\x18\x01 \x01(\x06\x12\x15\n\rend_timestamp\x18\x02 \x01(\x06\x12\x0e\n\x06region\x18\x03 \x01(\t\x12\x11\n\tbatch_num\x18\x04 \x01(\x05\x12\x12\n\nbatch_size\x18\x05 \x01(\x05\x12\'\n\x0fsignature_infos\x18\x06 \x03(\x0b\x32\x0e.SignatureInfo\x12#\n\x04keys\x18\x07 \x03(\x0b\x32\x15.TemporaryExposureKey\x12+\n\x0crevised_keys\x18\x08 \x03(\x0b\x32\x15.TemporaryExposureKey\"\x97\x01\n\rSignatureInfo\x12 \n\x18verification_key_version\x18\x03 \x01(\t\x12\x1b\n\x13verification_key_id\x18\x04 \x01(\t\x12\x1b\n\x13signature_algorithm\x18\x05 \x01(\tJ\x04\x08\x01\x10\x02J\x04\x08\x02\x10\x03R\rapp_bundle_idR\x0f\x61ndroid_package\"\xec\x02\n\x14TemporaryExposureKey\x12\x10\n\x08key_data\x18\x01 \x01(\x0c\x12#\n\x17transmission_risk_level\x18\x02 \x01(\x05\x42\x02\x18\x01\x12%\n\x1drolling_start_interval_number\x18\x03 \x01(\x05\x12\x1b\n\x0erolling_period\x18\x04 \x01(\x05:\x03\x31\x34\x34\x12\x35\n\x0breport_type\x18\x05 \x01(\x0e\x32 .TemporaryExposureKey.ReportType\x12$\n\x1c\x64\x61ys_since_onset_of_symptoms\x18\x06 \x01(\x11\"|\n\nReportType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x12\n\x0e\x43ONFIRMED_TEST\x10\x01\x12 \n\x1c\x43ONFIRMED_CLINICAL_DIAGNOSIS\x10\x02\x12\x0f\n\x0bSELF_REPORT\x10\x03\x12\r\n\tRECURSIVE\x10\x04\x12\x0b\n\x07REVOKED\x10\x05'
23 | )
24 |
25 |
26 |
27 | _TEMPORARYEXPOSUREKEY_REPORTTYPE = _descriptor.EnumDescriptor(
28 | name='ReportType',
29 | full_name='TemporaryExposureKey.ReportType',
30 | filename=None,
31 | file=DESCRIPTOR,
32 | create_key=_descriptor._internal_create_key,
33 | values=[
34 | _descriptor.EnumValueDescriptor(
35 | name='UNKNOWN', index=0, number=0,
36 | serialized_options=None,
37 | type=None,
38 | create_key=_descriptor._internal_create_key),
39 | _descriptor.EnumValueDescriptor(
40 | name='CONFIRMED_TEST', index=1, number=1,
41 | serialized_options=None,
42 | type=None,
43 | create_key=_descriptor._internal_create_key),
44 | _descriptor.EnumValueDescriptor(
45 | name='CONFIRMED_CLINICAL_DIAGNOSIS', index=2, number=2,
46 | serialized_options=None,
47 | type=None,
48 | create_key=_descriptor._internal_create_key),
49 | _descriptor.EnumValueDescriptor(
50 | name='SELF_REPORT', index=3, number=3,
51 | serialized_options=None,
52 | type=None,
53 | create_key=_descriptor._internal_create_key),
54 | _descriptor.EnumValueDescriptor(
55 | name='RECURSIVE', index=4, number=4,
56 | serialized_options=None,
57 | type=None,
58 | create_key=_descriptor._internal_create_key),
59 | _descriptor.EnumValueDescriptor(
60 | name='REVOKED', index=5, number=5,
61 | serialized_options=None,
62 | type=None,
63 | create_key=_descriptor._internal_create_key),
64 | ],
65 | containing_type=None,
66 | serialized_options=None,
67 | serialized_start=692,
68 | serialized_end=816,
69 | )
70 | _sym_db.RegisterEnumDescriptor(_TEMPORARYEXPOSUREKEY_REPORTTYPE)
71 |
72 |
73 | _TEMPORARYEXPOSUREKEYEXPORT = _descriptor.Descriptor(
74 | name='TemporaryExposureKeyExport',
75 | full_name='TemporaryExposureKeyExport',
76 | filename=None,
77 | file=DESCRIPTOR,
78 | containing_type=None,
79 | create_key=_descriptor._internal_create_key,
80 | fields=[
81 | _descriptor.FieldDescriptor(
82 | name='start_timestamp', full_name='TemporaryExposureKeyExport.start_timestamp', index=0,
83 | number=1, type=6, cpp_type=4, label=1,
84 | has_default_value=False, default_value=0,
85 | message_type=None, enum_type=None, containing_type=None,
86 | is_extension=False, extension_scope=None,
87 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
88 | _descriptor.FieldDescriptor(
89 | name='end_timestamp', full_name='TemporaryExposureKeyExport.end_timestamp', index=1,
90 | number=2, type=6, cpp_type=4, label=1,
91 | has_default_value=False, default_value=0,
92 | message_type=None, enum_type=None, containing_type=None,
93 | is_extension=False, extension_scope=None,
94 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
95 | _descriptor.FieldDescriptor(
96 | name='region', full_name='TemporaryExposureKeyExport.region', index=2,
97 | number=3, type=9, cpp_type=9, label=1,
98 | has_default_value=False, default_value=b"".decode('utf-8'),
99 | message_type=None, enum_type=None, containing_type=None,
100 | is_extension=False, extension_scope=None,
101 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
102 | _descriptor.FieldDescriptor(
103 | name='batch_num', full_name='TemporaryExposureKeyExport.batch_num', index=3,
104 | number=4, type=5, cpp_type=1, label=1,
105 | has_default_value=False, default_value=0,
106 | message_type=None, enum_type=None, containing_type=None,
107 | is_extension=False, extension_scope=None,
108 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
109 | _descriptor.FieldDescriptor(
110 | name='batch_size', full_name='TemporaryExposureKeyExport.batch_size', index=4,
111 | number=5, type=5, cpp_type=1, label=1,
112 | has_default_value=False, default_value=0,
113 | message_type=None, enum_type=None, containing_type=None,
114 | is_extension=False, extension_scope=None,
115 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
116 | _descriptor.FieldDescriptor(
117 | name='signature_infos', full_name='TemporaryExposureKeyExport.signature_infos', index=5,
118 | number=6, type=11, cpp_type=10, label=3,
119 | has_default_value=False, default_value=[],
120 | message_type=None, enum_type=None, containing_type=None,
121 | is_extension=False, extension_scope=None,
122 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
123 | _descriptor.FieldDescriptor(
124 | name='keys', full_name='TemporaryExposureKeyExport.keys', index=6,
125 | number=7, type=11, cpp_type=10, label=3,
126 | has_default_value=False, default_value=[],
127 | message_type=None, enum_type=None, containing_type=None,
128 | is_extension=False, extension_scope=None,
129 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
130 | _descriptor.FieldDescriptor(
131 | name='revised_keys', full_name='TemporaryExposureKeyExport.revised_keys', index=7,
132 | number=8, type=11, cpp_type=10, label=3,
133 | has_default_value=False, default_value=[],
134 | message_type=None, enum_type=None, containing_type=None,
135 | is_extension=False, extension_scope=None,
136 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
137 | ],
138 | extensions=[
139 | ],
140 | nested_types=[],
141 | enum_types=[
142 | ],
143 | serialized_options=None,
144 | is_extendable=False,
145 | syntax='proto2',
146 | extension_ranges=[],
147 | oneofs=[
148 | ],
149 | serialized_start=41,
150 | serialized_end=295,
151 | )
152 |
153 |
154 | _SIGNATUREINFO = _descriptor.Descriptor(
155 | name='SignatureInfo',
156 | full_name='SignatureInfo',
157 | filename=None,
158 | file=DESCRIPTOR,
159 | containing_type=None,
160 | create_key=_descriptor._internal_create_key,
161 | fields=[
162 | _descriptor.FieldDescriptor(
163 | name='verification_key_version', full_name='SignatureInfo.verification_key_version', index=0,
164 | number=3, type=9, cpp_type=9, label=1,
165 | has_default_value=False, default_value=b"".decode('utf-8'),
166 | message_type=None, enum_type=None, containing_type=None,
167 | is_extension=False, extension_scope=None,
168 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
169 | _descriptor.FieldDescriptor(
170 | name='verification_key_id', full_name='SignatureInfo.verification_key_id', index=1,
171 | number=4, type=9, cpp_type=9, label=1,
172 | has_default_value=False, default_value=b"".decode('utf-8'),
173 | message_type=None, enum_type=None, containing_type=None,
174 | is_extension=False, extension_scope=None,
175 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
176 | _descriptor.FieldDescriptor(
177 | name='signature_algorithm', full_name='SignatureInfo.signature_algorithm', index=2,
178 | number=5, type=9, cpp_type=9, label=1,
179 | has_default_value=False, default_value=b"".decode('utf-8'),
180 | message_type=None, enum_type=None, containing_type=None,
181 | is_extension=False, extension_scope=None,
182 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
183 | ],
184 | extensions=[
185 | ],
186 | nested_types=[],
187 | enum_types=[
188 | ],
189 | serialized_options=None,
190 | is_extendable=False,
191 | syntax='proto2',
192 | extension_ranges=[],
193 | oneofs=[
194 | ],
195 | serialized_start=298,
196 | serialized_end=449,
197 | )
198 |
199 |
200 | _TEMPORARYEXPOSUREKEY = _descriptor.Descriptor(
201 | name='TemporaryExposureKey',
202 | full_name='TemporaryExposureKey',
203 | filename=None,
204 | file=DESCRIPTOR,
205 | containing_type=None,
206 | create_key=_descriptor._internal_create_key,
207 | fields=[
208 | _descriptor.FieldDescriptor(
209 | name='key_data', full_name='TemporaryExposureKey.key_data', index=0,
210 | number=1, type=12, cpp_type=9, label=1,
211 | has_default_value=False, default_value=b"",
212 | message_type=None, enum_type=None, containing_type=None,
213 | is_extension=False, extension_scope=None,
214 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
215 | _descriptor.FieldDescriptor(
216 | name='transmission_risk_level', full_name='TemporaryExposureKey.transmission_risk_level', index=1,
217 | number=2, type=5, cpp_type=1, label=1,
218 | has_default_value=False, default_value=0,
219 | message_type=None, enum_type=None, containing_type=None,
220 | is_extension=False, extension_scope=None,
221 | serialized_options=b'\030\001', file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
222 | _descriptor.FieldDescriptor(
223 | name='rolling_start_interval_number', full_name='TemporaryExposureKey.rolling_start_interval_number', index=2,
224 | number=3, type=5, cpp_type=1, label=1,
225 | has_default_value=False, default_value=0,
226 | message_type=None, enum_type=None, containing_type=None,
227 | is_extension=False, extension_scope=None,
228 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
229 | _descriptor.FieldDescriptor(
230 | name='rolling_period', full_name='TemporaryExposureKey.rolling_period', index=3,
231 | number=4, type=5, cpp_type=1, label=1,
232 | has_default_value=True, default_value=144,
233 | message_type=None, enum_type=None, containing_type=None,
234 | is_extension=False, extension_scope=None,
235 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
236 | _descriptor.FieldDescriptor(
237 | name='report_type', full_name='TemporaryExposureKey.report_type', index=4,
238 | number=5, type=14, cpp_type=8, label=1,
239 | has_default_value=False, default_value=0,
240 | message_type=None, enum_type=None, containing_type=None,
241 | is_extension=False, extension_scope=None,
242 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
243 | _descriptor.FieldDescriptor(
244 | name='days_since_onset_of_symptoms', full_name='TemporaryExposureKey.days_since_onset_of_symptoms', index=5,
245 | number=6, type=17, cpp_type=1, label=1,
246 | has_default_value=False, default_value=0,
247 | message_type=None, enum_type=None, containing_type=None,
248 | is_extension=False, extension_scope=None,
249 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
250 | ],
251 | extensions=[
252 | ],
253 | nested_types=[],
254 | enum_types=[
255 | _TEMPORARYEXPOSUREKEY_REPORTTYPE,
256 | ],
257 | serialized_options=None,
258 | is_extendable=False,
259 | syntax='proto2',
260 | extension_ranges=[],
261 | oneofs=[
262 | ],
263 | serialized_start=452,
264 | serialized_end=816,
265 | )
266 |
267 | _TEMPORARYEXPOSUREKEYEXPORT.fields_by_name['signature_infos'].message_type = _SIGNATUREINFO
268 | _TEMPORARYEXPOSUREKEYEXPORT.fields_by_name['keys'].message_type = _TEMPORARYEXPOSUREKEY
269 | _TEMPORARYEXPOSUREKEYEXPORT.fields_by_name['revised_keys'].message_type = _TEMPORARYEXPOSUREKEY
270 | _TEMPORARYEXPOSUREKEY.fields_by_name['report_type'].enum_type = _TEMPORARYEXPOSUREKEY_REPORTTYPE
271 | _TEMPORARYEXPOSUREKEY_REPORTTYPE.containing_type = _TEMPORARYEXPOSUREKEY
272 | DESCRIPTOR.message_types_by_name['TemporaryExposureKeyExport'] = _TEMPORARYEXPOSUREKEYEXPORT
273 | DESCRIPTOR.message_types_by_name['SignatureInfo'] = _SIGNATUREINFO
274 | DESCRIPTOR.message_types_by_name['TemporaryExposureKey'] = _TEMPORARYEXPOSUREKEY
275 | _sym_db.RegisterFileDescriptor(DESCRIPTOR)
276 |
277 | TemporaryExposureKeyExport = _reflection.GeneratedProtocolMessageType('TemporaryExposureKeyExport', (_message.Message,), {
278 | 'DESCRIPTOR' : _TEMPORARYEXPOSUREKEYEXPORT,
279 | '__module__' : 'TemporaryExposureKeyExportV1.5_pb2'
280 | # @@protoc_insertion_point(class_scope:TemporaryExposureKeyExport)
281 | })
282 | _sym_db.RegisterMessage(TemporaryExposureKeyExport)
283 |
284 | SignatureInfo = _reflection.GeneratedProtocolMessageType('SignatureInfo', (_message.Message,), {
285 | 'DESCRIPTOR' : _SIGNATUREINFO,
286 | '__module__' : 'TemporaryExposureKeyExportV1.5_pb2'
287 | # @@protoc_insertion_point(class_scope:SignatureInfo)
288 | })
289 | _sym_db.RegisterMessage(SignatureInfo)
290 |
291 | TemporaryExposureKey = _reflection.GeneratedProtocolMessageType('TemporaryExposureKey', (_message.Message,), {
292 | 'DESCRIPTOR' : _TEMPORARYEXPOSUREKEY,
293 | '__module__' : 'TemporaryExposureKeyExportV1.5_pb2'
294 | # @@protoc_insertion_point(class_scope:TemporaryExposureKey)
295 | })
296 | _sym_db.RegisterMessage(TemporaryExposureKey)
297 |
298 |
299 | _TEMPORARYEXPOSUREKEY.fields_by_name['transmission_risk_level']._options = None
300 | # @@protoc_insertion_point(module_scope)
301 |
--------------------------------------------------------------------------------
/count_keys.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | from lib.diagnosis_keys import *
4 | from lib.conversions import *
5 | import argparse
6 | from lib.diagnosis_key import DiagnosisKey
7 | from lib.count_users_v1_5 import count_users
8 |
9 | parser = argparse.ArgumentParser(description="Exposure Notification Diagnosis Key Parser / Counter.",
10 | formatter_class=argparse.ArgumentDefaultsHelpFormatter)
11 | parser.add_argument("-d", "--diagnosiskeys", type=str,
12 | help="file name of the Diagnosis Keys .zip file")
13 | parser.add_argument("-t", "--print-metadata", action="store_true",
14 | help="print metadata from the Diagnosis Keys .zip file")
15 | parser.add_argument("-k", "--print-keys", action="store_true",
16 | help="print all keys from the Diagnosis Keys .zip file")
17 | parser.add_argument("-m", "--multiplier", type=int, default=1,
18 | help="padding multiplier (RANDOM_KEY_PADDING_MULTIPLIER as set on cwa-server)")
19 | parser.add_argument("-a", "--auto-multiplier", action="store_true",
20 | help="automatically detect the multiplier (range 1..10)")
21 | args = parser.parse_args()
22 |
23 | dk_file_name = args.diagnosiskeys
24 |
25 | print("Exposure Notification Diagnosis Key Parser / Counter")
26 | print("This script counts published Diagnosis Keys.\n")
27 | # see https://github.com/google/exposure-notifications-server/tree/master/examples/export
28 |
29 | dk = DiagnosisKeys(dk_file_name)
30 | print("File '%s' read." % dk_file_name)
31 |
32 | start_timestamp = dk.get_upload_start_timestamp()
33 | end_timestamp = dk.get_upload_end_timestamp()
34 | if args.print_metadata:
35 | print("- Time window: %s - %s" % (get_string_from_datetime(start_timestamp),
36 | get_string_from_datetime(end_timestamp)))
37 | print("- Region: %s" % dk.get_region())
38 | print("- Batch: %d of %d" % (dk.get_batch_num(), dk.get_batch_size()))
39 | print("- # of keys in batch: %d" % len(dk.get_keys()))
40 |
41 | for signature_info in dk.get_signature_infos():
42 | print("- Signature Info:")
43 | print(signature_info)
44 |
45 | dk_list = []
46 |
47 | keys = None
48 | for _ in [0, 1]:
49 | if _ == 0:
50 | keys = dk.get_keys()
51 | if args.print_keys:
52 | print("Diagnosis Keys:")
53 | elif _ == 1:
54 | keys = dk.get_revised_keys()
55 | if args.print_keys:
56 | print("\nRevised Diagnosis Keys:")
57 | if args.print_keys:
58 | if len(keys) == 0:
59 | print("(none)\n")
60 |
61 | count = 0
62 | for tek in keys:
63 | count += 1
64 | start_timestamp = \
65 | get_datetime_from_utc_timestamp(get_timestamp_from_interval(tek.rolling_start_interval_number))
66 | end_timestamp = \
67 | get_datetime_from_utc_timestamp(get_timestamp_from_interval(tek.rolling_start_interval_number +
68 | tek.rolling_period))
69 |
70 | if args.print_keys:
71 | print("%5d: TEK: %s, Transmission Risk Level: %s, Validity: %s - %s (%d, %d)" %
72 | (count, tek.key_data.hex(), tek.transmission_risk_level,
73 | get_string_from_datetime(start_timestamp),
74 | get_string_from_datetime(end_timestamp),
75 | tek.rolling_start_interval_number, tek.rolling_period),
76 | end='')
77 | if tek.HasField("report_type"):
78 | field_types = ["UNKNOWN", "CONFIRMED_TEST", "CONFIRMED_CLINICAL_DIAGNOSIS",
79 | "SELF_REPORT", "RECURSIVE", "REVOKED"]
80 | print(", Report Type: %s" % field_types[tek.report_type], end='')
81 | if tek.HasField("days_since_onset_of_symptoms"):
82 | print(", Days since onset of symptoms: %d" % tek.days_since_onset_of_symptoms, end='')
83 | print()
84 |
85 | dk_list.append(DiagnosisKey(tek.key_data, tek.rolling_start_interval_number, tek.rolling_period,
86 | tek.transmission_risk_level))
87 |
88 | count_users(dk_list, padding_multiplier=args.multiplier, auto_multiplier_detect=args.auto_multiplier)
89 |
--------------------------------------------------------------------------------
/create_demo_key_set.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | from lib.diagnosis_keys_write import *
4 | import argparse
5 |
6 | parser = argparse.ArgumentParser(description="Exposure Notification Demo Diagnosis Key Set Generator.",
7 | formatter_class=argparse.ArgumentDefaultsHelpFormatter)
8 | parser.add_argument("-d", "--diagnosiskeys", type=str, default="demo_dks.zip",
9 | help="file name of the Diagnosis Keys .zip file that should be generated")
10 | args = parser.parse_args()
11 |
12 | dk_file_name = args.diagnosiskeys
13 |
14 | print("Exposure Notification Demo Diagnosis Key Set Generator")
15 | print("This script generates a Demo Diagnosis Keys Set for apps that parse these keys.\n")
16 |
17 | dk = DiagnosisKeysWriter(dk_file_name)
18 | print("File '%s' written." % dk_file_name)
19 |
20 |
--------------------------------------------------------------------------------
/derive_aem_key.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | from lib.crypto import *
4 | import argparse
5 |
6 | parser = argparse.ArgumentParser(description="Derive AEM-Key from TEK.")
7 | parser.add_argument("TEK", type=str,
8 | help="TEK (16 bytes hex)")
9 | args = parser.parse_args()
10 |
11 | try:
12 | tek = bytes.fromhex(args.TEK)
13 | if len(tek) != 16:
14 | raise ValueError
15 | except ValueError:
16 | parser.error("TEK must be 16 bytes hex")
17 |
18 | # print("TEK: %s" % tek.hex())
19 | print(derive_aem_key(tek).hex())
20 |
--------------------------------------------------------------------------------
/derive_rpi_key.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | from lib.crypto import *
4 | import argparse
5 |
6 | parser = argparse.ArgumentParser(description="Derive RPI-Key from TEK.")
7 | parser.add_argument("TEK", type=str,
8 | help="TEK (16 bytes hex)")
9 | args = parser.parse_args()
10 |
11 | try:
12 | tek = bytes.fromhex(args.TEK)
13 | if len(tek) != 16:
14 | raise ValueError
15 | except ValueError:
16 | parser.error("TEK must be 16 bytes hex")
17 |
18 | # print("TEK: %s" % tek.hex())
19 | print(derive_rpi_key(tek).hex())
20 |
--------------------------------------------------------------------------------
/doc/algorithm.md:
--------------------------------------------------------------------------------
1 | ## TRL Profile
2 |
3 | The TRL (transmission risk level) profile determines the TRL that is attached to each Diagnosis Key.
4 | For each day in the past, a value from this list is selected by the cwa-app:
5 | ```
6 | trl_profile = [5, 6, 8, 8, 8, 5, 3, 1, 1, 1, 1, 1, 1, 1] # 0: today, 1: yesterday, ...
7 | ```
8 | Today's key is not uploaded, so the maximum numbers of keys that can be uploaded is 13.
9 | (Case 4 / Fig. 14 in https://github.com/corona-warn-app/cwa-documentation/blob/master/transmission_risk.pdf)
10 |
11 | ## Counting Users
12 |
13 | After https://github.com/corona-warn-app/cwa-app-android/issues/678
14 | was fixed, and using a Android app that contains the fix is now enforced by cwa-server,
15 | every user will - at the moment - at least submit exactly one key with TRL == 6.
16 | So this could be used to count the number of users submitting keys.
17 | Note that this can change when https://github.com/corona-warn-app/cwa-documentation/issues/343
18 | will be fixed, because then a user might upload older keys, but not yesterday's key.
19 |
20 | ## Counting Keys per User
21 |
22 | A simple algorithm tracks the TRL profile chain through the list of Diagnosis Keys and stops at 13,
23 | or when it doesn't find the correct TRL in any keys from the previous day. Each found key is counted
24 | and then deleted from the list.
25 |
26 | However there is a problem with _missing keys_:
27 | The simple algorithm fails if a user has stopped Exposure Notifications for at least one day,
28 | because then a key was not generated nor uploaded for that day. This would result in non-parsed keys.
29 |
30 | Before we improve the algorithm, let's first look at corner cases that could happen.
31 |
32 | Assuming the currently uploaded TRL profiles (with #343 not fixed), _missing keys_ would require that
33 | the algorithm searches for a key with the previous day's TRL not only in previous day's keys, but also
34 | in older keys, for up to -13 days. If TRL paths cross, the wrong path might be followed, but that would
35 | still yield correct counts.
36 |
37 | With #343 fixed, _missing keys_ could cause scenarios like these:
38 |
39 | ```
40 | 01 02 03 04 05 06 07 08 09 10 11 12 13
41 | user a 8 8 8 5 3 # 5 keys
42 | user b 1 1 1 1 1 1 1 # 7 keys
43 | user c 6 # 1 key
44 |
45 | mixed 6 8 8 8 5 3 1 1 1 1 1 1 1 # 1 user with 13 keys
46 | ```
47 | ```
48 | 01 02 03 04 05 06 07 08 09 10 11 12 13
49 | user a 6 8 8 8 5 3 1 # 7 keys
50 | user b 1 1 1 1 1 1 1 # 7 keys
51 |
52 | mixed 6 8 8 8 5 3 1 1 1 1 1 1 1 # 1 user with 13 keys
53 | 1 # 1 user with 1 key
54 | ```
55 | So with #343 fixed, the result of the (desired) anonymization on the server would be that
56 | the number of users counted by the algorithm will likely be **lower than in reality**
57 | and the keys per user cannot be counted correctly anymore.
58 |
--------------------------------------------------------------------------------
/lib/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mh-/diagnosis-keys/25cebbd24204200f9b986dffeaf0133cdd74727f/lib/__init__.py
--------------------------------------------------------------------------------
/lib/contact_records_pb2.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # Generated by the protocol buffer compiler. DO NOT EDIT!
3 | # source: contact_records.proto
4 |
5 | from google.protobuf import descriptor as _descriptor
6 | from google.protobuf import message as _message
7 | from google.protobuf import reflection as _reflection
8 | from google.protobuf import symbol_database as _symbol_database
9 | # @@protoc_insertion_point(imports)
10 |
11 | _sym_db = _symbol_database.Default()
12 |
13 |
14 |
15 |
16 | DESCRIPTOR = _descriptor.FileDescriptor(
17 | name='contact_records.proto',
18 | package='gms.en',
19 | syntax='proto2',
20 | serialized_options=None,
21 | create_key=_descriptor._internal_create_key,
22 | serialized_pb=b'\n\x15\x63ontact_records.proto\x12\x06gms.en\":\n\nScanRecord\x12\x11\n\ttimestamp\x18\x01 \x01(\r\x12\x0c\n\x04rssi\x18\x03 \x01(\x03\x12\x0b\n\x03\x61\x65m\x18\x04 \x01(\x0c\"8\n\x0e\x43ontactRecords\x12&\n\nscanrecord\x18\x01 \x03(\x0b\x32\x12.gms.en.ScanRecord'
23 | )
24 |
25 |
26 |
27 |
28 | _SCANRECORD = _descriptor.Descriptor(
29 | name='ScanRecord',
30 | full_name='gms.en.ScanRecord',
31 | filename=None,
32 | file=DESCRIPTOR,
33 | containing_type=None,
34 | create_key=_descriptor._internal_create_key,
35 | fields=[
36 | _descriptor.FieldDescriptor(
37 | name='timestamp', full_name='gms.en.ScanRecord.timestamp', index=0,
38 | number=1, type=13, cpp_type=3, label=1,
39 | has_default_value=False, default_value=0,
40 | message_type=None, enum_type=None, containing_type=None,
41 | is_extension=False, extension_scope=None,
42 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
43 | _descriptor.FieldDescriptor(
44 | name='rssi', full_name='gms.en.ScanRecord.rssi', index=1,
45 | number=3, type=3, cpp_type=2, label=1,
46 | has_default_value=False, default_value=0,
47 | message_type=None, enum_type=None, containing_type=None,
48 | is_extension=False, extension_scope=None,
49 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
50 | _descriptor.FieldDescriptor(
51 | name='aem', full_name='gms.en.ScanRecord.aem', index=2,
52 | number=4, type=12, cpp_type=9, label=1,
53 | has_default_value=False, default_value=b"",
54 | message_type=None, enum_type=None, containing_type=None,
55 | is_extension=False, extension_scope=None,
56 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
57 | ],
58 | extensions=[
59 | ],
60 | nested_types=[],
61 | enum_types=[
62 | ],
63 | serialized_options=None,
64 | is_extendable=False,
65 | syntax='proto2',
66 | extension_ranges=[],
67 | oneofs=[
68 | ],
69 | serialized_start=33,
70 | serialized_end=91,
71 | )
72 |
73 |
74 | _CONTACTRECORDS = _descriptor.Descriptor(
75 | name='ContactRecords',
76 | full_name='gms.en.ContactRecords',
77 | filename=None,
78 | file=DESCRIPTOR,
79 | containing_type=None,
80 | create_key=_descriptor._internal_create_key,
81 | fields=[
82 | _descriptor.FieldDescriptor(
83 | name='scanrecord', full_name='gms.en.ContactRecords.scanrecord', index=0,
84 | number=1, type=11, cpp_type=10, label=3,
85 | has_default_value=False, default_value=[],
86 | message_type=None, enum_type=None, containing_type=None,
87 | is_extension=False, extension_scope=None,
88 | serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
89 | ],
90 | extensions=[
91 | ],
92 | nested_types=[],
93 | enum_types=[
94 | ],
95 | serialized_options=None,
96 | is_extendable=False,
97 | syntax='proto2',
98 | extension_ranges=[],
99 | oneofs=[
100 | ],
101 | serialized_start=93,
102 | serialized_end=149,
103 | )
104 |
105 | _CONTACTRECORDS.fields_by_name['scanrecord'].message_type = _SCANRECORD
106 | DESCRIPTOR.message_types_by_name['ScanRecord'] = _SCANRECORD
107 | DESCRIPTOR.message_types_by_name['ContactRecords'] = _CONTACTRECORDS
108 | _sym_db.RegisterFileDescriptor(DESCRIPTOR)
109 |
110 | ScanRecord = _reflection.GeneratedProtocolMessageType('ScanRecord', (_message.Message,), {
111 | 'DESCRIPTOR' : _SCANRECORD,
112 | '__module__' : 'contact_records_pb2'
113 | # @@protoc_insertion_point(class_scope:gms.en.ScanRecord)
114 | })
115 | _sym_db.RegisterMessage(ScanRecord)
116 |
117 | ContactRecords = _reflection.GeneratedProtocolMessageType('ContactRecords', (_message.Message,), {
118 | 'DESCRIPTOR' : _CONTACTRECORDS,
119 | '__module__' : 'contact_records_pb2'
120 | # @@protoc_insertion_point(class_scope:gms.en.ContactRecords)
121 | })
122 | _sym_db.RegisterMessage(ContactRecords)
123 |
124 |
125 | # @@protoc_insertion_point(module_scope)
126 |
--------------------------------------------------------------------------------
/lib/conversions.py:
--------------------------------------------------------------------------------
1 | import datetime
2 |
3 | interval_length_minutes = 10 # 10 minutes per interval
4 | tek_rolling_period = 144 # 24*60//10 - 24 hours per day, 60 minutes per hour, 10 minutes per interval
5 |
6 |
7 | def get_timestamp_from_interval(interval_number):
8 | return interval_number * interval_length_minutes * 60 # 60 seconds per minute
9 |
10 |
11 | def get_interval_from_utc_timestamp(utc_time_stamp):
12 | return utc_time_stamp // (interval_length_minutes * 60) # 60 seconds per minute
13 |
14 |
15 | def get_datetime_from_utc_timestamp(utc_timestamp):
16 | return datetime.datetime.utcfromtimestamp(utc_timestamp).replace(tzinfo=datetime.timezone.utc)
17 |
18 |
19 | def get_timestamp_from_utc_datetime(utc_datetime):
20 | return int(datetime.datetime.timestamp(utc_datetime))
21 |
22 |
23 | def get_local_datetime(date_time):
24 | return date_time.astimezone(datetime.datetime.utcnow().astimezone().tzinfo)
25 |
26 |
27 | def get_string_from_datetime(date_time):
28 | return date_time.strftime('%Y-%m-%d %H:%M:%S %Z')
29 |
--------------------------------------------------------------------------------
/lib/count_users.py:
--------------------------------------------------------------------------------
1 | trl_profile = [5, 6, 8, 8, 8, 5, 3, 1, 1, 1, 1, 1, 1, 1] # 0: today, 1: yesterday, ...
2 |
3 |
4 | def count_users(diagnosis_key_list, multiplier=10, auto_multiplier_detect=False,
5 | new_android_apps_only=False):
6 | print("Parsing the Diagnosis Key list, counting unique users...")
7 | original_len = len(diagnosis_key_list)
8 | if not auto_multiplier_detect:
9 | print("Length: %d keys (%d without padding)" % (original_len, original_len // multiplier))
10 | if len(diagnosis_key_list) % multiplier != 0:
11 | print("WARNING: Apparently the list is not padded by %d!" % multiplier)
12 | else:
13 | print("Length: %d keys" % original_len)
14 |
15 | user_days = []
16 | num_old_android_apps = 0
17 |
18 | if len(diagnosis_key_list) > 0:
19 | latest_interval = max(dk.start_interval for dk in diagnosis_key_list)
20 | min_interval = latest_interval - 14*144
21 | else:
22 | # no keys provided, skip user count
23 | print("%d user(s) found." % 0)
24 | return
25 |
26 | if not new_android_apps_only:
27 | search_range = [0, 1]
28 | else:
29 | search_range = range(0, 15)
30 |
31 | for i in search_range:
32 | # do this twice, because if keys are distributed in the morning,
33 | # they could include yesterday's submissions
34 |
35 | if not new_android_apps_only:
36 | # First search for 'invalid' TRL profiles, caused by old Android apps
37 | # (before this fix was released: https://github.com/corona-warn-app/cwa-app-android/pull/679)
38 |
39 | if len(diagnosis_key_list) > 0:
40 | top_level_dks = [dk for dk in diagnosis_key_list if dk.start_interval == latest_interval]
41 | for dk in top_level_dks:
42 | try:
43 | pos = trl_profile[2:].index(dk.transmission_risk_level)+2
44 | except ValueError:
45 | continue
46 | diagnosis_key_list.remove(dk)
47 | days = 1
48 | interval = latest_interval
49 | while pos > 1:
50 | interval -= 144
51 | next_dk = next((dk_entry for dk_entry in diagnosis_key_list
52 | if (dk_entry.start_interval == interval) and
53 | (dk_entry.transmission_risk_level == trl_profile[pos-1])), None)
54 | if (next_dk is None) and (trl_profile[pos] == 8):
55 | pos += 1
56 | next_dk = next((dk_entry for dk_entry in diagnosis_key_list
57 | if (dk_entry.start_interval == interval) and
58 | (dk_entry.transmission_risk_level == trl_profile[pos - 1])), None)
59 | if next_dk is None:
60 | break
61 | diagnosis_key_list.remove(next_dk)
62 | days += 1
63 | pos -= 1
64 | user_days.append(days)
65 | num_old_android_apps += 1
66 |
67 | # Now search for 'standard' TRL profiles
68 |
69 | if len(diagnosis_key_list) > 0:
70 | top_level_dks = [dk for dk in diagnosis_key_list if dk.start_interval == latest_interval]
71 | for dk in top_level_dks:
72 | days = 0
73 | if dk.transmission_risk_level == trl_profile[1]: # newest entry is from yesterday
74 | diagnosis_key_list.remove(dk)
75 | days = 1
76 | interval = latest_interval
77 | while days < len(trl_profile)-1:
78 | interval -= 144
79 | if not new_android_apps_only:
80 | next_dk = next((dk_entry for dk_entry in diagnosis_key_list
81 | if (dk_entry.start_interval == interval) and
82 | (dk_entry.transmission_risk_level == trl_profile[days+1])),
83 | None)
84 | else: # new_android_apps_only
85 | next_dk = None
86 | while interval >= min_interval:
87 | next_dk = next((dk_entry for dk_entry in diagnosis_key_list
88 | if (dk_entry.start_interval == interval) and
89 | (dk_entry.transmission_risk_level == trl_profile[days + 1])),
90 | None)
91 | if next_dk is not None:
92 | break
93 | interval -= 144
94 |
95 | if next_dk is None:
96 | break
97 | diagnosis_key_list.remove(next_dk)
98 | days += 1
99 | user_days.append(days)
100 |
101 | latest_interval -= 144
102 |
103 | days_count = [0] * 15
104 | for entry in user_days:
105 | days_count[entry] += 1
106 |
107 | if auto_multiplier_detect:
108 | relevant_values = [original_len, len(diagnosis_key_list), len(user_days), num_old_android_apps]
109 | relevant_values.extend(days_count)
110 | for multiplier_candidate in reversed(range(1, multiplier+1)):
111 | candidate_suitable = True
112 | for value in relevant_values:
113 | if not value % multiplier_candidate == 0:
114 | candidate_suitable = False
115 | break
116 | if candidate_suitable:
117 | # (we will reach this latest with multiplier_candidate == 1)
118 | multiplier = multiplier_candidate
119 | break
120 | print("Padding Multiplier detected: %d" % multiplier)
121 |
122 | reduced_users = len(user_days) // multiplier
123 | print("%d user(s) found." % reduced_users)
124 |
125 | reduced_days_count = [days // multiplier for days in days_count]
126 | print("They submitted these numbers of keys:")
127 | days = 0
128 | for count in reduced_days_count:
129 | if count > 0:
130 | if days > 0:
131 | print("%d user(s): %d Diagnosis Key(s)" % (count, days))
132 | else:
133 | print("%d user(s): Invalid Transmission Risk Profile" % count)
134 | days += 1
135 |
136 | if num_old_android_apps > 0:
137 | print("Old Android app used by %d user(s)." % (num_old_android_apps // multiplier))
138 | print("%d keys not parsed (%d without padding)." % (len(diagnosis_key_list), len(diagnosis_key_list) // multiplier))
139 |
140 | # print statistics / https://github.com/corona-warn-app/cwa-documentation/issues/258#issuecomment-649007240
141 | print("%d / " % reduced_users, end='')
142 | comma = False
143 | days = 0
144 | for count in reduced_days_count:
145 | if count > 0:
146 | if days > 0:
147 | if not comma:
148 | comma = True
149 | else:
150 | print(", ", end='')
151 | print("%d*%d" % (count, days), end='')
152 | days += 1
153 | if num_old_android_apps > 0:
154 | print(" (%d old Android app(s))" % (num_old_android_apps // multiplier), end='')
155 | print()
156 |
--------------------------------------------------------------------------------
/lib/count_users_v1_5.py:
--------------------------------------------------------------------------------
1 | # Count Users who reported keys using CWA 1.5ff
2 | # see https://github.com/mh-/diagnosis-keys/issues/12
3 | import math
4 | import sys
5 | from lib.conversions import get_datetime_from_utc_timestamp, get_timestamp_from_interval, tek_rolling_period
6 |
7 | # TRL Profiles: (0: today, 1: yesterday, ...) # why 15 values, not 14?
8 | trl_profiles = [[5, 6, 8, 8, 8, 5, 3, 1, 1, 1, 1, 1, 1, 1, 1], # "classic"
9 | [5, 6, 7, 7, 7, 6, 4, 3, 2, 1, 1, 1, 1, 1, 1], # noInformation
10 | [4, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # nonSymptomatic
11 | [5, 6, 8, 8, 8, 7, 5, 3, 2, 1, 1, 1, 1, 1, 1], # symptomaticWithUnknownOnset
12 | [4, 5, 6, 7, 7, 7, 6, 5, 4, 3, 2, 1, 1, 1, 1], # lastSevenDays
13 | [1, 1, 1, 1, 2, 3, 4, 5, 6, 6, 7, 7, 6, 6, 4], # oneToTwoWeeksAgo
14 | [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5]] # moreThanTwoWeeksAgo
15 |
16 |
17 | def count_users(diagnosis_key_list, padding_multiplier=5, auto_multiplier_detect=False):
18 | print("\nParsing the Diagnosis Key list...")
19 | original_len = len(diagnosis_key_list)
20 | if not auto_multiplier_detect:
21 | print("Length: %d keys (%d without padding)" % (original_len, original_len // padding_multiplier))
22 | if len(diagnosis_key_list) % padding_multiplier != 0:
23 | print("WARNING: The number of keys is not a multiple of %d!" % padding_multiplier)
24 | print("See https://github.com/corona-warn-app/cwa-server/issues/693#issuecomment-672688610",
25 | "for a possible explanation.")
26 | else:
27 | print("Length: %d keys" % original_len)
28 |
29 | # find min and max start timestamp (interval) in the DK list
30 | min_interval = sys.maxsize
31 | max_interval = 0
32 | for dk in diagnosis_key_list:
33 | if min_interval > dk.start_interval:
34 | min_interval = dk.start_interval
35 | if max_interval < dk.start_interval:
36 | max_interval = dk.start_interval
37 |
38 | # create a dictionary for each day (also for days that might not have entries in the DK list)
39 | # key: start_interval, value: a list of 8 counters
40 | days_dict = dict()
41 | for interval in range(min_interval, max_interval+1, tek_rolling_period):
42 | days_dict[interval] = [0, 0, 0, 0, 0, 0, 0, 0] # number of entries for TRLs from 1 to 8
43 |
44 | # detect padding multiplier
45 | if auto_multiplier_detect:
46 | multiplier_candidate_table = [0, 0, 0, 0, 0] # 1, 2, 3, 4, 5
47 |
48 | # count number of TRLs for each day
49 | max_value = 0
50 | for dk in diagnosis_key_list:
51 | trl_nums = days_dict[dk.start_interval]
52 | value = trl_nums[dk.transmission_risk_level-1] + 1
53 | trl_nums[dk.transmission_risk_level-1] = value
54 | if max_value < value:
55 | max_value = value
56 | days_dict[dk.start_interval] = trl_nums
57 |
58 | # print number of TRL for each day
59 | max_value_width = len("{num}".format(num=max_value))
60 | trl_sums = [0, 0, 0, 0, 0, 0, 0, 0]
61 | print("Number of keys per TRL:")
62 | print("Date: ", end='')
63 | for trl in range(8):
64 | print("{num:{width}}".format(num=trl+1, width=max_value_width + 3), end='')
65 | print(" Sum:")
66 | # for each day:
67 | max_row_sum = 0
68 | for key in sorted(days_dict.keys(), reverse=True):
69 | print(get_datetime_from_utc_timestamp(get_timestamp_from_interval(key)).strftime("%Y-%m-%d: "), end='')
70 | row_sum = 0
71 | trl = 0
72 | for trl_num in days_dict[key]:
73 | print("{num:{width}}".format(num=trl_num, width=max_value_width + 3), end='')
74 | row_sum += trl_num
75 | trl += 1
76 | trl_sums[trl-1] += trl_num
77 | # detect padding multiplier
78 | if auto_multiplier_detect:
79 | for candidate in range(len(multiplier_candidate_table), 0, -1):
80 | if trl_num % candidate == 0:
81 | multiplier_candidate_table[candidate-1] += 1
82 | break
83 | # print row sum:
84 | print(" {num:{width}}".format(num=row_sum, width=max_value_width + 2))
85 | if max_row_sum < row_sum:
86 | max_row_sum = row_sum
87 |
88 | # print column sum:
89 | total = 0
90 | print("Total: ", end='')
91 | for row_sum in trl_sums:
92 | print("{num:{width}}".format(num=row_sum, width=max_value_width + 3), end='')
93 | total += row_sum
94 | print(" {num:{width}}".format(num=total, width=max_value_width + 2))
95 | print()
96 |
97 | # find padding_multiplier
98 | if auto_multiplier_detect:
99 | max_value = max(multiplier_candidate_table)
100 | for candidate in range(len(multiplier_candidate_table), 0, -1):
101 | if multiplier_candidate_table[candidate-1] == max_value:
102 | padding_multiplier = candidate
103 | break
104 | print("Padding multiplier is probably: %d" % padding_multiplier)
105 |
106 | # print results:
107 | # column sum of TRL 6
108 | old_user_count = math.ceil(trl_sums[6-1] / padding_multiplier)
109 | # maximum row sum
110 | new_user_count = math.ceil(max_row_sum / padding_multiplier)
111 | print("Pre-V1.5 user count: %d" % old_user_count)
112 | print("Post-V1.5 user count: %d" % new_user_count)
113 |
--------------------------------------------------------------------------------
/lib/crypto.py:
--------------------------------------------------------------------------------
1 | from Crypto.Protocol.KDF import HKDF
2 | from Crypto.Hash import SHA256
3 | from Crypto.Cipher import AES
4 | import struct
5 |
6 | interval_length_minutes = 10
7 | tek_rolling_period=144
8 |
9 |
10 | def en_interval_number(timestamp_seconds):
11 | return timestamp_seconds // (60 * interval_length_minutes)
12 |
13 |
14 | def encoded_en_interval_number(enin):
15 | return struct.pack("= 1, trl <= 8
55 | key.transmission_risk_level = trl
56 | assert start > 0
57 | key.rolling_start_interval_number = start
58 | assert duration <= 144
59 | key.rolling_period = duration
60 | assert report_type >= 0, report_type <= 5
61 | key.report_type = report_type
62 |
--------------------------------------------------------------------------------
/lib/ramble_rpis.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 | from lib.conversions import get_datetime_from_utc_timestamp
3 | from lib.scanned_rpis import RPIEntry
4 |
5 |
6 | class RambleRPIs:
7 |
8 | __ramble_sql_script= \
9 | """
10 | SELECT
11 | locations.timestamp as 'timestamp_start',
12 | locations.timestamp as 'timestamp_end',
13 | devices.service_data as 'identifier',
14 | locations.rssi as 'rssi',
15 | devices.id as 'device_id',
16 | locations.latitude as 'lat',
17 | locations.longitude as 'long'
18 | FROM
19 | devices
20 | INNER JOIN locations ON devices.id = locations.device_id
21 | WHERE
22 | devices.service_data LIKE 'fd6f:%'
23 | ORDER BY
24 | devices.id, locations.timestamp;
25 | """
26 |
27 | def __init__(self, file_name):
28 | self.rpis_dict = dict()
29 | with sqlite3.connect(file_name) as db_conn:
30 | rpi_reader = db_conn.execute(RambleRPIs.__ramble_sql_script)
31 | # StartTime, EndTime, RPI, AEM, MaxRSSI, BDADDR [, LAT, LON, Altitude, Speed]
32 | full_rpi_list = rpi_reader.fetchall()
33 | rpi_list = []
34 | # get start and end date from multiple rows
35 | for c_row, row in enumerate(full_rpi_list):
36 | if (c_row > 0) and (row[4] == full_rpi_list[c_row-1][4]):
37 | rpi_list[-1][1] = row[1] # replace end date with later timestamp
38 | if rpi_list[-1][3] < row[3]: #replace stronger RSSI
39 | rpi_list[-1][3] = row[3]
40 | else:
41 | rpi_list.append(list(row)) # first entry for this ID, create it
42 |
43 | for row in rpi_list:
44 | rpi_value = row[2][5:37]
45 | aem_value = row[2][37:]
46 | rpi = RPIEntry(get_datetime_from_utc_timestamp(int(row[0])),
47 | get_datetime_from_utc_timestamp(int(row[1])),
48 | bytes.fromhex(rpi_value), bytes.fromhex(aem_value),
49 | int(row[3]), row[4],
50 | lat=row[5], lon=row[6])
51 |
52 | if rpi.rpi in self.rpis_dict:
53 | existing_entries = self.rpis_dict[rpi.rpi]
54 | existing_entries.append(rpi)
55 | self.rpis_dict[rpi.rpi] = existing_entries
56 | else:
57 | self.rpis_dict[rpi.rpi] = [rpi]
58 |
59 | # print('Recorded %d unique RPIs' % len(self.rpis_dict))
--------------------------------------------------------------------------------
/lib/rpis_in_db.py:
--------------------------------------------------------------------------------
1 | import struct
2 |
3 |
4 | class RPIinLevelDB:
5 | def __init__(self, db):
6 | self.rpis_dict = dict()
7 | for key, value in db:
8 | # each "key" entry has 18 bytes: 2 bytes "day" and 16 bytes "rpi"
9 | day, rpi = struct.unpack(">H16s", key)
10 | self.rpis_dict[rpi] = day
11 | # print(self.rpis_dict)
12 |
--------------------------------------------------------------------------------
/lib/scanned_rpis.py:
--------------------------------------------------------------------------------
1 | import csv
2 | from lib.conversions import *
3 |
4 |
5 | class RPIEntry:
6 | def __init__(self, start_time, end_time, rpi, aem, rssi, bdaddr, lat=None, lon=None, altitude=None, speed=None):
7 | self.start_time = start_time
8 | self.end_time = end_time
9 | self.rpi = rpi
10 | self.aem = aem
11 | self.rssi = rssi
12 | self.bdaddr = bdaddr
13 | self.lat = lat
14 | self.lon = lon
15 | self.altitude = altitude
16 | self.speed = speed
17 |
18 |
19 | class ScannedRPIs:
20 | def __init__(self, file_name):
21 | self.rpis_dict = dict()
22 | with open(file_name, newline='') as rpi_file:
23 | rpi_reader = csv.reader(rpi_file, delimiter=';')
24 | # StartTime, EndTime, RPI, AEM, MaxRSSI, BDADDR [, LAT, LON, Altitude, Speed]
25 | for row in rpi_reader:
26 | if row[0] == "StartTime":
27 | continue
28 | if len(row) == 6:
29 | rpi = RPIEntry(get_datetime_from_utc_timestamp(int(row[0])),
30 | get_datetime_from_utc_timestamp(int(row[1])),
31 | bytes.fromhex(row[2]), bytes.fromhex(row[3]),
32 | int(row[4]), row[5])
33 | elif len(row) == 10:
34 | rpi = RPIEntry(get_datetime_from_utc_timestamp(int(row[0])),
35 | get_datetime_from_utc_timestamp(int(row[1])),
36 | bytes.fromhex(row[2]), bytes.fromhex(row[3]),
37 | int(row[4]), row[5],
38 | lat=row[6], lon=row[7], altitude=row[8], speed=row[9])
39 | else:
40 | print("ERROR: %s must have only rows with 6 or 10 entries, found a row with %d entries" %
41 | (file_name, len(row)))
42 | exit(1)
43 | if rpi.rpi in self.rpis_dict:
44 | existing_entries = self.rpis_dict[rpi.rpi]
45 | existing_entries.append(rpi)
46 | self.rpis_dict[rpi.rpi] = existing_entries
47 | else:
48 | self.rpis_dict[rpi.rpi] = [rpi]
49 | # print(self.rpis_dict)
50 |
--------------------------------------------------------------------------------
/parse_keys.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | from lib.diagnosis_keys import *
4 | from lib.scanned_rpis import *
5 | from lib.ramble_rpis import *
6 | from lib.rpis_in_db import *
7 | from lib.conversions import *
8 | from lib.crypto import *
9 | import argparse
10 | import plyvel
11 | import struct
12 | import lib.contact_records_pb2
13 | from lib.diagnosis_key import DiagnosisKey
14 | from lib.count_users import count_users
15 |
16 | parser = argparse.ArgumentParser(description="Exposure Notification Diagnosis Key Parser.",
17 | formatter_class=argparse.ArgumentDefaultsHelpFormatter)
18 | parser.add_argument("-d", "--diagnosiskeys", type=str, default="testExport-2-records-1-of-1.zip",
19 | help="file name of the Diagnosis Keys .zip file")
20 | parser.add_argument("-c", "--contactrecords", type=str, default="",
21 | help="directory name of a contact record LevelDB (e.g. app_contact-tracing-contact-record-db/)")
22 | parser.add_argument("-r", "--rpis", type=str, default="",
23 | help="file name of a Scanned RPIs .csv file")
24 | parser.add_argument("--ramble_rpis", type=str, default="",
25 | help="file name of a RamBLE sqlite file")
26 | parser.add_argument("-s", "--short", action="store_true",
27 | help="show only one scan per match")
28 | parser.add_argument("-l", "--localtime", action="store_true",
29 | help="display timestamps in local time (otherwise the default is UTC)")
30 | parser.add_argument("-u", "--usercount", action="store_true",
31 | help="count the number of users who submitted Diagnosis Keys")
32 | parser.add_argument("-m", "--multiplier", type=int, default=1,
33 | help="padding multiplier (RANDOM_KEY_PADDING_MULTIPLIER as set on cwa-server)")
34 | parser.add_argument("-a", "--auto-multiplier", action="store_true",
35 | help="automatically detect the multiplier (range 1..10)")
36 | parser.add_argument("-n", "--new-android-apps-only", action="store_true",
37 | help="assume that no 'old' Android apps uploaded keys")
38 | args = parser.parse_args()
39 |
40 | dk_file_name = args.diagnosiskeys
41 | rpi_file_name = args.rpis
42 | ramble_file_name = args.ramble_rpis
43 | read_rpi_file = (rpi_file_name != "")
44 | read_ramble_file = (ramble_file_name != "")
45 | contactrecord_dir_name = args.contactrecords
46 | read_contact_record_db = (contactrecord_dir_name != "")
47 |
48 | print("Exposure Notification Diagnosis Key Parser")
49 | print("This script parses published Diagnosis Keys.\n")
50 | # see https://github.com/google/exposure-notifications-server/tree/master/examples/export
51 |
52 | dk = DiagnosisKeys(dk_file_name)
53 | print("File '%s' read." % dk_file_name)
54 |
55 | contactrecord_db = None
56 | if read_contact_record_db:
57 | contactrecord_db = plyvel.DB(contactrecord_dir_name)
58 | rpis_in_db = RPIinLevelDB(contactrecord_db)
59 |
60 | scanned_rpis = None
61 | if read_rpi_file:
62 | scanned_rpis = ScannedRPIs(rpi_file_name)
63 | print("File '%s' read." % rpi_file_name)
64 |
65 | ramble_rpis = None
66 | if read_ramble_file:
67 | ramble_rpis = RambleRPIs(ramble_file_name)
68 | print("File '%s' read." % ramble_file_name)
69 |
70 | start_timestamp = dk.get_upload_start_timestamp()
71 | end_timestamp = dk.get_upload_end_timestamp()
72 | if args.localtime:
73 | start_timestamp = get_local_datetime(start_timestamp)
74 | end_timestamp = get_local_datetime(end_timestamp)
75 | print("- Time window: %s - %s" % (get_string_from_datetime(start_timestamp),
76 | get_string_from_datetime(end_timestamp)))
77 | print("- Region: %s" % dk.get_region())
78 | print("- Batch: %d of %d" % (dk.get_batch_num(), dk.get_batch_size()))
79 | print("- # of keys in batch: %d" % len(dk.get_keys()))
80 |
81 | for signature_info in dk.get_signature_infos():
82 | print("- Signature Info:")
83 | print(signature_info)
84 |
85 | dk_list = []
86 |
87 | keys = None
88 | for i in [0, 1]:
89 | if i == 0:
90 | keys = dk.get_keys()
91 | print("Diagnosis Keys:")
92 | elif i == 1:
93 | keys = dk.get_revised_keys()
94 | print("\nRevised Diagnosis Keys:")
95 | if len(keys) == 0:
96 | print("(none)")
97 | i = 0
98 | for tek in keys:
99 | i += 1
100 | start_timestamp = get_datetime_from_utc_timestamp(get_timestamp_from_interval(tek.rolling_start_interval_number))
101 | end_timestamp = get_datetime_from_utc_timestamp(get_timestamp_from_interval(tek.rolling_start_interval_number+tek.rolling_period))
102 | if args.localtime:
103 | start_timestamp = get_local_datetime(start_timestamp)
104 | end_timestamp = get_local_datetime(end_timestamp)
105 | print("%3d: TEK: %s, Transmission Risk Level: %s, Validity: %s - %s (%d, %d)" %
106 | (i, tek.key_data.hex(), tek.transmission_risk_level,
107 | get_string_from_datetime(start_timestamp),
108 | get_string_from_datetime(end_timestamp),
109 | tek.rolling_start_interval_number, tek.rolling_period),
110 | end='')
111 | if tek.HasField("report_type"):
112 | field_types = ["UNKNOWN", "CONFIRMED_TEST", "CONFIRMED_CLINICAL_DIAGNOSIS",
113 | "SELF_REPORT", "RECURSIVE", "REVOKED"]
114 | print (", Report Type: %s" % field_types[tek.report_type], end='')
115 | if tek.HasField("days_since_onset_of_symptoms"):
116 | print (", Days since onset of symptoms: %d" % tek.days_since_onset_of_symptoms, end='')
117 | print()
118 |
119 | if read_contact_record_db:
120 | rpi_key = derive_rpi_key(tek.key_data)
121 | for diagnosis_rpi in create_list_of_rpis_for_interval_range(rpi_key, tek.rolling_start_interval_number,
122 | tek.rolling_period):
123 | if diagnosis_rpi in rpis_in_db.rpis_dict:
124 | print("FOUND MATCH!")
125 | aem_key = derive_aem_key(tek.key_data)
126 | interval = get_interval_number_from_rpi(diagnosis_rpi, rpi_key)
127 | interval_timestamp1 = get_datetime_from_utc_timestamp(get_timestamp_from_interval(interval))
128 | interval_timestamp2 = get_datetime_from_utc_timestamp(get_timestamp_from_interval(interval+1))
129 | if args.localtime:
130 | interval_timestamp1 = get_local_datetime(interval_timestamp1)
131 | interval_timestamp2 = get_local_datetime(interval_timestamp2)
132 | print("RPI Validity:", get_string_from_datetime(interval_timestamp1),
133 | "-", get_string_from_datetime(interval_timestamp2),
134 | "(Interval number: %d," % interval,
135 | "RPI: %s)" % diagnosis_rpi.hex())
136 |
137 | aem_key = derive_aem_key(tek.key_data)
138 | day = rpis_in_db.rpis_dict[diagnosis_rpi]
139 | # each "key" entry in the LevelDB has 18 bytes: 2 bytes "day" and 16 bytes "rpi"
140 | dbkey = struct.pack(">H16s", day, diagnosis_rpi)
141 | dbvalue = contactrecord_db.get(dbkey)
142 | # each "value" entry is a ProtocolBuffer-encoded message, length at least 1
143 | contact_records = lib.contact_records_pb2.ContactRecords()
144 | contact_records.ParseFromString(dbvalue)
145 | for scanrecord in contact_records.scanrecord:
146 | metadata = decrypt_aem(aem_key, scanrecord.aem, diagnosis_rpi)
147 | if metadata[0] >= 0x40:
148 | tx_power = struct.unpack_from("b", metadata, 1)[0] # signed char
149 | else:
150 | tx_power = 0
151 | print("--> WARNING: Expected metadata to start with at least 0x40, so this could be a false positive!")
152 |
153 | sr_timestamp = get_datetime_from_utc_timestamp(scanrecord.timestamp)
154 | if args.localtime:
155 | sr_timestamp = get_local_datetime(sr_timestamp)
156 | attenuation = tx_power-scanrecord.rssi
157 | print(get_string_from_datetime(sr_timestamp),
158 | "Attenuation: %ddB" % attenuation,
159 | "(RSSI: %ddBm, AEM: %s, Metadata: % s)" % (scanrecord.rssi, scanrecord.aem.hex(), metadata.hex()))
160 | if args.short:
161 | print("(...)")
162 | break
163 |
164 | if read_rpi_file:
165 | for diagnosis_rpi in create_list_of_rpis_for_interval_range(derive_rpi_key(tek.key_data),
166 | tek.rolling_start_interval_number, tek.rolling_period):
167 | if diagnosis_rpi in scanned_rpis.rpis_dict:
168 | print("FOUND MATCH!")
169 | aem_key = derive_aem_key(tek.key_data)
170 | scanned_rpi_entries = scanned_rpis.rpis_dict[diagnosis_rpi]
171 | for scanned_rpi_entry in scanned_rpi_entries:
172 | metadata = decrypt_aem(aem_key, scanned_rpi_entry.aem, diagnosis_rpi)
173 | print("Timeframe: %s - %s (%d seconds), RSSI: %d dBm, LAT, LON, altitude, speed: %s, %s, %s, %s" %
174 | (get_string_from_datetime(get_local_datetime(scanned_rpi_entry.start_time)),
175 | get_string_from_datetime(get_local_datetime(scanned_rpi_entry.end_time)),
176 | (scanned_rpi_entry.end_time-scanned_rpi_entry.start_time).total_seconds(),
177 | scanned_rpi_entry.rssi,
178 | scanned_rpi_entry.lat, scanned_rpi_entry.lon,
179 | scanned_rpi_entry.altitude, scanned_rpi_entry.speed))
180 | print("Decrypted metadata: %s " % metadata.hex(), end='')
181 | if metadata[0] == 0x40:
182 | tx_power = struct.unpack_from("b", metadata, 1)[0] # signed char
183 | print("--> TX Power: %d dBm --> RF attenuation: %d dB" %
184 | (tx_power, tx_power-scanned_rpi_entry.rssi), end='')
185 | else:
186 | print("--> WARNING: Expected metadata to start with 40, so this could be a false positive!")
187 | print()
188 | if args.short:
189 | print("(...)")
190 | break
191 |
192 | if read_ramble_file:
193 | for diagnosis_rpi in create_list_of_rpis_for_interval_range(derive_rpi_key(tek.key_data),
194 | tek.rolling_start_interval_number, tek.rolling_period):
195 | if diagnosis_rpi in ramble_rpis.rpis_dict:
196 | print("FOUND MATCH!")
197 | aem_key = derive_aem_key(tek.key_data)
198 | ramble_rpi_entries = ramble_rpis.rpis_dict[diagnosis_rpi]
199 | for ramble_rpi_entry in ramble_rpi_entries:
200 | metadata = decrypt_aem(aem_key, ramble_rpi_entry.aem, diagnosis_rpi)
201 | print("Timeframe: %s - %s (%d seconds), RSSI: %d dBm, LAT, LON, altitude, speed: %s, %s, %s, %s" %
202 | (get_string_from_datetime(get_local_datetime(ramble_rpi_entry.start_time)),
203 | get_string_from_datetime(get_local_datetime(ramble_rpi_entry.end_time)),
204 | (ramble_rpi_entry.end_time-ramble_rpi_entry.start_time).total_seconds(),
205 | ramble_rpi_entry.rssi,
206 | ramble_rpi_entry.lat, ramble_rpi_entry.lon,
207 | ramble_rpi_entry.altitude, ramble_rpi_entry.speed))
208 | print("Decrypted metadata: %s " % metadata.hex(), end='')
209 | if metadata[0] == 0x40:
210 | tx_power = struct.unpack_from("b", metadata, 1)[0] # signed char
211 | print("--> TX Power: %d dBm --> RF attenuation: %d dB" %
212 | (tx_power, tx_power-ramble_rpi_entry.rssi), end='')
213 | else:
214 | print("--> WARNING: Expected metadata to start with 40, so this could be a false positive!")
215 | print()
216 | if args.short:
217 | print("(...)")
218 | break
219 |
220 | if args.usercount:
221 | dk_list.append(DiagnosisKey(tek.key_data, tek.rolling_start_interval_number, tek.rolling_period, tek.transmission_risk_level))
222 |
223 | if read_contact_record_db:
224 | contactrecord_db.close()
225 |
226 | if args.usercount:
227 | count_users(dk_list, multiplier = args.multiplier, auto_multiplier_detect = args.auto_multiplier,
228 | new_android_apps_only = args.new_android_apps_only)
229 |
--------------------------------------------------------------------------------
/parse_keys_json.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | from lib.diagnosis_keys import *
3 | from lib.conversions import *
4 | import argparse
5 | import struct
6 | from lib.count_users import count_users
7 | import json
8 |
9 | parser = argparse.ArgumentParser(description="Exposure Notification Diagnosis Key Parser.", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
10 | parser.add_argument("-d", "--diagnosiskeys", type=str, default="testExport-2-records-1-of-1.zip", help="file name of the Diagnosis Keys .zip file")
11 | parser.add_argument("-l", "--localtime", action="store_true", help="display timestamps in local time (otherwise the default is UTC)")
12 | args = parser.parse_args()
13 |
14 | dk_file_name = args.diagnosiskeys
15 | dk = DiagnosisKeys(dk_file_name)
16 |
17 | json_obj = dict()
18 |
19 | start_timestamp = dk.get_upload_start_timestamp()
20 | end_timestamp = dk.get_upload_end_timestamp()
21 | if args.localtime:
22 | start_timestamp = get_local_datetime(start_timestamp)
23 | end_timestamp = get_local_datetime(end_timestamp)
24 |
25 | json_obj["timeWindowStart"] = get_string_from_datetime(start_timestamp)
26 | json_obj["timeWindowEnd"] = get_string_from_datetime(end_timestamp)
27 | json_obj["region"] = dk.get_region()
28 | json_obj["batchNum"] = dk.get_batch_num()
29 | json_obj["batchCount"] = dk.get_batch_size()
30 | json_obj["keyCount"] = len(dk.get_keys())
31 |
32 | json_obj["signatureInfos"] = dict()
33 | for signature_info in dk.get_signature_infos():
34 | for line in str(signature_info).split("\n"):
35 | line = line.strip()
36 | if line:
37 | json_obj["signatureInfos"][line.split(":")[0]] = line.split(":")[1].replace('"', "").strip()
38 |
39 | json_obj["diagnosisKeys"] = []
40 | i = 0
41 | for tek in dk.get_keys():
42 | i += 1
43 | start_timestamp = get_datetime_from_utc_timestamp(get_timestamp_from_interval(tek.rolling_start_interval_number))
44 | end_timestamp = get_datetime_from_utc_timestamp(get_timestamp_from_interval(tek.rolling_start_interval_number + tek.rolling_period))
45 | if args.localtime:
46 | start_timestamp = get_local_datetime(start_timestamp)
47 | end_timestamp = get_local_datetime(end_timestamp)
48 | key = dict()
49 | key["TemporaryExposureKey"] = tek.key_data.hex()
50 | key["transmissionRiskLevel"] = tek.transmission_risk_level
51 | key["validity"] = dict()
52 | key["validity"]["start"] = get_string_from_datetime(start_timestamp)
53 | key["validity"]["end"] = get_string_from_datetime(end_timestamp)
54 | key["validity"]["rollingStartIntervalNumber"] = tek.rolling_start_interval_number
55 | key["validity"]["rollingPeriod"] = tek.rolling_period
56 | json_obj["diagnosisKeys"].append(key)
57 |
58 | print(json.dumps(json_obj, indent=2))
59 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pycryptodome
2 | protobuf
3 | plyvel
4 |
--------------------------------------------------------------------------------