Debian Codegraph @

addons/iot_drivers/iot_handlers/drivers/l10n_eg_drivers.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2 import base64
3 import json
4 import logging
5 import PyKCS11
6
7 from passlib.context import CryptContext
8
9 from odoo import http
10 from odoo.tools.config import config
11 from odoo.addons.iot_drivers.tools import route
12 from odoo.addons.iot_drivers.tools.system import IOT_SYSTEM, IS_RPI, IS_WINDOWS
13
14 _logger = logging.getLogger(__name__)
15
16 crypt_context = CryptContext(schemes=['pbkdf2_sha512'])
17
18
19 class EtaUsbController(http.Controller):
20
21 def _is_access_token_valid(self, access_token):
22 stored_hash = config.get('proxy_access_token')
23 if not stored_hash:
24 # empty password/hash => authentication forbidden
25 return False
26 return crypt_context.verify(access_token, stored_hash)
27
28 @route.iot_route('/hw_l10n_eg_eta/certificate', type='http', cors='*', csrf=False, methods=['POST'])
29 def eta_certificate(self, pin, access_token):
30 """Gets the certificate from the token and returns it to the main odoo instance so that we can prepare the
31 cades-bes object on the main odoo instance rather than this middleware
32
33 :param pin: pin of the token
34 :param access_token: token shared with the main odoo instance
35 :return: json object with the certificate
36 """
37 if not self._is_access_token_valid(access_token):
38 return self._get_error_template('unauthorized')
39 session, error = self._get_session(pin)
40 if error:
41 return error
42 try:
43 cert = session.findObjects([(PyKCS11.CKA_CLASS, PyKCS11.CKO_CERTIFICATE)])[0]
44 cert_bytes = bytes(session.getAttributeValue(cert, [PyKCS11.CKA_VALUE])[0])
45 payload = {
46 'certificate': base64.b64encode(cert_bytes).decode()
47 }
48 return json.dumps(payload)
49 except Exception as ex:
50 _logger.exception('Error while getting ETA certificate')
51 return self._get_error_template(str(ex))
52 finally:
53 session.logout()
54 session.closeSession()
55
56 @route.iot_route('/hw_l10n_eg_eta/sign', type='http', cors='*', csrf=False, methods=['POST'])
57 def eta_sign(self, pin, access_token, invoices):
58 """Check if the access_token is valid and sign the invoices accessing the usb key with the pin.
59
60 :param pin: pin of the token
61 :param access_token: token shared with the main odoo instance
62 :param invoices: dictionary of invoices. Keys are invoices ids, value are the base64 encoded binaries to sign
63 :return: json object with the signed invoices
64 """
65 if not self._is_access_token_valid(access_token):
66 return self._get_error_template('unauthorized')
67 session, error = self._get_session(pin)
68 if error:
69 return error
70 try:
71 cert = session.findObjects([(PyKCS11.CKA_CLASS, PyKCS11.CKO_CERTIFICATE)])[0]
72 cert_id = session.getAttributeValue(cert, [PyKCS11.CKA_ID])[0]
73 priv_key = session.findObjects([(PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY), (PyKCS11.CKA_ID, cert_id)])[0]
74
75 invoice_dict = dict()
76 invoices = json.loads(invoices)
77 for invoice, eta_inv in invoices.items():
78 to_sign = base64.b64decode(eta_inv)
79 signed_data = session.sign(priv_key, to_sign, PyKCS11.Mechanism(PyKCS11.CKM_SHA256_RSA_PKCS))
80 invoice_dict[invoice] = base64.b64encode(bytes(signed_data)).decode()
81
82 payload = {
83 'invoices': json.dumps(invoice_dict),
84 }
85 return json.dumps(payload)
86 except Exception as ex:
87 _logger.exception('Error while signing invoices')
88 return self._get_error_template(str(ex))
89 finally:
90 session.logout()
91 session.closeSession()
92
93 def _get_session(self, pin):
94 session = False
95
96 lib, error = self.get_crypto_lib()
97 if error:
98 return session, error
99
100 try:
101 pkcs11 = PyKCS11.PyKCS11Lib()
102 pkcs11.load(pkcs11dll_filename=lib)
103 except PyKCS11.PyKCS11Error:
104 return session, self._get_error_template('missing_dll')
105
106 slots = pkcs11.getSlotList(tokenPresent=True)
107 if not slots:
108 return session, self._get_error_template('no_drive')
109 if len(slots) > 1:
110 return session, self._get_error_template('multiple_drive')
111
112 try:
113 session = pkcs11.openSession(slots[0], PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION)
114 session.login(pin)
115 except Exception as ex: # noqa: BLE001
116 error = self._get_error_template(str(ex))
117 return session, error
118
119 def get_crypto_lib(self):
120 error = lib = False
121 if IOT_SYSTEM == 'Darwin':
122 lib = '/Library/OpenSC/lib/onepin-opensc-pkcs11.so'
123 elif IS_RPI:
124 lib = '/usr/lib/x86_64-linux-gnu/opensc-pkcs11.so'
125 elif IS_WINDOWS:
126 lib = 'C:/Windows/System32/eps2003csp11.dll'
127 else:
128 error = self._get_error_template('unsupported_system')
129 return lib, error
130
131 def _get_error_template(self, error_str):
132 return json.dumps({
133 'error': error_str,
134 })