├── .gitignore ├── .project ├── .pydevproject ├── LICENSE ├── README.md ├── example └── TSE.py └── src ├── cli ├── config.py.example └── test.py └── lib ├── worm.py ├── wormentry.py ├── wormexception.py ├── worminfo.py ├── wormtransactionresponse.py └── wormtypes.py /.gitignore: -------------------------------------------------------------------------------- 1 | src/cli/__pycache__/ 2 | src/cli/config.py 3 | so/libWormAPI.so 4 | .pydevproject 5 | *.pyc 6 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | python-tse 4 | 5 | 6 | 7 | 8 | 9 | org.python.pydev.PyDevBuilder 10 | 11 | 12 | 13 | 14 | 15 | org.python.pydev.pythonNature 16 | 17 | 18 | -------------------------------------------------------------------------------- /.pydevproject: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Default 5 | 6 | python interpreter 7 | 8 | 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python-tse 2 | 3 | Gemäß KassenSicherungsVerordnung muss jede in Deutschland betriebene Bargeld-Registrierkasse ab 2020 mit einem Sicherheitsmodul "TSE" / "Technische Sicherheits-Einrichtung" ausgerüstet werden. Ein Hersteller dieser Geräte ist die schweizerische Firma Swissbit. 4 | 5 | Voraussetzung für die Nutzung dieses Moduls ist eine binäre Bibliothek, die mit der TSE kommuniziert. Die Weitergabe-Auflagen dieser Bibliothek sind restriktiv, daher ist diese Bibliothek nicht hier im Repository enthalten. Käufer der Entwickler-Version erhalten diese Daten vom Händler. 6 | 7 | Der Interne Name der TSE-Bibliothek ist **worm** ("write once, read many"), der aus Gründen der Kompatibilität beibehalten wird. 8 | 9 | Diese Python-Bibliothek kümmert sich um den Datenaustausch mit dem Modul. 10 | 11 | Im Programm **cli/test.py** befinden sich Anwendungsbeispiele für die Nutzung aller Funktionen. 12 | 13 | Zum Zugriff auf das TSE-Modul ist eine "Client-ID" nötig, die das Kassensystem identifiziert. Das kann ein beliebiger Freitext sein, also alphanumerisch. Intern wird dieser String als "latin1" codiert. Es wird dringend empfohlen, sich auf die einfachen ASCII-Zeichen zu beschränken. Das TSE-Modul kann mehrere Client-IDs verwalten und parallel betreiben, das ist in dieser Bibliothek aber nicht implementiert. 14 | 15 | Das Modul kennt 3 Zugangsdaten: Admin-PIN (5-stellig, für Aktivierung/Deaktivierung und ähnliches), Time-Admin-PIN (5-stelling, zum aktualisieren der Zeit) und Admin-PUK (6-stellig) um die anderen PINs wieder freizuschalten. Die Zeit muss regelmäßig (ca. alle halbe Stunde) neu gesetzt werden, daher muss diese PIN im Regelbetrieb zur Verfügung stehen. Die PINs können alphanumerisch sein aber es sollte sich konsequent um 1-Byte-Zeichen handeln, da die Länge der PINs in Bytes fest ist. 16 | 17 | 18 | Ein Ablauf könnte so aussehen: 19 | 20 | ## Nutzung der Bibliothek 21 | 22 | ```python 23 | import worm 24 | 25 | tse = worm.Worm(clientid="...", time_admin_pin="...") 26 | ``` 27 | 28 | Bei einem fabrikneuen Modul wird dann eine Warnung ausgegeben, dass das Modul noch nicht initialisiert ist. 29 | 30 | ``` 31 | ./src/lib/worm.py:54: Warning: TSE ist noch nicht initialisiert. Bitte zuerst initialisieren! 32 | warnings.warn(Warning('TSE ist noch nicht initialisiert. Bitte zuerst initialisieren!')) 33 | ``` 34 | 35 | 36 | ## Einmaliges Initialisieren der TSE 37 | 38 | Vor der allerersten Nutzung muss die TSE initialisiert werden. Ob dies nötig ist, zeigt die Status-Variable **initializationState**. 39 | 40 | ```python 41 | if tse.info.initializationState == worm.WORM_INIT_UNINITIALIZED: 42 | tse.tse_setup('SwissbitSwissbit', adminpuk=ADMIN_PUK, adminpin=ADMIN_PIN, timeadminpin=TIME_ADMIN_PIN) 43 | ``` 44 | 45 | Der erste Parameter "credentialseed" muss nach derzeitigen Informationen immer der feste String 'SwissbitSwissbit' sein. 46 | Die PINs und die PUK müssen alle vom Anwendungssystem bereitgestellt werden. Datentyp kann bytes oder string sein. 47 | Die Client-ID sollte bereits im Konstruktor übergeben worden sein und wird aus diesem verwendet. 48 | 49 | Die Swissbit-Bibliothek unterstützt einige Kommandos um die Initialisierung einzeln vorzunehmen. Diese sind hier nicht implementiert, da alles mit einem einzigen Aufruf von tse_setup() erledigt wird. 50 | 51 | 52 | ## Selbsttest und Zeit 53 | 54 | Nach einem Neustart und nach mehr als 24 Stunden Betrieb muss das TSE-Modul einen Selbsttest machen, zudm muss regelmäßig ca. alle halbe Stunde die Zeit gesetzt werden. Beides macht die Python-Bibliothek transparent bei Bedarf um Transaktionen zu ermöglichen. **HINWEIS:** Da der Selbsttest bis zu einer Minute dauern kann, ist es sinnvoll, den Selbsttest beim Start und danach täglich zu machen bevor eine Kunden-Transaktion eröffnet wird. Das Setzen der Zeit ist unerheblich und kann automatisch bei Bedarf erfolgen. 55 | 56 | ```python 57 | if not tse.info.hasPassedSelfTest: 58 | tse.tse_runSelfTest() 59 | if not tse.info.hasValidTime: 60 | tse.tse_updateTime() 61 | ``` 62 | 63 | ## Transaktionen 64 | 65 | Um Kassen-Transaktionen abzusichern muss eine Transaktion gestartet, beliebig oft aktualisiert und beendet werden. Die Aktualisierung kann ausbleiben wenn keine Änderungen mehr nötig sind. Start und Beenden ist obligatorisch. 66 | 67 | Bei diesen Operationen wird ein "response"-Objekt zurückgegeben, aus dem Status-Informationen ausgelesen werden können. Die Transaktionsnummer ist dabei besonders wichtig für die nachfolgenden Operationen. 68 | 69 | ```python 70 | response = myworm.transaction_start(processdata=b'', processtype='') 71 | num = response.transactionNumber 72 | response = myworm.transaction_update(num, processdata=b'...', processtype='Bestellung-V1') 73 | response = myworm.transaction_finish(num, processdata=b'...', processtype='Bestellung-V1') 74 | 75 | print(response.signatureCounter) 76 | print(response.logTime) 77 | print(base64_encode(response.signature)) 78 | ``` 79 | 80 | Hier wird eine Transaktion gestartet, einmal aktualisiert und danach abgeschlossen. Am Ende werden der Signatur-Zähler, die Signatur-Zeit und die Signatur ausgegeben. 81 | 82 | Die Parameter **processtype** und **processdata** sollten als Bytes-Objekte übergeben werden um Verfälschungen auszuschließen. Hilfsweise werden Strings via "latin1"-Codec codiert. 83 | 84 | **Hinweis zu den Inhalten**: Gemäß aktueller Richtlinien sollen processtype und processdata beim Start der Transaktion zunächst leer bleiben (Nur Absicherung des Zeitpunkts der ersten Aktion) und später mit Inhalten gefüllt werden. Die Bibliothek oder die TSE prüfen keinerlei Plausibilität der übergebenen Daten. 85 | 86 | 87 | ## Exceptions 88 | 89 | Wenn ein Fehler auftritt, wird dieser als "worm.WormException" geworfen und kann wie folgt behandelt werden. 90 | 91 | ```python 92 | try: 93 | tse.start_transaction(...) 94 | except worm.WormException as e: 95 | print(e.errno) 96 | print(e.message) 97 | ``` 98 | Für errno stehen die Konstanten aus der Entwickler-Doku zur Verfügung. 99 | 100 | 101 | ## TAR-Export 102 | 103 | Für Kassenprüfungen und zu Dokumentationszwecken muss der Bestand in der TSE immer wieder exportiert werden. Dafür stehen mehrere Routinen zur Verfügung: 104 | 105 | ```python 106 | tse.export_tar(filename='...') 107 | ``` 108 | Hier wird der gesamte Bestand als ein TAR-File exportiert. Es können Einschränkungen nach Datum oder Transaktionenummern festgelegt werden, Details sind im Code nachzuschauen. 109 | 110 | ```python 111 | (firstSignatureCounter, lastSignatureCounter, newState) = tse.export_tar_incremental(filename='...', lastState=None, callback=None) 112 | ``` 113 | Hier wird Status als "newState" ausgegeben, dieser kann beim nächsten Aufruf als "lastState" wieder übergeben werden um den Export ab der letzten Steller weiter zu führen. Der Status muss dabei vom Kassensystem zwischengespeichert werden um z.B. einen täglichen oder wöchentlichen inkrementellen Export zu machen. 114 | 115 | Der Parameter _callback_ kann eine Callback-Funktion sein, die ggf. einen Progress-Dialog oder ähnliches bedient. Die Funktion kann **False** zurück liefern, um den Export abzubrechen. 116 | 117 | 118 | ## Abrufen der Transaktionen 119 | 120 | FIXME: Wie das in der Praxis benutzt wird, weiß keiner... 121 | 122 | ```python 123 | e = tse.entry 124 | tse.entry.iterate_first() 125 | while e.isValid: 126 | print('Transaktion: #%i (%s)' % (e.id, e.type)) 127 | print(' ', e.readLogMessage()) 128 | print(' ', e.readProcessData()) 129 | tse.entry.iterate_next() 130 | ``` 131 | -------------------------------------------------------------------------------- /example/TSE.py: -------------------------------------------------------------------------------- 1 | # TSE Implementation Example 2 | # Copyright (C) 2020 Bernd Wurst 3 | # 4 | # This program is free software; you can redistribute it and/or 5 | # modify it under the terms of the GNU Lesser General Public 6 | # License as published by the Free Software Foundation; either 7 | # version 3 of the License, or (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | # Lesser General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU Lesser General Public License 15 | # along with this program; if not, write to the Free Software Foundation, 16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 17 | 18 | 19 | ####################################### 20 | # 21 | # Diese Datei stellt eine Klasse dar, die als Singleton Teil einer Anwendung sein kann. 22 | # Dabei wird die TSE-Biobliothek nur einmal instanziert und als neuer Thread gestartet 23 | # und bei weiterer Instanzierung wieder verwendet. 24 | # 25 | # Zudem wird bei Bedarf selbstständig der Selftest und das Setzen der Zeit vorgenommen. 26 | # 27 | ####################################### 28 | 29 | 30 | 31 | import os.path 32 | conf['library'] = os.path.join(os.path.dirname(__file__), '../src/lib') 33 | conf['clientid'] = 'MeineFirma' 34 | conf['timeadminpin'] = '98765' 35 | conf['adminpin'] = '12345' 36 | conf['adminpuk'] = '123456' 37 | 38 | from threading import Timer, Thread, Lock, Event 39 | import sys 40 | import time 41 | import logging 42 | sys.path.insert(0, conf['library']) 43 | import worm 44 | 45 | TSEException = worm.WormException 46 | log = logging.getLogger(__name__) 47 | 48 | class TSE(): 49 | _tse = None 50 | _thread = None 51 | _stop = None 52 | _lock = None 53 | 54 | def __init__(self): 55 | self.master = False 56 | if not self.__class__._tse: 57 | log.info('start new TSE controller thread!') 58 | self.__class__._tse = worm.Worm(clientid=conf['clientid'], time_admin_pin=conf['timeadminpin']) 59 | self.__class__._lock = Lock() 60 | self.__class__._stop = Event() 61 | self.__class__._thread = Thread(target=self.worker) 62 | self.__class__._thread.start() 63 | self.master = True 64 | 65 | def worker(self): 66 | log.debug('this is the new TSE worker thread!') 67 | while not self.__class__._stop.is_set(): 68 | log.debug('TSE: keep alive!') 69 | self.keepalive() 70 | try: 71 | timeout = 1500 72 | if not self.__class__._tse.info: 73 | # Wenn die TSE nicht da ist, alle Minute prüfen 74 | timeout = 60 75 | self.__class__._stop.wait(timeout) 76 | except TimeoutError: 77 | # 25 Minuten vorüber 78 | pass 79 | log.debug('TSE worker fertig.') 80 | 81 | def keepalive(self): 82 | with self.__class__._lock: 83 | try: 84 | if not self.__class__._tse or not self.__class__._tse.info: 85 | log.debug('TSE war nicht korrekt initialisiert') 86 | # TSE beim Start nicht vorhanden gewesen! 87 | self.__class__._tse = worm.Worm(clientid=conf['clientid'], time_admin_pin=conf['timeadminpin']) 88 | self.tse_prepare(adminpuk=conf['adminpuk'], adminpin=conf['adminpin']) 89 | if not self.info.hasPassedSelfTest or self.info.timeUntilNextSelfTest < 1500: 90 | log.debug('TSE-Selbsttest ist jetzt nötig') 91 | self.tse_runSelfTest() 92 | self.tse_updateTime() 93 | except TSEException as e: 94 | if e.errno == 2: # TSE nicht verfügbar 95 | log.info('Keine TSE vorhanden') 96 | pass 97 | elif e.errno == 0x1011: # client not registered 98 | log.info('Die TSE meldet, dass diese Client-ID bisher nicht registriert ist') 99 | self.tse_prepare(adminpuk=conf['adminpuk'], adminpin=conf['adminpin']) 100 | 101 | 102 | def __del__(self): 103 | if self.master: 104 | self.stop() 105 | else: 106 | log.debug('TSE: Beende nicht-master-objekt') 107 | 108 | def stop(self): 109 | log.debug('TSE: Signalisiere beenden') 110 | self.__class__._stop.set() 111 | 112 | 113 | def __getattr__(self, name): 114 | log.debug('TSE attribute fetched: %s' % (name,)) 115 | return getattr(self.__class__._tse, name) 116 | 117 | 118 | if __name__ == '__main__': 119 | tse = TSE() 120 | print('Signaturzähler: %s' % tse.info.createdSignatures) 121 | tse2 = TSE() 122 | print('Signaturzähler: %s' % tse2.info.createdSignatures) 123 | del(tse) 124 | del(tse2) -------------------------------------------------------------------------------- /src/cli/config.py.example: -------------------------------------------------------------------------------- 1 | PIN_TIME_ADMIN = '98765' 2 | PIN = '12345' 3 | PUK = '123456' 4 | 5 | clientId = 'SwissbitDemo' -------------------------------------------------------------------------------- /src/cli/test.py: -------------------------------------------------------------------------------- 1 | import config 2 | import sys 3 | import os.path 4 | from encodings.base64_codec import base64_encode 5 | import logging 6 | logging.getLogger('TSE-test') 7 | logging.basicConfig() 8 | 9 | sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'lib')) 10 | 11 | 12 | import worm 13 | 14 | TSE = worm.Worm(clientid=config.clientId, time_admin_pin=config.PIN_TIME_ADMIN) 15 | 16 | if len(sys.argv) > 1 and sys.argv[1] == '--info': 17 | print('Kapazität:', TSE.info.capacity) 18 | print('Development-Firmware? =>', TSE.info.isDevelopmentFirmware) 19 | print('Benutzter Speicher:', TSE.info.size) 20 | 21 | print('Gültige Zeit gesetzt? =>', TSE.info.hasValidTime) 22 | print('Selbsttest gemacht? =>', TSE.info.hasPassedSelfTest) 23 | print('Ist das CTSS-Interface aktiv? =>', TSE.info.isCtssInterfaceActive) 24 | print('Initialisierungs-Status:', TSE.info.initializationState) 25 | 26 | print('Transaktion läuft grade? =>', TSE.info.isDataImportInProgress) 27 | 28 | print('PUK schon gesetzt? =>', TSE.info.hasChangedPuk) 29 | print('Admin-PIN schon gesetzt? =>', TSE.info.hasChangedAdminPin) 30 | print('Time-Admin-PIN schon gesetzt? =>', TSE.info.hasChangedTimeAdminPin) 31 | 32 | print('Zeit bis zum nächsten Selbsttest:', TSE.info.timeUntilNextSelfTest) 33 | print('Zeit bis zum nächsten Time-Sync:', TSE.info.timeUntilNextTimeSynchronization) 34 | print('Zeit zwischen zwei Time-Syncs:', TSE.info.maxTimeSynchronizationDelay) 35 | print('Maximale Dauer einer offenen Transaktion:', TSE.info.maxUpdateDelay) 36 | 37 | print('Zahl der offenen Transaktionen: %i / %i' % (TSE.info.startedTransactions, TSE.info.maxStartedTransactions)) 38 | print('Zahl der bisherigen Signaturen: %i / %i (noch %i übrig)' % (TSE.info.createdSignatures, TSE.info.maxSignatures, TSE.info.remainingSignatures)) 39 | 40 | print('TSE-Beschreibung:', TSE.info.tseDescription, 'Customization:', TSE.info.customizationIdentifier.decode('ascii')) 41 | print('Signatur-Algorithmus:', TSE.signatureAlgorithm()) 42 | print('Pubkey:', base64_encode(TSE.info.tsePublicKey)) 43 | print('Serial:', bytes(TSE.info.tseSerialNumber).hex()) 44 | 45 | print('Zahl der aktiven Clients: %i / %i' % (TSE.info.registeredClients, TSE.info.maxRegisteredClients)) 46 | print('Zertifikat-Ablaufdatum:', TSE.info.certificateExpirationDate) 47 | 48 | print('Log-Time-Format:', TSE.logTimeFormat()) 49 | print('Hardware-Version: %i.%i.%i' % TSE.info.hardwareVersion) 50 | print('Software-Version: %i.%i.%i' % TSE.info.softwareVersion) 51 | print('Library-Version:', TSE.getVersion()) 52 | print('TSE Form-Factor:', TSE.info.formFactor) 53 | 54 | print('Health check:') 55 | status = TSE.flash_health_summary() 56 | for key, val in status.items(): 57 | print(f'{key}: {val}') 58 | 59 | if len(sys.argv) > 1 and sys.argv[1] == '--reset': 60 | TSE.tse_factoryReset() 61 | 62 | if len(sys.argv) > 1 and sys.argv[1] == '--prepare': 63 | TSE.tse_prepare(config.PUK, config.PIN) 64 | 65 | if len(sys.argv) > 1 and sys.argv[1] == '--selftest': 66 | TSE.tse_runSelfTest() 67 | 68 | if len(sys.argv) > 1 and sys.argv[1] == '--registerclient': 69 | TSE.user_login(worm.WORM_USER_ADMIN, config.PIN) 70 | TSE.tse_registerClient() 71 | 72 | if len(sys.argv) > 1 and sys.argv[1] == '--deregisterclient': 73 | TSE.user_login(worm.WORM_USER_ADMIN, config.PIN) 74 | TSE.tse_deregisterClient() 75 | 76 | if len(sys.argv) > 1 and sys.argv[1] == '--clients': 77 | TSE.user_login(worm.WORM_USER_ADMIN, config.PIN) 78 | clients = TSE.tse_listRegisteredClients() 79 | print('registrierte Clients:') 80 | for c in clients: 81 | print('- '+c) 82 | 83 | if len(sys.argv) > 1 and sys.argv[1] == '--setup': 84 | TSE.tse_setup(config.PUK, config.PIN, config.PIN_TIME_ADMIN) 85 | 86 | if len(sys.argv) > 1 and sys.argv[1] == '--time': 87 | TSE.tse_updateTime() 88 | 89 | if len(sys.argv) > 1 and sys.argv[1] == '--login': 90 | TSE.user_login(worm.WORM_USER_ADMIN, config.PIN) 91 | 92 | if len(sys.argv) > 1 and sys.argv[1] == '--initcreds': 93 | print(TSE.user_deriveInitialCredentials()) 94 | 95 | 96 | if len(sys.argv) > 1 and sys.argv[1] == '--trxstart': 97 | response = TSE.transaction_start('processdata', 'Bestellung-V1') 98 | num = response.transactionNumber 99 | print(num) 100 | print(response.signatureCounter) 101 | print(response.logTime) 102 | response = TSE.transaction_update(num, 'processdata2'.encode('ascii'), 'Bestellung-V1') 103 | print(response.signatureCounter) 104 | print(response.logTime) 105 | response = TSE.transaction_finish(num, 'processdata3'.encode('ascii'), 'Bestellung-V1') 106 | print(response.signatureCounter) 107 | print(response.logTime) 108 | print(base64_encode(response.signature)) 109 | 110 | 111 | if len(sys.argv) > 1 and sys.argv[1] == '--trxlist': 112 | trx = TSE.transaction_listStartedTransactions(0) 113 | print(trx) 114 | 115 | if len(sys.argv) > 1 and sys.argv[1] == '--trxfinishall': 116 | trx = TSE.transaction_listStartedTransactions(0) 117 | for t in trx: 118 | response = TSE.transaction_finish(t, ''.encode('ascii'), 'Bestellung-V1') 119 | 120 | if len(sys.argv) > 2 and sys.argv[1] == '--export-tar': 121 | TSE.export_tar(sys.argv[2]) 122 | 123 | if len(sys.argv) > 2 and sys.argv[1] == '--export-tar-inc': 124 | try: 125 | (firstSignatureCounter, lastSignatureCounter, newState) = TSE.export_tar_incremental(sys.argv[2]) 126 | print('newState:', bytes(newState).hex()) 127 | except worm.WormException as err: 128 | if err.errno == worm.WORM_ERROR_INCREMENTAL_EXPORT_INVALID_STATE: 129 | print('Die TSE-Einheit ist nicht bereit für einen Export!') 130 | else: 131 | print('Fehler beim Export: %s' % err.errno) 132 | 133 | if len(sys.argv) > 1 and sys.argv[1] == '--cert': 134 | print(TSE.getLogMessageCertificate().decode()) 135 | 136 | if len(sys.argv) > 1 and sys.argv[1] == '--listentries': 137 | e = TSE.entry 138 | TSE.entry.iterate_first() 139 | while e.isValid: 140 | print('Transaktion: #%i (%s)' % (e.id, e.type)) 141 | print(' ', e.readLogMessage()) 142 | print(' ', e.readProcessData()) 143 | TSE.entry.iterate_next() 144 | 145 | 146 | #print(TSE.runSelfTest()) # läuft (jetzt nicht mehr. Keine Ahnung wieso!!) 147 | 148 | #print(TSE.user_login()) 149 | #print(TSE.user_unblock()) 150 | #print(TSE.user_change_puk()) 151 | 152 | 153 | #print(TSE.info_capacity()) # läuft nicht (wahrscheinlich weil mywormInfo nicht korrekt definiert ist) 154 | 155 | #print(TSE.flash_health_summary()) # läuft nicht richtig 156 | 157 | 158 | 159 | 160 | -------------------------------------------------------------------------------- /src/lib/worm.py: -------------------------------------------------------------------------------- 1 | # TSE Connection Library 2 | # Copyright (C) 2020 Bernd Wurst 3 | # 4 | # This program is free software; you can redistribute it and/or 5 | # modify it under the terms of the GNU Lesser General Public 6 | # License as published by the Free Software Foundation; either 7 | # version 3 of the License, or (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | # Lesser General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU Lesser General Public License 15 | # along with this program; if not, write to the Free Software Foundation, 16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 17 | 18 | import os.path 19 | import datetime 20 | import logging 21 | import codecs 22 | from base64 import b64encode 23 | from ctypes import * 24 | from wormtypes import * 25 | from worminfo import Worm_Info 26 | from wormentry import Worm_Entry 27 | from wormtransactionresponse import Worm_Transaction_Response 28 | from wormexception import WormException, WormError_to_exception 29 | 30 | log = logging.getLogger('worm') 31 | 32 | def find_mountpoint(): 33 | # Lese alle gemounteten Laufwerke 34 | with open('/proc/mounts', 'r') as mounts: 35 | # iteriere über die Laufwerke 36 | for line in mounts.readlines(): 37 | dir = line.split(' ')[1] 38 | # Teste, ob die Datei vorhanden ist. Erster Treffer wird zurückgegeben. 39 | if os.path.exists(os.path.join(dir, 'TSE_COMM.DAT')): 40 | log.info('found TSE unit at %s' % (dir,)) 41 | return dir 42 | return None 43 | 44 | 45 | class Worm: 46 | wormlib = None 47 | 48 | def __init__(self, clientid, mountpoint = None, time_admin_pin = None, library = None, keepalive = None): 49 | self.qrcode_data = None 50 | log.setLevel(logging.DEBUG) 51 | self.time_admin_pin = time_admin_pin 52 | self.clientid = clientid 53 | self.entry = None 54 | self.mountpoint = mountpoint 55 | self.keepalive = keepalive 56 | self.export_callback = None 57 | if not library: 58 | library = os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(__file__)), '../../so/libWormAPI.so')) 59 | if not os.path.exists(library): 60 | log.critical('cannot find TSE / SMAERS library on this location: %s' % (library,)) 61 | raise WormException(WORM_ERROR_UNKNOWN, 'Cannot find TSE / SMAERS library. Was expected as %s' % library) 62 | log.debug('using TSE / SMAERS library at %s' % library) 63 | self.wormlib = cdll.LoadLibrary(library) 64 | self.ctx = WormContext() 65 | self.entry = Worm_Entry(self) 66 | self.info = None 67 | try: 68 | self.setup() 69 | except: 70 | log.error('TSE: Exception occured whilst initializing TSE. Possibly no module present?!') 71 | pass 72 | 73 | def setup(self, mountpoint = None, keepalive=None): 74 | # Hier können Laufzeitfehler auftreten, wenn die TSE nicht vorhanden ist! 75 | if not mountpoint: 76 | mountpoint = self.mountpoint 77 | if not mountpoint: 78 | mountpoint = find_mountpoint() 79 | if not mountpoint: 80 | log.error('cannot find TSE unit on any mount path') 81 | raise WormException(WORM_ERROR_NO_WORM_CARD, 'Cannot find TSE unit!') 82 | 83 | self.wormlib.worm_init.restype = WormError 84 | self.wormlib.worm_init.argtypes = (POINTER(WormContext), c_char_p) 85 | log.debug('call worm_init()') 86 | ret = self.wormlib.worm_init(byref(self.ctx), mountpoint.encode('utf-8')) 87 | WormError_to_exception(ret) 88 | 89 | # Configure keepalive. Default of SDK is keepalive interval of 1 Second, likely unnecessary on linux. 90 | # So we default to no have any keepalive as it was before 91 | try: 92 | if keepalive and int(keepalive) > 0: 93 | self.keepalive_configure(keepalive) 94 | elif keepalive is False or keepalive == 0: 95 | self.keepalive_disable() 96 | elif self.keepalive and int(self.keepalive) > 0: 97 | self.keepalive_configure(self.keepalive) 98 | else: 99 | self.keepalive_disable() 100 | except ValueError: 101 | log.critical(f'could not understand keepalive argument {str(self.keepalive)}, disabling keepalive') 102 | self.keepalive_disable() 103 | 104 | self.info = Worm_Info(self) 105 | 106 | if self.info.initializationState == WORM_INIT_DECOMMISSIONED: 107 | log.critical('this TSE unit is out of order / decommissioned permanently!') 108 | raise WormException(WORM_ERROR_TSE_DECOMMISSIONED, 'TSE ist unwiderruflich außer Betrieb gesetzt und kann nicht mehr benutzt werden!') 109 | elif self.info.initializationState == WORM_INIT_UNINITIALIZED: 110 | log.warning('this TSE module is not yet set up! Please initialize!') 111 | import warnings 112 | warnings.warn(Warning('TSE ist noch nicht initialisiert. Bitte zuerst initialisieren!')) 113 | 114 | 115 | def __del__(self): 116 | log.debug('TSE library is about to be shut down') 117 | if self.info: 118 | del(self.info) 119 | if self.wormlib: 120 | self.wormlib.worm_cleanup.restype = WormError 121 | ret = self.wormlib.worm_cleanup(self.ctx) 122 | WormError_to_exception(ret) 123 | 124 | def keepalive_configure(self, intervalInSeconds : int): 125 | # Intervall muss zwischen 1 und 3600 sein. 126 | assert 1 <= intervalInSeconds <= 3600, 'keepalive interval must be in range from 1 to 3600' 127 | self.wormlib.worm_keepalive_configure.argtypes = (WormContext, c_int) 128 | self.wormlib.worm_keepalive_configure.restype = WormError 129 | ret = self.wormlib.worm_keepalive_configure(self.ctx, intervalInSeconds) 130 | WormError_to_exception(ret) 131 | return ret 132 | 133 | def keepalive_disable(self): 134 | self.wormlib.worm_keepalive_disable.argtypes = (WormContext,) 135 | self.wormlib.worm_keepalive_disable.restype = WormError 136 | ret = self.wormlib.worm_keepalive_disable(self.ctx) 137 | WormError_to_exception(ret) 138 | return ret 139 | 140 | #################################################################### 141 | # Library Information 142 | #################################################################### 143 | 144 | def getVersion(self): 145 | self.wormlib.worm_getVersion.restype = c_char_p 146 | ret = self.wormlib.worm_getVersion() 147 | # liefert bytes. Wir konvertieren als latin1, da es da keine UnicodeDecodeErrors geben kann. 148 | return ret.decode('latin1') 149 | 150 | def logTimeFormat(self): 151 | self.wormlib.worm_logTimeFormat.restype = c_char_p 152 | ret = self.wormlib.worm_logTimeFormat() 153 | return ret.decode('latin1') 154 | 155 | 156 | def signatureAlgorithm(self): 157 | self.wormlib.worm_signatureAlgorithm.restype = c_char_p 158 | ret = self.wormlib.worm_signatureAlgorithm() 159 | return ret.decode('latin1') 160 | 161 | #################################################################### 162 | # TSE-Configuration 163 | #################################################################### 164 | 165 | def tse_factoryReset(self): 166 | self.wormlib.worm_tse_factoryReset.restype = WormError 167 | self.wormlib.worm_tse_factoryReset.argtypes = (WormContext, ) 168 | ret = self.wormlib.worm_tse_factoryReset(self.ctx) 169 | WormError_to_exception(ret) 170 | self.info.update() 171 | return ret 172 | 173 | def tse_prepare(self, adminpuk, adminpin, time_admin_pin = None): 174 | '''Kann beim Programmstart aufgerufen werden und kümmert sich um 175 | tse_setup() bei Bedarf oder richtet die clientid ein''' 176 | if not time_admin_pin: 177 | time_admin_pin = self.time_admin_pin 178 | if not self.info: 179 | log.info('not yet initialized.') 180 | self.setup() 181 | if self.info.initializationState == WORM_INIT_UNINITIALIZED: 182 | log.warning('TSE still not commissioned, calling tse_setup()') 183 | self.tse_setup(adminpuk, adminpin, time_admin_pin) 184 | self.tse_updateTime() 185 | if not self.info.hasPassedSelfTest: 186 | try: 187 | log.info('running selfTest()') 188 | self.tse_runSelfTest() 189 | except WormException as e: 190 | if e.errno == WORM_ERROR_CLIENT_NOT_REGISTERED: 191 | log.info('client not registered, calling registerClient()') 192 | self.user_login(WORM_USER_ADMIN, adminpin) 193 | self.tse_registerClient(adminpin = adminpin) 194 | self.user_logout(WORM_USER_ADMIN) 195 | # self-test nochmal ausführen. Schlägt dieser nochmal fehl, wird die exception durchgereicht. 196 | self.tse_runSelfTest() 197 | if not self.info.hasValidTime: 198 | self.tse_updateTime() 199 | 200 | 201 | def tse_setup(self, adminpuk, adminpin, timeadminpin): 202 | if self.info.initializationState == WORM_INIT_INITIALIZED: 203 | raise WormException(WORM_ERROR_UNKNOWN, 'initialization ist schon erfolgt!') 204 | # Es muss mindestens ein SelfTest gemacht werden vor dem setup. 205 | try: 206 | self.tse_runSelfTest() 207 | except WormException: 208 | # Dieser Self-Test schlägt fehl, das ist by design. 209 | pass 210 | credentialseed = b'SwissbitSwissbit' 211 | if type(adminpuk) == str: 212 | adminpuk = adminpuk.encode('latin1') 213 | if len(adminpuk) != 6: 214 | raise ValueError('Admin-PUK muss genau 6 Stellen lang sein') 215 | if type(adminpin) == str: 216 | adminpin = adminpin.encode('latin1') 217 | if len(adminpin) != 5: 218 | raise ValueError('Admin-PIN muss genau 5 Stellen lang sein') 219 | if type(timeadminpin) == str: 220 | timeadminpin = timeadminpin.encode('latin1') 221 | if len(timeadminpin) != 5: 222 | raise ValueError('Time-Admin-PIN muss genau 5 Stellen lang sein') 223 | self.wormlib.worm_tse_setup.restype = WormError 224 | self.wormlib.worm_tse_setup.argtypes = (WormContext, c_char_p, c_int, c_char_p, c_int, c_char_p, c_int, c_char_p, c_int, c_char_p) 225 | ret = self.wormlib.worm_tse_setup(self.ctx, credentialseed, len(credentialseed), 226 | adminpuk, len(adminpuk), adminpin, len(adminpin), timeadminpin, len(timeadminpin), 227 | self.clientid.encode('latin1')) 228 | WormError_to_exception(ret) 229 | self.info.update() 230 | return ret 231 | 232 | 233 | def tse_runSelfTest(self): 234 | self.wormlib.worm_tse_runSelfTest.argtypes = (WormContext, c_char_p) 235 | self.wormlib.worm_tse_runSelfTest.restype = WormError 236 | ret = self.wormlib.worm_tse_runSelfTest(self.ctx, self.clientid.encode('latin1')) 237 | WormError_to_exception(ret) 238 | self.info.update() 239 | return ret 240 | 241 | def tse_updateTime(self): 242 | if self.time_admin_pin: 243 | self.user_login(WORM_USER_TIME_ADMIN, self.time_admin_pin) 244 | self.wormlib.worm_tse_updateTime.argtypes = (WormContext, worm_uint) 245 | self.wormlib.worm_tse_updateTime.restype = WormError 246 | ret = self.wormlib.worm_tse_updateTime(self.ctx, int(datetime.datetime.now().timestamp())) 247 | WormError_to_exception(ret) 248 | self.info.update() 249 | return ret 250 | 251 | def tse_listRegisteredClients(self): 252 | skip = 0 253 | clients = [] 254 | while True: 255 | _clients = WormRegisteredClients() 256 | self.wormlib.worm_tse_listRegisteredClients.argtypes = (WormContext, c_int, POINTER(WormRegisteredClients)) 257 | ret = self.wormlib.worm_tse_listRegisteredClients(self.ctx, skip, _clients) 258 | WormError_to_exception(ret) 259 | data = False 260 | for entry in _clients.clientIds: 261 | id = cast(entry, c_char_p).value.decode('latin1') 262 | if id: 263 | clients.append(id) 264 | data = True 265 | if len(clients) >= _clients.amount or not data: 266 | break 267 | skip += 16 268 | return clients 269 | 270 | def tse_registerClient(self, clientid = None, adminpin = None): 271 | if not clientid: 272 | clientid = self.clientid 273 | if adminpin: 274 | self.user_login(WORM_USER_ADMIN, adminpin) 275 | self.wormlib.worm_tse_registerClient.argtypes = (WormContext, c_char_p) 276 | ret = self.wormlib.worm_tse_registerClient(self.ctx, clientid.encode('latin1')) 277 | WormError_to_exception(ret) 278 | 279 | def tse_deregisterClient(self, clientid = None): 280 | if not clientid: 281 | clientid = self.clientid 282 | self.wormlib.worm_tse_deregisterClient.argtypes = (WormContext, c_char_p) 283 | ret = self.wormlib.worm_tse_deregisterClient(self.ctx, clientid.encode('latin1')) 284 | WormError_to_exception(ret) 285 | 286 | def user_login(self, userid, pin): 287 | pin = pin.encode('latin1') 288 | remainingRetries = c_int() 289 | 290 | self.wormlib.worm_user_login.argtypes = (WormContext, c_int, c_char_p, c_int, POINTER(c_int)) 291 | self.wormlib.worm_user_login.restype = WormError 292 | ret = self.wormlib.worm_user_login(self.ctx, userid, pin, len(pin), byref(remainingRetries)) 293 | WormError_to_exception(ret) 294 | self.info.update() 295 | return remainingRetries.value 296 | 297 | def user_logout(self, userid): 298 | self.wormlib.worm_user_logout.argtypes = (WormContext, c_int) 299 | self.wormlib.worm_user_logout.restype = WormError 300 | ret = self.wormlib.worm_user_logout(self.ctx, userid) 301 | WormError_to_exception(ret) 302 | self.info.update() 303 | 304 | def user_deriveInitialCredentials(self): 305 | seed = b'SwissbitSwissbit' 306 | adminpuk = c_char_p(b'xxxxxx') 307 | adminpin = c_char_p(b'xxxxx') 308 | timeadminpin = c_char_p(b'xxxxx') 309 | self.wormlib.worm_user_deriveInitialCredentials.argtypes = (WormContext, c_char_p, c_int, c_char_p, c_int, c_char_p, c_int, c_char_p, c_int) 310 | self.wormlib.worm_user_deriveInitialCredentials.restype = WormError 311 | ret = self.wormlib.worm_user_deriveInitialCredentials(self.ctx, seed, len(seed), adminpuk, 6, adminpin, 5, timeadminpin, 5) 312 | WormError_to_exception(ret) 313 | print('adminPUK:', adminpuk.value.decode('latin1')) 314 | print('adminPIN:', adminpin.value.decode('latin1')) 315 | print('timeadminPIN:', timeadminpin.value.decode('latin1')) 316 | return (adminpuk.value.decode('latin1'), adminpin.value.decode('latin1'), timeadminpin.value.decode('latin1')) 317 | 318 | 319 | #################################################################### 320 | # Transactions 321 | #################################################################### 322 | 323 | def __pre_transaction_checks(self): 324 | if not self.info: 325 | raise WormException(WORM_ERROR_NO_WORM_CARD, 'No TSE available') 326 | self.info.update() 327 | if not self.info.hasPassedSelfTest: 328 | self.tse_runSelfTest() 329 | if not self.info.hasValidTime: 330 | self.tse_updateTime() 331 | if not self.info.isCtssInterfaceActive: 332 | raise WormException(WORM_ERROR_WRONG_STATE_NEEDS_ACTIVE_CTSS, 'TSE not ready!') 333 | 334 | 335 | def transaction_start(self, processdata, processtype): 336 | self.__pre_transaction_checks() 337 | if type(processdata) == str: 338 | processdata = processdata.encode('utf-8') 339 | if type(processtype) == str: 340 | processtype = processtype.encode('utf-8') 341 | assert type(processdata) == bytes, 'processdata ist kein byte-string' 342 | assert type(processtype) == bytes, 'processtype ist kein byte-string' 343 | r = Worm_Transaction_Response(self) 344 | self.wormlib.worm_transaction_start.argtypes = (WormContext, c_char_p, c_char_p, c_int64, c_char_p, WormTransactionResponse) 345 | self.wormlib.worm_transaction_start.restype = WormError 346 | ret = self.wormlib.worm_transaction_start(self.ctx, self.clientid.encode('latin1'), processdata, 347 | len(processdata), processtype, r.response) 348 | WormError_to_exception(ret) 349 | self.transaction_start_time = r.logTime 350 | return r 351 | 352 | 353 | def transaction_update(self, transactionnumber, processdata, processtype): 354 | self.__pre_transaction_checks() 355 | if type(processdata) == str: 356 | processdata = processdata.encode('utf-8') 357 | if type(processtype) == str: 358 | processtype = processtype.encode('utf-8') 359 | assert type(processdata) == bytes, 'processdata ist kein byte-string' 360 | assert type(processtype) == bytes, 'processtype ist kein byte-string' 361 | r = Worm_Transaction_Response(self) 362 | self.wormlib.worm_transaction_update.argtypes = (WormContext, c_char_p, worm_uint, c_char_p, worm_uint, c_char_p, WormTransactionResponse) 363 | self.wormlib.worm_transaction_update.restype = WormError 364 | ret = self.wormlib.worm_transaction_update(self.ctx, self.clientid.encode('latin1'), transactionnumber, processdata, 365 | len(processdata), processtype, r.response) 366 | WormError_to_exception(ret) 367 | return r 368 | 369 | def transaction_finish(self, transactionnumber, processdata, processtype): 370 | self.__pre_transaction_checks() 371 | if type(processdata) == str: 372 | processdata = processdata.encode('utf-8') 373 | if type(processtype) == str: 374 | processtype = processtype.encode('utf-8') 375 | assert type(processdata) == bytes, 'processdata ist kein byte-string' 376 | assert type(processtype) == bytes, 'processtype ist kein byte-string' 377 | r = Worm_Transaction_Response(self) 378 | self.wormlib.worm_transaction_finish.argtypes = (WormContext, c_char_p, worm_uint, c_char_p, worm_uint, c_char_p, WormTransactionResponse) 379 | self.wormlib.worm_transaction_finish.restype = WormError 380 | ret = self.wormlib.worm_transaction_finish(self.ctx, self.clientid.encode('latin1'), transactionnumber, processdata, 381 | len(processdata), processtype, r.response) 382 | WormError_to_exception(ret) 383 | self.info.update() 384 | 385 | # get qr code information 386 | qrcode = ['V0',] 387 | qrcode.append(self.clientid) 388 | qrcode.append(processtype.decode('utf-8')) 389 | qrcode.append(processdata.decode('utf-8')) 390 | qrcode.append(r.transactionNumber) 391 | qrcode.append(r.signatureCounter) 392 | qrcode.append(self.transaction_start_time.astimezone(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.000Z')) 393 | qrcode.append(r.logTime.astimezone(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.000Z')) 394 | qrcode.append(self.signatureAlgorithm()) 395 | qrcode.append('unixTime') 396 | qrcode.append(b64encode(r.signature).decode('ascii').strip()) 397 | qrcode.append(b64encode(self.info.tsePublicKey).decode('ascii').strip()) 398 | self.qrcode_data = ';'.join([str(x) for x in qrcode]) 399 | 400 | return r 401 | 402 | def transaction_listStartedTransactions(self, skip=0): 403 | self.__pre_transaction_checks() 404 | numbers_buffer = (worm_uint * 62)() 405 | count = c_int() 406 | self.wormlib.worm_transaction_listStartedTransactions.argtypes = (WormContext, c_char_p, c_uint, worm_uint * 62, c_int, POINTER(c_int)) 407 | self.wormlib.worm_transaction_listStartedTransactions.restype = WormError 408 | ret = self.wormlib.worm_transaction_listStartedTransactions(self.ctx, self.clientid.encode('latin1'), skip, numbers_buffer, 62, byref(count)) 409 | WormError_to_exception(ret) 410 | return numbers_buffer[:count.value] 411 | 412 | 413 | #################################################################### 414 | # Export 415 | #################################################################### 416 | 417 | def getLogMessageCertificate(self): 418 | s = c_char_p() 419 | sLength = c_uint32() 420 | # First call with NULL buffer to get the needed size 421 | self.wormlib.worm_getLogMessageCertificate.argtypes = (WormContext, POINTER(c_char_p), POINTER(c_uint32)) 422 | res = self.wormlib.worm_getLogMessageCertificate(self.ctx, None, byref(sLength)) 423 | WormError_to_exception(res) 424 | 425 | # initialize buffer to the correct length 426 | buffer = pointer((c_char * sLength.value)()) 427 | self.wormlib.worm_getLogMessageCertificate.argtypes = (WormContext, POINTER(c_char * sLength.value), POINTER(c_uint32)) 428 | res = self.wormlib.worm_getLogMessageCertificate(self.ctx, buffer, byref(sLength)) 429 | WormError_to_exception(res) 430 | s = cast(buffer, POINTER(c_char)) 431 | ret = string_at(s, size=sLength.value) 432 | return ret 433 | 434 | def export_tar(self, filename, clientid=None, time_start=None, time_end=None, trxid_start=None, trxid_end=None): 435 | CALLBACK = CFUNCTYPE(c_int, POINTER(c_char), c_uint, c_void_p) 436 | callback = CALLBACK(self.export_tar_callback) 437 | with open(filename, 'wb') as self.tarfile: 438 | if time_start: 439 | if type(time_start) == datetime.datetime: 440 | time_start = int(time_start.timestamp()) 441 | time_end = int(time_start.timestamp()) 442 | assert type(time_start) == int 443 | assert type(time_end) == int 444 | ret = self.wormlib.worm_export_tar_filtered_time(self.ctx, worm_uint(time_start), worm_uint(time_end), c_char_p(clientid), callback, None) 445 | WormError_to_exception(ret) 446 | elif trxid_start: 447 | assert type(trxid_start) == int 448 | assert type(trxid_end) == int 449 | ret = self.wormlib.worm_export_tar_filtered_transaction(self.ctx, worm_uint(trxid_start), worm_uint(trxid_end), c_char_p(clientid), callback, None) 450 | WormError_to_exception(ret) 451 | else: 452 | ret = self.wormlib.worm_export_tar(self.ctx, callback, None) 453 | WormError_to_exception(ret) 454 | 455 | 456 | def export_tar_incremental(self, filename, lastState=None, callback=None): 457 | (firstSignatureCounter, lastSignatureCounter, return_state, allDataExported) = self.export_tar_incremental_ex(filename, lastState=lastState, maxExportSize=0, callback=callback) 458 | return (firstSignatureCounter, lastSignatureCounter, return_state) 459 | 460 | def export_tar_incremental_ex(self, filename, lastState=None, maxExportSize=0, callback=None): 461 | '''inkrementeller export 462 | returns (firstSignatureCounter, lastSignatureCounter, newState, allDataExported) 463 | newState muss beim nächsten inkrementellen export als lastState übergeben werden. 464 | callback kann eine callback-Funktion sein, die als argumente processedBlocks und totalBlocks erhält. 465 | Gibt die Callback-Funktion False zurück, wird abgebrochen.''' 466 | self.export_callback = callback 467 | CALLBACK = CFUNCTYPE(c_int, POINTER(c_char), c_uint, c_uint32, c_uint32, c_void_p) 468 | callback = CALLBACK(self.export_tar_incremental_callback) 469 | with open(filename, 'wb') as self.tarfile: 470 | firstSignatureCounter = c_uint64() 471 | lastSignatureCounter = c_uint64() 472 | last_state = None 473 | last_state_len = 0 474 | if lastState: 475 | last_state = c_char_p(lastState) 476 | last_state_len = c_int(len(lastState)) 477 | new_state = cast(create_string_buffer(WORM_EXPORT_TAR_INCREMENTAL_STATE_SIZE), c_char_p) 478 | new_state_len = c_int(WORM_EXPORT_TAR_INCREMENTAL_STATE_SIZE) 479 | maxExportSize = c_uint64(maxExportSize) 480 | allDataExported = c_int64() 481 | ret = self.wormlib.worm_export_tar_incremental_ex(self.ctx, last_state, last_state_len, new_state, new_state_len, maxExportSize, byref(allDataExported), byref(firstSignatureCounter), byref(lastSignatureCounter), callback, None) 482 | WormError_to_exception(ret) 483 | new_state = cast(new_state, POINTER(c_char)) 484 | return_state = string_at(new_state, new_state_len) 485 | self.export_callback = None 486 | return (firstSignatureCounter.value, lastSignatureCounter.value, return_state, bool(allDataExported)) 487 | 488 | def export_tar_callback(self, chunk, chunklen, data): 489 | chunk = cast(chunk, POINTER(c_char)) 490 | if not self.tarfile: 491 | # Sollte schon vorhanden sein, sonst Fehler 492 | return 1 493 | self.tarfile.write(string_at(chunk, chunklen)) 494 | return 0 495 | 496 | def export_tar_incremental_callback(self, chunk, chunklen, processedBlocks, totalBlocks, data): 497 | chunk = cast(chunk, POINTER(c_char)) 498 | if not self.tarfile: 499 | # Sollte schon vorhanden sein, sonst Fehler 500 | return 1 501 | self.tarfile.write(string_at(chunk, chunklen)) 502 | log.info('exported %i / %i blocks' % (processedBlocks, totalBlocks)) 503 | if self.export_callback: 504 | if not self.export_callback(processedBlocks, totalBlocks): 505 | return 1 506 | return 0 507 | 508 | def export_tar_incremental_sizeInSectors(self, lastState=None): 509 | '''calculates size of an incremental export in sectors''' 510 | last_state = None 511 | last_state_len = 0 512 | if lastState: 513 | last_state = c_char_p(lastState) 514 | last_state_len = c_int(len(lastState)) 515 | size = c_uint64() 516 | ret = self.wormlib.worm_export_tar_incremental_sizeInSectors(self.ctx, last_state, last_state_len, byref(size)) 517 | WormError_to_exception(ret) 518 | return size.value 519 | 520 | def export_tar_incremental_size(self, lastState=None): 521 | '''calculates size of an incremental export in bytes''' 522 | last_state = None 523 | last_state_len = 0 524 | if lastState: 525 | last_state = c_char_p(lastState) 526 | last_state_len = c_int(len(lastState)) 527 | size = c_uint64() 528 | ret = self.wormlib.worm_export_tar_incremental_size(self.ctx, last_state, last_state_len, byref(size)) 529 | WormError_to_exception(ret) 530 | return size.value 531 | 532 | 533 | #################################################################### 534 | # disfunctional 535 | #################################################################### 536 | 537 | 538 | def user_unblock(self): 539 | WormUserId = WORM_USER_TIME_ADMIN 540 | puk = c_wchar_p(config.PUK) 541 | pukLength = 6 542 | newPin = c_wchar_p(config.PIN_TIME_ADMIN) 543 | newPinLength = 5 544 | remainingRetries = c_int() 545 | 546 | self.wormlib.worm_user_unblock.argtypes = (WormContext, c_int, c_wchar_p, c_int, c_wchar_p, c_int, POINTER(c_int)) 547 | self.wormlib.worm_user_unblock.restype = WormError 548 | ret = self.wormlib.worm_user_unblock(self.ctx, WormUserId, puk, pukLength, newPin, newPinLength, remainingRetries) 549 | 550 | print('remainingRetries: ', remainingRetries.value) 551 | print(ret) 552 | return ret 553 | 554 | 555 | # FIXME: Diese Funktion gibt nichts zurück 556 | def flash_health_summary(self): 557 | uncorrectableEccErrors = c_uint32() 558 | percentageRemainingSpareBlocks = c_uint8() 559 | percentageRemainingEraseCounts = c_uint8() 560 | percentageRemainingTenYearsDataRetention = c_uint8() 561 | 562 | self.wormlib.worm_flash_health_summary.argtypes = (WormContext, POINTER(c_uint32), POINTER(c_uint8), POINTER(c_uint8), POINTER(c_uint8)) 563 | self.wormlib.worm_flash_health_summary.restype = WormError 564 | ret = self.wormlib.worm_flash_health_summary(self.ctx, byref(uncorrectableEccErrors), byref(percentageRemainingSpareBlocks), 565 | byref(percentageRemainingEraseCounts), byref(percentageRemainingTenYearsDataRetention)) 566 | 567 | return { 568 | "status": ret, 569 | "uncorrectableEccErrors": uncorrectableEccErrors.value, 570 | "percentageRemainingSpareBlocks": percentageRemainingSpareBlocks.value, 571 | "percentageRemainingEraseCounts": percentageRemainingEraseCounts.value, 572 | "percentageRemainingTenYearsDataRetention": percentageRemainingTenYearsDataRetention.value, 573 | } 574 | -------------------------------------------------------------------------------- /src/lib/wormentry.py: -------------------------------------------------------------------------------- 1 | # TSE Connection Library 2 | # Copyright (C) 2020 Bernd Wurst 3 | # 4 | # This program is free software; you can redistribute it and/or 5 | # modify it under the terms of the GNU Lesser General Public 6 | # License as published by the Free Software Foundation; either 7 | # version 3 of the License, or (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | # Lesser General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU Lesser General Public License 15 | # along with this program; if not, write to the Free Software Foundation, 16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 17 | 18 | import datetime 19 | from ctypes import * 20 | from wormtypes import * 21 | 22 | 23 | class Worm_Entry: 24 | def __init__(self, worm): 25 | self.ctx = worm.ctx 26 | self.wormlib = worm.wormlib 27 | 28 | self.wormlib.worm_entry_new.argtypes = (WormContext,) 29 | self.wormlib.worm_entry_new.restype = WormEntry 30 | self.entry = cast(self.wormlib.worm_entry_new(self.ctx), WormEntry) 31 | 32 | 33 | def __del__(self): 34 | if self.entry: 35 | self.wormlib.worm_entry_free(self.entry) 36 | self.entry = None 37 | 38 | def __getattr__(self, key): 39 | if key in ['isValid',]: 40 | return bool(self.__get_info_uint(key)) 41 | elif key in ['id', ]: 42 | return self.__get_info_uint32(key) 43 | elif key in ['logMessageLength', 'processDataLength', 'type']: 44 | return self.__get_info_uint64(key) 45 | else: 46 | raise AttributeError('unimplemented: %s' % key) 47 | 48 | 49 | def __get_info_uint(self, key): 50 | getattr(self.wormlib, 'worm_entry_'+key).restype = c_uint 51 | getattr(self.wormlib, 'worm_entry_'+key).argtypes = (WormEntry,) 52 | ret = getattr(self.wormlib, 'worm_entry_'+key)(self.entry) 53 | return ret 54 | 55 | 56 | def __get_info_uint32(self, key): 57 | getattr(self.wormlib, 'worm_entry_'+key).restype = c_uint32 58 | getattr(self.wormlib, 'worm_entry_'+key).argtypes = (WormEntry,) 59 | ret = getattr(self.wormlib, 'worm_entry_'+key)(self.entry) 60 | return ret 61 | 62 | 63 | def __get_info_uint64(self, key): 64 | getattr(self.wormlib, 'worm_entry_'+key).restype = c_uint64 65 | getattr(self.wormlib, 'worm_entry_'+key).argtypes = (WormEntry,) 66 | ret = getattr(self.wormlib, 'worm_entry_'+key)(self.entry) 67 | return ret 68 | 69 | 70 | def iterate_first(self): 71 | ret = self.wormlib.worm_entry_iterate_first(self.entry) 72 | return ret 73 | 74 | def iterate_last(self): 75 | ret = self.wormlib.worm_entry_iterate_last(self.entry) 76 | return ret 77 | 78 | def iterate_id(self, id): 79 | self.wormlib.worm_entry_iterate_id.argtypes(WormEntry, c_uint32) 80 | ret = self.wormlib.worm_entry_iterate_id(self.entry, id) 81 | return ret 82 | 83 | def iterate_next(self): 84 | ret = self.wormlib.worm_entry_iterate_next(self.entry) 85 | return ret 86 | 87 | def readLogMessage(self): 88 | # FIXME So ist das nicht gedacht aber wir rechnen nicht mit sehr großen Datenmengen 89 | length = self.logMessageLength 90 | buffer = pointer((c_char * length)()) 91 | self.wormlib.worm_entry_readLogMessage.restype = WormError 92 | self.wormlib.worm_entry_readLogMessage.argtypes = (WormEntry, POINTER(c_char*length), worm_uint) 93 | ret = self.wormlib.worm_entry_readLogMessage(self.entry, buffer, length) 94 | s = cast(buffer, POINTER(c_char)) 95 | return string_at(s, size=length) 96 | 97 | def readProcessData(self, offset=0): 98 | # FIXME So ist das nicht gedacht aber wir rechnen nicht mit sehr großen Datenmengen 99 | length = self.processDataLength - offset 100 | buffer = pointer((c_char * length)()) 101 | self.wormlib.worm_entry_readProcessData.restype = WormError 102 | self.wormlib.worm_entry_readProcessData.argtypes = (WormEntry, worm_uint, POINTER(c_char*length), worm_uint) 103 | ret = self.wormlib.worm_entry_readProcessData(self.entry, offset, buffer, length) 104 | s = cast(buffer, POINTER(c_char)) 105 | return string_at(s, size=length) 106 | 107 | -------------------------------------------------------------------------------- /src/lib/wormexception.py: -------------------------------------------------------------------------------- 1 | # TSE Connection Library 2 | # Copyright (C) 2020 Bernd Wurst 3 | # 4 | # This program is free software; you can redistribute it and/or 5 | # modify it under the terms of the GNU Lesser General Public 6 | # License as published by the Free Software Foundation; either 7 | # version 3 of the License, or (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | # Lesser General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU Lesser General Public License 15 | # along with this program; if not, write to the Free Software Foundation, 16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 17 | 18 | from wormtypes import * 19 | 20 | class WormException(Exception): 21 | def __init__(self, errno, message): 22 | self.errno = errno 23 | self.message = message 24 | 25 | def __repr__(self): 26 | return '%s: %s' % (self.errno.hex(), self.message) 27 | 28 | 29 | def WormError_to_exception(errno): 30 | if errno == WORM_ERROR_NOERROR: 31 | return None 32 | else: 33 | raise WormException(errno, errno_map[errno]) 34 | 35 | errno_map = { 36 | 0: 'WORM_ERROR_NOERROR', 37 | 1: 'WORM_ERROR_INVALID_PARAMETER', 38 | 2: 'WORM_ERROR_NO_WORM_CARD', 39 | 3: 'WORM_ERROR_IO', 40 | 4: 'WORM_ERROR_TIMEOUT', 41 | 5: 'WORM_ERROR_OUTOFMEM', 42 | 6: 'WORM_ERROR_INVALID_RESPONSE', 43 | 7: 'WORM_ERROR_STORE_FULL_INTERNAL', 44 | 8: 'WORM_ERROR_RESPONSE_MISSING', 45 | 9: 'WORM_ERROR_EXPORT_NOT_INITIALIZED', 46 | 10: 'WORM_ERROR_EXPORT_FAILED', 47 | 11: 'WORM_ERROR_INCREMENTAL_EXPORT_INVALID_STATE', 48 | 12: 'WORM_ERROR_INCREMENTAL_EXPORT_NO_DATA', 49 | 13: 'WORM_ERROR_POWER_CYCLE_DETECTED', 50 | 14: 'WORM_ERROR_FIRMWARE_UPDATE_NOT_APPLIED', 51 | 15: 'WORM_ERROR_THREAD_START_FAILED', 52 | 16: 'WORM_ERROR_NETWORK', 53 | 17: 'WORM_ERROR_CMD_NOT_SUPPORTED', 54 | 18: 'WORM_ERROR_LAN_INVALID_API_TOKEN', 55 | 19: 'WORM_ERROR_NETWORK_TIMEOUT', 56 | 20: 'WORM_ERROR_CONNECTION_FAILED', 57 | 21: 'WORM_ERROR_LAN_UNBALANCED_LOCKS', 58 | 22: 'WORM_ERROR_LAN_INVALID_SERVER_RESPONSE', 59 | 23: 'WORM_ERROR_INVALID_STATE', 60 | 24: 'WORM_ERROR_TSE_NOT_FOUND', 61 | 25: 'WORM_ERROR_INCREMENTAL_EXPORT_LIMIT_TOO_LOW', 62 | 26: 'WORM_ERROR_FWU_NOT_AVAILABLE', 63 | 0x1000: 'WORM_ERROR_FROM_CARD_FIRST', 64 | 0x1001: 'WORM_ERROR_UNKNOWN', 65 | 0x1002: 'WORM_ERROR_NO_TIME_SET', 66 | 0x1004: 'WORM_ERROR_NO_TRANSACTION_IN_PROGRESS', 67 | 0x1005: 'WORM_ERROR_INVALID_CMD_SYNTAX', 68 | 0x1006: 'WORM_ERROR_NOT_ENOUGH_DATA_WRITTEN', 69 | 0x1007: 'WORM_ERROR_TSE_INVALID_PARAMETER', 70 | 0x1008: 'WORM_ERROR_TRANSACTION_NOT_STARTED', 71 | 0x1009: 'WORM_ERROR_MAX_PARALLEL_TRANSACTIONS', 72 | 0x100A: 'WORM_ERROR_CERTIFICATE_EXPIRED', 73 | 0x100C: 'WORM_ERROR_NO_LAST_TRANSACTION', 74 | 0x100D: 'WORM_ERROR_CMD_NOT_ALLOWED', 75 | 0x100E: 'WORM_ERROR_TRANSACTION_SIGNATURES_EXCEEDED', 76 | 0x100F: 'WORM_ERROR_NOT_AUTHORIZED', 77 | 0x1010: 'WORM_ERROR_MAX_REGISTERED_CLIENTS_REACHED', 78 | 0x1011: 'WORM_ERROR_CLIENT_NOT_REGISTERED', 79 | 0x1012: 'WORM_ERROR_EXPORT_UNACKNOWLEDGED_DATA', 80 | 0x1013: 'WORM_ERROR_CLIENT_HAS_UNFINISHED_TRANSACTIONS', 81 | 0x1014: 'WORM_ERROR_TSE_HAS_UNFINISHED_TRANSACTIONS', 82 | 0x1015: 'WORM_ERROR_TSE_NO_RESPONSE_TO_FETCH', 83 | 0x1016: 'WORM_ERROR_NOT_ALLOWED_EXPORT_IN_PROGRESS', 84 | 0x1017: 'WORM_ERROR_STORE_FULL', 85 | 0x1050: 'WORM_ERROR_WRONG_STATE_NEEDS_PUK_CHANGE', 86 | 0x1051: 'WORM_ERROR_WRONG_STATE_NEEDS_PIN_CHANGE', 87 | 0x1053: 'WORM_ERROR_WRONG_STATE_NEEDS_ACTIVE_CTSS', 88 | 0x1054: 'WORM_ERROR_WRONG_STATE_NEEDS_SELF_TEST', 89 | 0x1055: 'WORM_ERROR_WRONG_STATE_NEEDS_SELF_TEST_PASSED', 90 | 0x1061: 'WORM_ERROR_FWU_INTEGRITY_FAILURE', 91 | 0x1062: 'WORM_ERROR_FWU_DECRYPTION_FAILURE', 92 | 0x1064: 'WORM_ERROR_FWU_WRONG_FORMAT', 93 | 0x1065: 'WORM_ERROR_FWU_INTERNAL_ERROR', 94 | 0x1067: 'WORM_ERROR_FWU_DOWNGRADE_PROHIBITED', 95 | 0x10FD: 'WORM_ERROR_TSE_ALREADY_INITIALIZED', 96 | 0x10FE: 'WORM_ERROR_TSE_DECOMMISSIONED', 97 | 0x10FF: 'WORM_ERROR_TSE_NOT_INITIALIZED', 98 | 0x1100: 'WORM_ERROR_AUTHENTICATION_FAILED', 99 | 0x1201: 'WORM_ERROR_AUTHENTICATION_PIN_BLOCKED', 100 | 0x1202: 'WORM_ERROR_AUTHENTICATION_USER_NOT_LOGGED_IN', 101 | 0x1300: 'WORM_ERROR_SELF_TEST_FAILED_FW', 102 | 0x1310: 'WORM_ERROR_SELF_TEST_FAILED_CSP', 103 | 0x1320: 'WORM_ERROR_SELF_TEST_FAILED_RNG', 104 | 0x1400: 'WORM_ERROR_FWU_BASE_FW_ERROR', 105 | 0x1500: 'WORM_ERROR_FWU_FWEXT_ERROR', 106 | 0x1600: 'WORM_ERROR_FWU_CSP_ERROR', 107 | 0x2001: 'WORM_ERROR_EXPORT_NONE_IN_PROGRESS', 108 | 0x2002: 'WORM_ERROR_EXPORT_RETRY', 109 | 0x2003: 'WORM_ERROR_EXPORT_NO_DATA_AVAILABLE', 110 | 0xF000: 'WORM_ERROR_CMD_NOT_FOUND', 111 | 0xFF00: 'WORM_ERROR_SIG_ERROR', 112 | 0xFFFF: 'WORM_ERROR_FROM_CARD_LAST', 113 | } 114 | -------------------------------------------------------------------------------- /src/lib/worminfo.py: -------------------------------------------------------------------------------- 1 | # TSE Connection Library 2 | # Copyright (C) 2020 Bernd Wurst 3 | # 4 | # This program is free software; you can redistribute it and/or 5 | # modify it under the terms of the GNU Lesser General Public 6 | # License as published by the Free Software Foundation; either 7 | # version 3 of the License, or (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | # Lesser General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU Lesser General Public License 15 | # along with this program; if not, write to the Free Software Foundation, 16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 17 | 18 | import datetime 19 | from ctypes import * 20 | from wormtypes import * 21 | 22 | 23 | class Worm_Info: 24 | def __init__(self, worm): 25 | self.ctx = worm.ctx 26 | self.wormlib = worm.wormlib 27 | 28 | self.wormlib.worm_info_new.argtypes = (WormContext,) 29 | self.wormlib.worm_info_new.restype = WormInfo 30 | self.info = cast(self.wormlib.worm_info_new(self.ctx), WormInfo) 31 | self.wormlib.worm_info_read.restype = WormError 32 | self.wormlib.worm_info_read.argtypes = (WormInfo, ) 33 | self.update() 34 | 35 | def update(self): 36 | ret = self.wormlib.worm_info_read(self.info) 37 | #WormError_to_exception(ret) 38 | #Wenn wir hier eine Exception ausgeben, bricht das an manchen Stellen, falls die TSE nicht angesteckt ist... 39 | 40 | 41 | def __del__(self): 42 | if self.info: 43 | self.wormlib.worm_info_free(self.info) 44 | self.info = None 45 | 46 | def __getattr__(self, key): 47 | if key in ['isDevelopmentFirmware', 'isStoreOpen', 'hasValidTime', 'hasPassedSelfTest', 48 | 'isCtssInterfaceActive', 'isErsInterfaceActive', 'isExportEnabledIfCspTestFails', 49 | 'isDataImportInProgress', 'isTransactionInProgress', 'hasChangedPuk', 'hasChangedAdminPin', 50 | 'hasChangedTimeAdminPin']: 51 | return bool(self.__get_info_uint32(key)) 52 | elif key in ['tarExportSizeInSectors', 'tarExportSize']: 53 | return self.__get_info_uint64(key) 54 | elif key in ['size', 'capacity', 'timeUntilNextSelfTest', 'timeUntilNextTimeSynchronization', 55 | 'startedTransactions', 'maxStartedTransactions', 56 | 'createdSignatures', 'maxSignatures', 'remainingSignatures', 'maxTimeSynchronizationDelay', 57 | 'maxUpdateDelay', 'registeredClients', 'maxRegisteredClients', 'initializationState']: 58 | return self.__get_info_uint32(key) 59 | elif key in ['customizationIdentifier', 'uniqueId']: 60 | return self.__get_string(key) 61 | elif key in ['tsePublicKey', 'tseSerialNumber']: 62 | return self.__get_string64(key) 63 | elif key in ['tseDescription', 'formFactor',]: 64 | return self.__get_chars(key) 65 | elif key in ['softwareVersion', 'hardwareVersion']: 66 | return self.__get_version(key) 67 | elif key in ['certificateExpirationDate',]: 68 | return self.__get_date(key) 69 | else: 70 | raise AttributeError('unimplemented: %s' % key) 71 | 72 | 73 | def __get_info_uint64(self, key): 74 | getattr(self.wormlib, 'worm_info_'+key).restype = c_uint64 75 | getattr(self.wormlib, 'worm_info_'+key).argtypes = (WormInfo,) 76 | ret = getattr(self.wormlib, 'worm_info_'+key)(self.info) 77 | return ret 78 | 79 | 80 | def __get_info_uint32(self, key): 81 | getattr(self.wormlib, 'worm_info_'+key).restype = c_uint32 82 | getattr(self.wormlib, 'worm_info_'+key).argtypes = (WormInfo,) 83 | ret = getattr(self.wormlib, 'worm_info_'+key)(self.info) 84 | return ret 85 | 86 | 87 | def __get_chars(self, key): 88 | getattr(self.wormlib, 'worm_info_'+key).restype = c_char_p 89 | getattr(self.wormlib, 'worm_info_'+key).argtypes = (WormInfo,) 90 | ret = getattr(self.wormlib, 'worm_info_'+key)(self.info) 91 | return ret.decode('latin1') 92 | 93 | 94 | def __get_string(self, key): 95 | s = c_char_p() 96 | sLength = c_uint() 97 | getattr(self.wormlib, 'worm_info_'+key).argtypes = (WormInfo, POINTER(c_char_p), POINTER(c_uint)) 98 | getattr(self.wormlib, 'worm_info_'+key)(self.info, byref(s), byref(sLength)) 99 | s = cast(s, POINTER(c_char)) 100 | ret = string_at(s, size=sLength.value) 101 | return ret 102 | 103 | 104 | def __get_string64(self, key): 105 | s = c_char_p() 106 | sLength = c_uint64() 107 | getattr(self.wormlib, 'worm_info_'+key).argtypes = (WormInfo, POINTER(c_char_p), POINTER(c_uint64)) 108 | getattr(self.wormlib, 'worm_info_'+key)(self.info, byref(s), byref(sLength)) 109 | s = cast(s, POINTER(c_char)) 110 | ret = string_at(s, size=sLength.value) 111 | return ret 112 | 113 | def __get_version(self, key): 114 | getattr(self.wormlib, 'worm_info_'+key).restype = c_uint32 115 | getattr(self.wormlib, 'worm_info_'+key).argtypes = (WormInfo,) 116 | ret = getattr(self.wormlib, 'worm_info_'+key)(self.info) 117 | major = (ret & 0xffff0000) >> 16 118 | minor = (ret & 0x0000ff00) >> 8 119 | patch = (ret & 0x000000ff) 120 | return (major, minor, patch) 121 | 122 | 123 | def __get_date(self, key): 124 | getattr(self.wormlib, 'worm_info_'+key).restype = c_uint64 125 | getattr(self.wormlib, 'worm_info_'+key).argtypes = (WormInfo,) 126 | ret = getattr(self.wormlib, 'worm_info_'+key)(self.info) 127 | return datetime.datetime.fromtimestamp(ret) 128 | 129 | 130 | -------------------------------------------------------------------------------- /src/lib/wormtransactionresponse.py: -------------------------------------------------------------------------------- 1 | # TSE Connection Library 2 | # Copyright (C) 2020 Bernd Wurst 3 | # 4 | # This program is free software; you can redistribute it and/or 5 | # modify it under the terms of the GNU Lesser General Public 6 | # License as published by the Free Software Foundation; either 7 | # version 3 of the License, or (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | # Lesser General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU Lesser General Public License 15 | # along with this program; if not, write to the Free Software Foundation, 16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 17 | 18 | import datetime 19 | from ctypes import * 20 | from wormtypes import * 21 | 22 | 23 | class Worm_Transaction_Response: 24 | def __init__(self, worm): 25 | self.ctx = worm.ctx 26 | self.wormlib = worm.wormlib 27 | 28 | self.wormlib.worm_transaction_response_new.argtypes = (WormContext,) 29 | self.wormlib.worm_transaction_response_new.restype = WormTransactionResponse 30 | self.response = cast(self.wormlib.worm_transaction_response_new(self.ctx), WormTransactionResponse) 31 | 32 | def __del__(self): 33 | if self.response: 34 | self.wormlib.worm_transaction_response_free(self.response) 35 | self.response = None 36 | 37 | def __getattr__(self, key): 38 | if key in ['signatureCounter', 'transactionNumber']: 39 | return self.__get_info_uint64(key) 40 | elif key in ['serialNumber', 'signature',]: 41 | return self.__get_string(key) 42 | elif key in ['logTime',]: 43 | return self.__get_date(key) 44 | else: 45 | raise AttributeError('unimplemented: %s' % key) 46 | 47 | 48 | def __get_info_uint64(self, key): 49 | getattr(self.wormlib, 'worm_transaction_response_'+key).restype = c_uint64 50 | getattr(self.wormlib, 'worm_transaction_response_'+key).argtypes = (WormTransactionResponse,) 51 | ret = getattr(self.wormlib, 'worm_transaction_response_'+key)(self.response) 52 | return ret 53 | 54 | 55 | def __get_string(self, key): 56 | s = c_char_p() 57 | sLength = worm_uint() 58 | getattr(self.wormlib, 'worm_transaction_response_'+key).argtypes = (WormTransactionResponse, POINTER(c_char_p), POINTER(worm_uint)) 59 | getattr(self.wormlib, 'worm_transaction_response_'+key)(self.response, byref(s), byref(sLength)) 60 | s = cast(s, POINTER(c_char)) 61 | ret = string_at(s, size=sLength.value) 62 | return ret 63 | 64 | 65 | def __get_date(self, key): 66 | getattr(self.wormlib, 'worm_transaction_response_'+key).restype = worm_uint 67 | getattr(self.wormlib, 'worm_transaction_response_'+key).argtypes = (WormTransactionResponse,) 68 | ret = getattr(self.wormlib, 'worm_transaction_response_'+key)(self.response) 69 | return datetime.datetime.fromtimestamp(ret) 70 | 71 | 72 | -------------------------------------------------------------------------------- /src/lib/wormtypes.py: -------------------------------------------------------------------------------- 1 | # TSE Connection Library 2 | # Copyright (C) 2020 Bernd Wurst 3 | # 4 | # This program is free software; you can redistribute it and/or 5 | # modify it under the terms of the GNU Lesser General Public 6 | # License as published by the Free Software Foundation; either 7 | # version 3 of the License, or (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | # Lesser General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU Lesser General Public License 15 | # along with this program; if not, write to the Free Software Foundation, 16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 17 | 18 | from ctypes import c_void_p, c_int, c_char, c_uint64, Structure 19 | 20 | WormContext = c_void_p 21 | WormInfo = c_void_p 22 | WormEntry = c_void_p 23 | WormTransactionResponse = c_void_p 24 | 25 | WormError = c_int 26 | worm_uint = c_uint64 27 | 28 | class WormRegisteredClients(Structure): 29 | _fields_ = [ 30 | ("amount", c_int), 31 | ("clientIds", (c_char * 31) * 16), 32 | ] 33 | 34 | 35 | 36 | (WORM_INIT_UNINITIALIZED, 37 | WORM_INIT_INITIALIZED, 38 | WORM_INIT_DECOMMISSIONED) = range(3) 39 | 40 | 41 | # constants for WormUserId 42 | WORM_USER_UNAUTHENTICATED = 0 43 | WORM_USER_ADMIN = 1 44 | WORM_USER_TIME_ADMIN = 2 45 | 46 | WORM_EXPORT_TAR_INCREMENTAL_STATE_SIZE = 16 47 | 48 | WORM_ERROR_NOERROR = 0 49 | WORM_ERROR_INVALID_PARAMETER = 1 50 | WORM_ERROR_NO_WORM_CARD = 2 51 | WORM_ERROR_IO = 3 52 | WORM_ERROR_TIMEOUT = 4 53 | WORM_ERROR_OUTOFMEM = 5 54 | WORM_ERROR_INVALID_RESPONSE = 6 55 | WORM_ERROR_STORE_FULL_INTERNAL = 7 56 | WORM_ERROR_RESPONSE_MISSING = 8 57 | WORM_ERROR_EXPORT_NOT_INITIALIZED = 9 58 | WORM_ERROR_EXPORT_FAILED = 10 59 | WORM_ERROR_INCREMENTAL_EXPORT_INVALID_STATE = 11 60 | WORM_ERROR_INCREMENTAL_EXPORT_NO_DATA = 12 61 | WORM_ERROR_POWER_CYCLE_DETECTED = 13 62 | WORM_ERROR_FIRMWARE_UPDATE_NOT_APPLIED = 14 63 | WORM_ERROR_FROM_CARD_FIRST = 0x1000 64 | WORM_ERROR_UNKNOWN = 0x1001 65 | WORM_ERROR_NO_TIME_SET = 0x1002 66 | WORM_ERROR_NO_TRANSACTION_IN_PROGRESS = 0x1004 67 | WORM_ERROR_INVALID_CMD_SYNTAX = 0x1005 68 | WORM_ERROR_WRONG_LENGTH = WORM_ERROR_INVALID_CMD_SYNTAX 69 | WORM_ERROR_NOT_ENOUGH_DATA_WRITTEN = 0x1006 70 | WORM_ERROR_TSE_INVALID_PARAMETER = 0x1007 71 | WORM_ERROR_TRANSACTION_NOT_STARTED = 0x1008 72 | WORM_ERROR_MAX_PARALLEL_TRANSACTIONS = 0x1009 73 | WORM_ERROR_CERTIFICATE_EXPIRED = 0x100a 74 | WORM_ERROR_NO_LAST_TRANSACTION = 0x100c 75 | WORM_ERROR_CMD_NOT_ALLOWED = 0x100d 76 | WORM_ERROR_TRANSACTION_SIGNATURES_EXCEEDED = 0x100e 77 | WORM_ERROR_NOT_AUTHORIZED = 0x100f 78 | WORM_ERROR_MAX_REGISTERED_CLIENTS_REACHED = 0x1010 79 | WORM_ERROR_CLIENT_NOT_REGISTERED = 0x1011 80 | WORM_ERROR_EXPORT_UNACKNOWLEDGED_DATA = 0x1012 81 | WORM_ERROR_CLIENT_HAS_UNFINISHED_TRANSACTIONS = 0x1013 82 | WORM_ERROR_TSE_HAS_UNFINISHED_TRANSACTIONS = 0x1014 83 | WORM_ERROR_TSE_NO_RESPONSE_TO_FETCH = 0x1015 84 | WORM_ERROR_NOT_ALLOWED_EXPORT_IN_PROGRESS = 0x1016 85 | WORM_ERROR_STORE_FULL = 0x1017 86 | WORM_ERROR_WRONG_STATE_NEEDS_PUK_CHANGE = 0x1050 87 | WORM_ERROR_WRONG_STATE_NEEDS_PIN_CHANGE = 0x1051 88 | WORM_ERROR_WRONG_STATE_NEEDS_ACTIVE_CTSS = 0x1053 89 | WORM_ERROR_WRONG_STATE_NEEDS_ACTIVE_ERS = WORM_ERROR_WRONG_STATE_NEEDS_ACTIVE_CTSS 90 | WORM_ERROR_WRONG_STATE_NEEDS_SELF_TEST = 0x1054 91 | WORM_ERROR_WRONG_STATE_NEEDS_SELF_TEST_PASSED = 0x1055 92 | WORM_ERROR_FWU_INTEGRITY_FAILURE = 0x1061 93 | WORM_ERROR_FWU_DECRYPTION_FAILURE = 0x1062 94 | WORM_ERROR_FWU_WRONG_FORMAT = 0x1064 95 | WORM_ERROR_FWU_INTERNAL_ERROR = 0x1065 96 | WORM_ERROR_FWU_DOWNGRADE_PROHIBITED = 0x1067 97 | WORM_ERROR_TSE_ALREADY_INITIALIZED = 0x10FD 98 | WORM_ERROR_TSE_DECOMMISSIONED = 0x10FE 99 | WORM_ERROR_TSE_NOT_INITIALIZED = 0x10FF 100 | WORM_ERROR_AUTHENTICATION_FAILED = 0x1100 101 | WORM_ERROR_AUTHENTICATION_PIN_BLOCKED = 0x1201 102 | WORM_ERROR_AUTHENTICATION_USER_NOT_LOGGED_IN = 0x1202 103 | WORM_ERROR_SELF_TEST_FAILED_FW = 0x1300 104 | WORM_ERROR_SELF_TEST_FAILED_CSP = 0x1310 105 | WORM_ERROR_SELF_TEST_FAILED_RNG = 0x1320 106 | WORM_ERROR_FWU_BASE_FW_ERROR = 0x1400 107 | WORM_ERROR_FWU_FWEXT_ERROR = 0x1500 108 | WORM_ERROR_FWU_CSP_ERROR = 0x1600 109 | WORM_ERROR_EXPORT_NONE_IN_PROGRESS = 0x2001 110 | WORM_ERROR_EXPORT_RETRY = 0x2002 111 | WORM_ERROR_EXPORT_NO_DATA_AVAILABLE = 0x2003 112 | WORM_ERROR_CMD_NOT_FOUND = 0xf000 113 | WORM_ERROR_SIG_ERROR = 0xff00 114 | WORM_ERROR_FROM_CARD_LAST = 0xFFFF 115 | 116 | --------------------------------------------------------------------------------