Revize 9a6c9613
Přidáno uživatelem Jan Pašek před téměř 4 roky(ů)
src/controllers/certificates_controller.py | ||
---|---|---|
1 |
import json
|
|
2 |
from datetime import datetime
|
|
3 |
from itertools import chain
|
|
4 |
from json import JSONDecodeError
|
|
1 |
import time
|
|
2 |
from sqlite3 import Connection, Error, DatabaseError, IntegrityError, ProgrammingError, OperationalError, \
|
|
3 |
NotSupportedError
|
|
4 |
from typing import Dict, List, Set
|
|
5 | 5 |
|
6 |
from flask import request, Response |
|
7 |
from injector import inject |
|
8 |
|
|
9 |
from src.constants import CA_ID, \ |
|
10 |
SSL_ID, SIGNATURE_ID, AUTHENTICATION_ID, \ |
|
11 |
DATETIME_FORMAT, ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID # TODO DATABASE_FILE - not the Controller's |
|
12 |
from src.controllers.return_codes import * |
|
13 | 6 |
from src.exceptions.database_exception import DatabaseException |
14 |
from src.exceptions.unknown_exception import UnknownException |
|
15 |
from src.model.subject import Subject |
|
16 |
from src.services.certificate_service import CertificateService, RevocationReasonInvalidException, \ |
|
17 |
CertificateStatusInvalidException, CertificateNotFoundException, CertificateAlreadyRevokedException, \ |
|
18 |
CertificateCannotBeSetToValid |
|
19 |
# responsibility. |
|
20 |
from src.services.cryptography import CryptographyException |
|
21 |
from src.services.key_service import KeyService |
|
7 |
from injector import inject |
|
8 |
from src.constants import * |
|
9 |
from src.model.certificate import Certificate |
|
22 | 10 |
from src.utils.logger import Logger |
23 |
from src.utils.util import dict_to_string |
|
24 |
|
|
25 |
EXTENSIONS = "extensions" |
|
26 |
|
|
27 |
TREE_NODE_TYPE_COUNT = 3 |
|
28 |
KEY_PEM = "key_pem" |
|
29 |
PASSWORD = "password" |
|
30 |
KEY = "key" |
|
31 |
FILTERING = "filtering" |
|
32 |
PAGE = "page" |
|
33 |
PER_PAGE = "per_page" |
|
34 |
ISSUER = "issuer" |
|
35 |
US = "usage" |
|
36 |
NOT_AFTER = "notAfter" |
|
37 |
NOT_BEFORE = "notBefore" |
|
38 |
COMMON_NAME = "CN" |
|
39 |
ID = "id" |
|
40 |
CA = "CA" |
|
41 |
USAGE = "usage" |
|
42 |
SUBJECT = "subject" |
|
43 |
VALIDITY_DAYS = "validityDays" |
|
44 |
TYPE = "type" |
|
45 |
ISSUED_BY = "issuedby" |
|
46 |
STATUS = "status" |
|
47 |
REASON = "reason" |
|
48 |
REASON_UNDEFINED = "unspecified" |
|
49 |
NAME = "name" |
|
50 |
PASSWORD = "password" |
|
51 |
|
|
52 |
E_NO_ISSUER_FOUND = {"success": False, "data": "No certificate authority with such unique ID exists."} |
|
53 |
E_NO_CERTIFICATES_FOUND = {"success": False, "data": "No such certificate found."} |
|
54 |
E_NO_CERTIFICATE_ALREADY_REVOKED = {"success": False, "data": "Certificate is already revoked."} |
|
55 |
E_NO_CERT_PRIVATE_KEY_FOUND = {"success": False, |
|
56 |
"data": "Internal server error (certificate's private key cannot be found)."} |
|
57 |
E_NOT_JSON_FORMAT = {"success": False, "data": "The request must be JSON-formatted."} |
|
58 |
E_CORRUPTED_DATABASE = {"success": False, "data": "Internal server error (corrupted database)."} |
|
59 |
E_GENERAL_ERROR = {"success": False, "data": "Internal server error (unknown origin)."} |
|
60 |
E_MISSING_PARAMETERS = {"success": False, "data": "Invalid request, missing parameters."} |
|
61 |
E_WRONG_PARAMETERS = {"success": False, "data": "Invalid request, wrong parameters."} |
|
62 |
E_WRONG_PASSWORD = {"success": False, "data": "The provided passphrase does not match the provided key."} |
|
63 |
E_IDENTITY_NAME_NOT_SPECIFIED = {"success": False, "data": "Invalid request, missing identity name."} |
|
64 |
E_IDENTITY_PASSWORD_NOT_SPECIFIED = {"success": False, "data": "Invalid request, missing identity password."} |
|
65 |
|
|
66 |
|
|
67 |
class CertController: |
|
68 |
USAGE_KEY_MAP = {'CA': CA_ID, 'SSL': SSL_ID, 'digitalSignature': SIGNATURE_ID, 'authentication': AUTHENTICATION_ID} |
|
69 |
INVERSE_USAGE_KEY_MAP = {k: v for v, k in USAGE_KEY_MAP.items()} |
|
70 |
FILTERING_TYPE_KEY_MAP = {'root': ROOT_CA_ID, 'inter': INTERMEDIATE_CA_ID, 'end': CERTIFICATE_ID} |
|
71 |
# INVERSE_FILTERING_TYPE_KEY_MAP = {k: v for v, k in FILTERING_TYPE_KEY_MAP.items()} |
|
72 |
|
|
73 | 11 |
|
74 |
@inject |
|
75 |
def __init__(self, certificate_service: CertificateService, key_service: KeyService): |
|
76 |
self.certificate_service = certificate_service |
|
77 |
self.key_service = key_service |
|
78 |
|
|
79 |
def create_certificate(self): |
|
80 |
"""create new certificate |
|
12 |
INTEGRITY_ERROR_MSG = "Database relational integrity corrupted." |
|
13 |
PROGRAMMING_ERROR_MSG = "Exception raised for programming errors (etc. SQL statement)." |
|
14 |
OPERATIONAL_ERROR_MSG = "Exception raised for errors that are related to the database’s operation." |
|
15 |
NOT_SUPPORTED_ERROR_MSG = "Method or database API was used which is not supported by the database" |
|
16 |
DATABASE_ERROR_MSG = "Unknown exception that are related to the database." |
|
17 |
ERROR_MSG = "Unknown exception." |
|
81 | 18 |
|
82 |
Create a new certificate based on given information |
|
83 | 19 |
|
84 |
:param body: Certificate data to be created |
|
85 |
:type body: dict | bytes |
|
20 |
class CertificateRepository: |
|
86 | 21 |
|
87 |
:rtype: CreatedResponse |
|
22 |
@inject |
|
23 |
def __init__(self, connection: Connection): |
|
88 | 24 |
""" |
25 |
Constructor of the CertificateRepository object |
|
89 | 26 |
|
90 |
Logger.info(f"\n\t{request.referrer}" |
|
91 |
f"\n\t{request.method} {request.path} {request.scheme}") |
|
92 |
|
|
93 |
required_keys = {SUBJECT, USAGE, VALIDITY_DAYS} # required fields of the POST req |
|
94 |
|
|
95 |
if request.is_json: # accept JSON only |
|
96 |
body = request.get_json() |
|
97 |
|
|
98 |
Logger.info(f"\n\tRequest body:" |
|
99 |
f"\n{dict_to_string(body)}") |
|
100 |
|
|
101 |
if not all(k in body for k in required_keys): # verify that all keys are present |
|
102 |
Logger.error(f"Invalid request, missing parameters") |
|
103 |
return E_MISSING_PARAMETERS, C_BAD_REQUEST |
|
104 |
|
|
105 |
if not isinstance(body[VALIDITY_DAYS], int): # type checking |
|
106 |
Logger.error(f"Invalid request, wrong parameter '{VALIDITY_DAYS}'.") |
|
107 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
108 |
|
|
109 |
subject = Subject.from_dict(body[SUBJECT]) # generate Subject from passed dict |
|
110 |
|
|
111 |
if subject is None: # if the format is incorrect |
|
112 |
Logger.error(f"Invalid request, wrong parameter '{SUBJECT}'.") |
|
113 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
114 |
|
|
115 |
usages_dict = {} |
|
116 |
|
|
117 |
if USAGE not in body or not isinstance(body[USAGE], list): # type checking |
|
118 |
Logger.error(f"Invalid request, wrong parameter '{USAGE}'.") |
|
119 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
120 |
|
|
121 |
for v in body[USAGE]: # for each usage |
|
122 |
if v not in CertController.KEY_MAP: # check that it is a valid usage |
|
123 |
Logger.error(f"Invalid request, wrong parameter '{USAGE}'[{v}].") |
|
124 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST # and throw if it is not |
|
125 |
usages_dict[CertController.KEY_MAP[v]] = True # otherwise translate key and set |
|
126 |
|
|
127 |
if KEY in body: |
|
128 |
if isinstance(body[KEY], dict): |
|
129 |
if PASSWORD in body[KEY]: |
|
130 |
passphrase = body[KEY][PASSWORD] |
|
131 |
if KEY_PEM in body[KEY]: |
|
132 |
key_pem = body[KEY][KEY_PEM] |
|
133 |
if not self.key_service.verify_key(key_pem, passphrase=passphrase): |
|
134 |
Logger.error(f"Passphrase specified but invalid.") |
|
135 |
return E_WRONG_PASSWORD, C_BAD_REQUEST |
|
136 |
key = self.key_service.wrap_custom_key(key_pem, passphrase=passphrase) |
|
137 |
else: |
|
138 |
key = self.key_service.create_new_key(passphrase) |
|
139 |
else: |
|
140 |
if KEY_PEM in body[KEY]: |
|
141 |
key_pem = body[KEY][KEY_PEM] |
|
142 |
if not self.key_service.verify_key(key_pem, passphrase=None): |
|
143 |
Logger.error("Passphrase ommited but required.") |
|
144 |
return E_WRONG_PASSWORD, C_BAD_REQUEST |
|
145 |
key = self.key_service.wrap_custom_key(key_pem, passphrase=None) |
|
146 |
else: |
|
147 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST # if "key" exists but is empty |
|
148 |
else: |
|
149 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
150 |
else: |
|
151 |
key = self.key_service.create_new_key() # if "key" does not exist |
|
152 |
|
|
153 |
if CA not in body or body[CA] is None: # if issuer omitted (legal) or none |
|
154 |
cert = self.certificate_service.create_root_ca( # create a root CA |
|
155 |
key, |
|
156 |
subject, |
|
157 |
usages=usages_dict, # TODO ignoring usages -> discussion |
|
158 |
days=body[VALIDITY_DAYS] |
|
159 |
) |
|
160 |
else: |
|
161 |
issuer = self.certificate_service.get_certificate(body[CA]) # get base issuer info |
|
162 |
|
|
163 |
if issuer is None: # if such issuer does not exist |
|
164 |
Logger.error(f"No certificate authority with such unique ID exists 'ID = {key.private_key_id}'.") |
|
165 |
self.key_service.delete_key(key.private_key_id) # free |
|
166 |
return E_NO_ISSUER_FOUND, C_BAD_REQUEST # and throw |
|
167 |
|
|
168 |
issuer_key = self.key_service.get_key(issuer.private_key_id) # get issuer's key, which must exist |
|
169 |
|
|
170 |
if issuer_key is None: # if it does not |
|
171 |
Logger.error(f"Internal server error (corrupted database).") |
|
172 |
self.key_service.delete_key(key.private_key_id) # free |
|
173 |
return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR # and throw |
|
174 |
|
|
175 |
f = self.certificate_service.create_ca if CA_ID in usages_dict and usages_dict[CA_ID] else \ |
|
176 |
self.certificate_service.create_end_cert |
|
177 |
|
|
178 |
# noinspection PyTypeChecker |
|
179 |
cert = f( # create inter CA or end cert |
|
180 |
key, # according to whether 'CA' is among |
|
181 |
subject, # the usages' fields |
|
182 |
issuer, |
|
183 |
issuer_key, |
|
184 |
usages=usages_dict, |
|
185 |
days=body[VALIDITY_DAYS] |
|
186 |
) |
|
187 |
|
|
188 |
if cert is not None: |
|
189 |
return {"success": True, |
|
190 |
"data": cert.certificate_id}, C_CREATED_SUCCESSFULLY |
|
191 |
else: # if this fails, then |
|
192 |
Logger.error(f"Internal error: The certificate could not have been created.") |
|
193 |
self.key_service.delete_key(key.private_key_id) # free |
|
194 |
return {"success": False, # and wonder what the cause is, |
|
195 |
"data": "Internal error: The certificate could not have been created."}, C_BAD_REQUEST |
|
196 |
# as obj/None carries only one bit |
|
197 |
# of error information |
|
198 |
else: |
|
199 |
Logger.error(f"The request must be JSON-formatted.") |
|
200 |
return E_NOT_JSON_FORMAT, C_BAD_REQUEST # throw in case of non-JSON format |
|
201 |
|
|
202 |
def get_certificate_by_id(self, id): |
|
203 |
"""get certificate by ID |
|
204 |
|
|
205 |
Get certificate in PEM format by ID |
|
206 |
|
|
207 |
:param id: ID of a certificate to be queried |
|
208 |
:type id: dict | bytes |
|
209 |
|
|
210 |
:rtype: PemResponse |
|
27 |
:param connection: Instance of the Connection object |
|
211 | 28 |
""" |
29 |
self.connection = connection |
|
30 |
self.cursor = connection.cursor() |
|
212 | 31 |
|
213 |
Logger.info(f"\n\t{request.referrer}" |
|
214 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
215 |
f"\n\tCertificate ID = {id}") |
|
216 |
try: |
|
217 |
v = int(id) |
|
218 |
except ValueError: |
|
219 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
220 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
221 |
|
|
222 |
cert = self.certificate_service.get_certificate(v) |
|
223 |
|
|
224 |
if cert is None: |
|
225 |
Logger.error(f"No such certificate found 'ID = {v}'.") |
|
226 |
return E_NO_CERTIFICATES_FOUND, C_NO_DATA |
|
227 |
else: |
|
228 |
return {"success": True, "data": cert.pem_data}, C_SUCCESS |
|
229 |
|
|
230 |
def get_certificate_details_by_id(self, id): |
|
231 |
"""get certificate's details by ID |
|
232 |
|
|
233 |
Get certificate details by ID |
|
32 |
def create(self, certificate: Certificate): |
|
33 |
""" |
|
34 |
Creates a certificate. |
|
35 |
For root certificate (CA) the parent certificate id is modified to the same id (id == parent_id). |
|
234 | 36 |
|
235 |
:param id: ID of a certificate whose details are to be queried |
|
236 |
:type id: dict | bytes |
|
37 |
:param certificate: Instance of the Certificate object |
|
237 | 38 |
|
238 |
:rtype: CertificateResponse
|
|
39 |
:return: the result of whether the creation was successful
|
|
239 | 40 |
""" |
240 | 41 |
|
241 |
Logger.info(f"\n\t{request.referrer}" |
|
242 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
243 |
f"\n\tCertificate ID = {id}") |
|
42 |
Logger.debug("Function launched.") |
|
244 | 43 |
|
245 | 44 |
try: |
246 |
v = int(id) |
|
247 |
except ValueError: |
|
248 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
249 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
45 |
sql = (f"INSERT INTO {TAB_CERTIFICATES} " |
|
46 |
f"({COL_VALID_FROM}," |
|
47 |
f"{COL_VALID_TO}," |
|
48 |
f"{COL_PEM_DATA}," |
|
49 |
f"{COL_COMMON_NAME}," |
|
50 |
f"{COL_COUNTRY_CODE}," |
|
51 |
f"{COL_LOCALITY}," |
|
52 |
f"{COL_PROVINCE}," |
|
53 |
f"{COL_ORGANIZATION}," |
|
54 |
f"{COL_ORGANIZATIONAL_UNIT}," |
|
55 |
f"{COL_EMAIL_ADDRESS}," |
|
56 |
f"{COL_TYPE_ID}," |
|
57 |
f"{COL_PARENT_ID}," |
|
58 |
f"{COL_PRIVATE_KEY_ID}) " |
|
59 |
f"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)") |
|
60 |
values = [certificate.valid_from, |
|
61 |
certificate.valid_to, |
|
62 |
certificate.pem_data, |
|
63 |
certificate.common_name, |
|
64 |
certificate.country_code, |
|
65 |
certificate.locality, |
|
66 |
certificate.province, |
|
67 |
certificate.organization, |
|
68 |
certificate.organizational_unit, |
|
69 |
certificate.email_address, |
|
70 |
certificate.type_id, |
|
71 |
certificate.parent_id, |
|
72 |
certificate.private_key_id] |
|
73 |
self.cursor.execute(sql, values) |
|
74 |
self.connection.commit() |
|
75 |
|
|
76 |
last_id: int = self.cursor.lastrowid |
|
77 |
|
|
78 |
if certificate.type_id == ROOT_CA_ID: |
|
79 |
certificate.parent_id = last_id |
|
80 |
self.update(last_id, certificate) |
|
81 |
else: |
|
82 |
for usage_id, usage_value in certificate.usages.items(): |
|
83 |
if usage_value: |
|
84 |
sql = (f"INSERT INTO {TAB_CERTIFICATE_USAGES} " |
|
85 |
f"({COL_CERTIFICATE_ID}," |
|
86 |
f"{COL_USAGE_TYPE_ID}) " |
|
87 |
f"VALUES (?,?)") |
|
88 |
values = [last_id, usage_id] |
|
89 |
self.cursor.execute(sql, values) |
|
90 |
self.connection.commit() |
|
91 |
except IntegrityError: |
|
92 |
Logger.error(INTEGRITY_ERROR_MSG) |
|
93 |
raise DatabaseException(INTEGRITY_ERROR_MSG) |
|
94 |
except ProgrammingError: |
|
95 |
Logger.error(PROGRAMMING_ERROR_MSG) |
|
96 |
raise DatabaseException(PROGRAMMING_ERROR_MSG) |
|
97 |
except OperationalError: |
|
98 |
Logger.error(OPERATIONAL_ERROR_MSG) |
|
99 |
raise DatabaseException(OPERATIONAL_ERROR_MSG) |
|
100 |
except NotSupportedError: |
|
101 |
Logger.error(NOT_SUPPORTED_ERROR_MSG) |
|
102 |
raise DatabaseException(NOT_SUPPORTED_ERROR_MSG) |
|
103 |
except DatabaseError: |
|
104 |
Logger.error(DATABASE_ERROR_MSG) |
|
105 |
raise DatabaseException(DATABASE_ERROR_MSG) |
|
106 |
except Error: |
|
107 |
Logger.error(ERROR_MSG) |
|
108 |
raise DatabaseException(ERROR_MSG) |
|
109 |
|
|
110 |
return last_id |
|
111 |
|
|
112 |
def read(self, certificate_id: int): |
|
113 |
""" |
|
114 |
Reads (selects) a certificate. |
|
250 | 115 |
|
251 |
cert = self.certificate_service.get_certificate(v)
|
|
116 |
:param certificate_id: ID of specific certificate
|
|
252 | 117 |
|
253 |
if cert is None: |
|
254 |
Logger.error(f"No such certificate found 'ID = {v}'.") |
|
255 |
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND |
|
118 |
:return: instance of the Certificate object |
|
119 |
""" |
|
256 | 120 |
|
257 |
data = self.cert_to_dict_full(cert) |
|
258 |
if data is None: |
|
259 |
return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR |
|
121 |
Logger.debug("Function launched.") |
|
260 | 122 |
|
261 | 123 |
try: |
262 |
state = self.certificate_service.get_certificate_state(v) |
|
263 |
data["status"] = state |
|
264 |
except CertificateNotFoundException: |
|
265 |
Logger.error(f"No such certificate found 'ID = {id}'.") |
|
266 |
|
|
267 |
return {"success": True, "data": data}, C_SUCCESS |
|
268 |
|
|
269 |
def get_certificate_list(self): |
|
270 |
"""get list of certificates |
|
271 |
|
|
272 |
Lists certificates based on provided filtering options |
|
273 |
|
|
274 |
:param filtering: Filter certificate type to be queried |
|
275 |
:type filtering: dict | bytes |
|
276 |
|
|
277 |
:rtype: CertificateListResponse |
|
124 |
sql = (f"SELECT * FROM {TAB_CERTIFICATES} " |
|
125 |
f"WHERE {COL_ID} = ? AND ({COL_DELETION_DATE} IS NULL OR {COL_DELETION_DATE} = '')") |
|
126 |
values = [certificate_id] |
|
127 |
self.cursor.execute(sql, values) |
|
128 |
certificate_row = self.cursor.fetchone() |
|
129 |
|
|
130 |
if certificate_row is None: |
|
131 |
return None |
|
132 |
|
|
133 |
sql = (f"SELECT * FROM {TAB_CERTIFICATE_USAGES} " |
|
134 |
f"WHERE {COL_CERTIFICATE_ID} = ?") |
|
135 |
self.cursor.execute(sql, values) |
|
136 |
usage_rows = self.cursor.fetchall() |
|
137 |
|
|
138 |
usage_dict: Dict[int, bool] = {} |
|
139 |
for usage_row in usage_rows: |
|
140 |
usage_dict[usage_row[2]] = True |
|
141 |
|
|
142 |
certificate: Certificate = Certificate(certificate_row[0], # ID |
|
143 |
certificate_row[1], # valid from |
|
144 |
certificate_row[2], # valid to |
|
145 |
certificate_row[3], # pem data |
|
146 |
certificate_row[14], # type ID |
|
147 |
certificate_row[15], # parent ID |
|
148 |
certificate_row[16], # private key ID |
|
149 |
usage_dict, |
|
150 |
certificate_row[4], # common name |
|
151 |
certificate_row[5], # country code |
|
152 |
certificate_row[6], # locality |
|
153 |
certificate_row[7], # province |
|
154 |
certificate_row[8], # organization |
|
155 |
certificate_row[9], # organizational unit |
|
156 |
certificate_row[10], # email address |
|
157 |
certificate_row[11], # revocation date |
|
158 |
certificate_row[12]) # revocation reason |
|
159 |
|
|
160 |
except IntegrityError: |
|
161 |
Logger.error(INTEGRITY_ERROR_MSG) |
|
162 |
raise DatabaseException(INTEGRITY_ERROR_MSG) |
|
163 |
except ProgrammingError: |
|
164 |
Logger.error(PROGRAMMING_ERROR_MSG) |
|
165 |
raise DatabaseException(PROGRAMMING_ERROR_MSG) |
|
166 |
except OperationalError: |
|
167 |
Logger.error(OPERATIONAL_ERROR_MSG) |
|
168 |
raise DatabaseException(OPERATIONAL_ERROR_MSG) |
|
169 |
except NotSupportedError: |
|
170 |
Logger.error(NOT_SUPPORTED_ERROR_MSG) |
|
171 |
raise DatabaseException(NOT_SUPPORTED_ERROR_MSG) |
|
172 |
except DatabaseError: |
|
173 |
Logger.error(DATABASE_ERROR_MSG) |
|
174 |
raise DatabaseException(DATABASE_ERROR_MSG) |
|
175 |
except Error: |
|
176 |
Logger.error(ERROR_MSG) |
|
177 |
raise DatabaseException(ERROR_MSG) |
|
178 |
|
|
179 |
return certificate |
|
180 |
|
|
181 |
def read_all(self, filter_type: int = None): |
|
278 | 182 |
""" |
183 |
Reads (selects) all certificates (with type). |
|
279 | 184 |
|
280 |
Logger.info(f"\n\t{request.referrer}" |
|
281 |
f"\n\t{request.method} {request.path} {request.scheme}") |
|
282 |
|
|
283 |
|
|
284 |
# the filtering parameter can be read as URL argument or as a request body |
|
285 |
if request.is_json: |
|
286 |
data = request.get_json() |
|
287 |
else: |
|
288 |
data = {} |
|
289 |
|
|
290 |
if FILTERING in request.args.keys(): |
|
291 |
try: |
|
292 |
data[FILTERING] = json.loads(request.args[FILTERING]) |
|
293 |
except JSONDecodeError: |
|
294 |
Logger.error(f"The request must be JSON-formatted.") |
|
295 |
return E_NOT_JSON_FORMAT, C_BAD_REQUEST |
|
296 |
|
|
297 |
if PAGE in request.args.keys(): |
|
298 |
try: |
|
299 |
data[PAGE] = json.loads(request.args[PAGE]) |
|
300 |
except JSONDecodeError: |
|
301 |
Logger.error(f"The request must be JSON-formatted.") |
|
302 |
return E_NOT_JSON_FORMAT, C_BAD_REQUEST |
|
303 |
|
|
304 |
if PER_PAGE in request.args.keys(): |
|
305 |
try: |
|
306 |
data[PER_PAGE] = json.loads(request.args[PER_PAGE]) |
|
307 |
except JSONDecodeError: |
|
308 |
Logger.error(f"The request must be JSON-formatted.") |
|
309 |
return E_NOT_JSON_FORMAT, C_BAD_REQUEST |
|
310 |
|
|
311 |
Logger.info(f"\n\tRequest body:" |
|
312 |
f"\n{dict_to_string(data)}") |
|
313 |
|
|
314 |
target_types = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID} |
|
315 |
target_usages = {v for v in CertController.INVERSE_USAGE_KEY_MAP.keys()} |
|
316 |
target_cn_substring = None |
|
317 |
issuer_id = -1 |
|
318 |
|
|
319 |
unfiltered = True |
|
320 |
|
|
321 |
if PER_PAGE in data: |
|
322 |
unfiltered = False |
|
323 |
page = data.get(PAGE, 0) |
|
324 |
per_page = data[PER_PAGE] |
|
325 |
else: |
|
326 |
page = None |
|
327 |
per_page = None |
|
328 |
|
|
329 |
if FILTERING in data: # if the 'filtering' field exists |
|
330 |
unfiltered = False |
|
331 |
if isinstance(data[FILTERING], dict): # and it is also a 'dict' |
|
332 |
|
|
333 |
# noinspection DuplicatedCode |
|
334 |
if TYPE in data[FILTERING]: # containing 'type' |
|
335 |
if isinstance(data[FILTERING][TYPE], list): # which is a 'list', |
|
336 |
# map every field to id |
|
337 |
try: |
|
338 |
target_types = {CertController.FILTERING_TYPE_KEY_MAP[v] for v in data[FILTERING][TYPE]} |
|
339 |
except KeyError as e: |
|
340 |
Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{TYPE}' - '{e}'.") |
|
341 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
342 |
else: |
|
343 |
Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{TYPE}'.") |
|
344 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
345 |
|
|
346 |
# noinspection DuplicatedCode |
|
347 |
if USAGE in data[FILTERING]: # containing 'usage' |
|
348 |
if isinstance(data[FILTERING][USAGE], list): # which is a 'list', |
|
349 |
# map every field to id |
|
350 |
try: |
|
351 |
target_usages = {CertController.USAGE_KEY_MAP[v] for v in data[FILTERING][USAGE]} |
|
352 |
except KeyError as e: |
|
353 |
Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{USAGE}' - '{e}'.") |
|
354 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
355 |
else: |
|
356 |
Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{USAGE}'.") |
|
357 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
358 |
|
|
359 |
if COMMON_NAME in data[FILTERING]: # containing 'CN' |
|
360 |
if isinstance(data[FILTERING][COMMON_NAME], str): # which is a 'str' |
|
361 |
target_cn_substring = data[FILTERING][COMMON_NAME] |
|
362 |
else: |
|
363 |
Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{COMMON_NAME}'.") |
|
364 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
365 |
|
|
366 |
if ISSUED_BY in data[FILTERING]: # containing 'issuedby' |
|
367 |
if isinstance(data[FILTERING][ISSUED_BY], int): # which is an 'int' |
|
368 |
issuer_id = data[FILTERING][ISSUED_BY] # then get its children only |
|
369 |
|
|
370 |
else: |
|
371 |
Logger.error(f"Invalid request, wrong parameters '{FILTERING}'.") |
|
372 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
373 |
|
|
374 |
if unfiltered: # if not filtering |
|
375 |
certs = self.certificate_service.get_certificates() |
|
376 |
elif issuer_id >= 0: # if filtering by an issuer |
|
377 |
try: |
|
378 |
# get his children, filtered |
|
379 |
certs = self.certificate_service.get_certificates_issued_by_filter( |
|
380 |
issuer_id=issuer_id, |
|
381 |
target_types=target_types, |
|
382 |
target_usages=target_usages, |
|
383 |
target_cn_substring=target_cn_substring, |
|
384 |
page=page, |
|
385 |
per_page=per_page |
|
386 |
) |
|
387 |
except CertificateNotFoundException: # if id does not exist |
|
388 |
Logger.error(f"No such certificate found 'ID = {issuer_id}'.") |
|
389 |
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND # throw |
|
390 |
else: |
|
391 |
certs = self.certificate_service.get_certificates_filter( |
|
392 |
target_types=target_types, |
|
393 |
target_usages=target_usages, |
|
394 |
target_cn_substring=target_cn_substring, |
|
395 |
page=page, |
|
396 |
per_page=per_page |
|
397 |
) |
|
185 |
:param filter_type: ID of certificate type from CertificateTypes table |
|
398 | 186 |
|
399 |
if certs is None: |
|
400 |
Logger.error(f"Internal server error (unknown origin).") |
|
401 |
return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR |
|
402 |
elif len(certs) == 0: |
|
403 |
# TODO check log level |
|
404 |
Logger.warning(f"No such certificate found (empty list).") |
|
405 |
return {"success": True, "data": []}, C_SUCCESS |
|
406 |
else: |
|
407 |
ret = [] |
|
408 |
for c in certs: |
|
409 |
data = self.cert_to_dict_partial(c) |
|
410 |
if data is None: |
|
411 |
Logger.error(f"Internal server error (corrupted database).") |
|
412 |
return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR |
|
413 |
ret.append( |
|
414 |
data |
|
415 |
) |
|
416 |
return {"success": True, "data": ret}, C_SUCCESS |
|
417 |
|
|
418 |
def get_certificate_root_by_id(self, id): |
|
419 |
"""get certificate's root of trust chain by ID |
|
420 |
|
|
421 |
Get certificate's root of trust chain in PEM format by ID |
|
422 |
|
|
423 |
:param id: ID of a child certificate whose root is to be queried |
|
424 |
:type id: dict | bytes |
|
425 |
|
|
426 |
:rtype: PemResponse |
|
187 |
:return: list of certificates |
|
427 | 188 |
""" |
428 | 189 |
|
429 |
Logger.info(f"\n\t{request.referrer}" |
|
430 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
431 |
f"\n\tCertificate ID = {id}") |
|
190 |
Logger.debug("Function launched.") |
|
432 | 191 |
|
433 | 192 |
try: |
434 |
v = int(id) |
|
435 |
except ValueError: |
|
436 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
437 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
438 |
|
|
439 |
cert = self.certificate_service.get_certificate(v) |
|
440 |
|
|
441 |
if cert is None: |
|
442 |
Logger.error(f"No such certificate found 'ID = {v}'.") |
|
443 |
return E_NO_CERTIFICATES_FOUND, C_NO_DATA |
|
444 |
|
|
445 |
trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False) |
|
446 |
if trust_chain is None or len(trust_chain) == 0: |
|
447 |
Logger.error(f"No such certificate found (empty list).") |
|
448 |
return E_NO_CERTIFICATES_FOUND, C_NO_DATA |
|
193 |
sql_extension = "" |
|
194 |
values = [] |
|
195 |
if filter_type is not None: |
|
196 |
sql_extension = (f" AND {COL_TYPE_ID} = (" |
|
197 |
f"SELECT {COL_ID} FROM {TAB_CERTIFICATE_TYPES} WHERE {COL_ID} = ?)") |
|
198 |
values = [filter_type] |
|
199 |
|
|
200 |
sql = (f"SELECT * FROM {TAB_CERTIFICATES} " |
|
201 |
f"WHERE ({COL_DELETION_DATE} IS NULL OR {COL_DELETION_DATE} = ''){sql_extension}") |
|
202 |
self.cursor.execute(sql, values) |
|
203 |
certificate_rows = self.cursor.fetchall() |
|
204 |
|
|
205 |
certificates: List[Certificate] = [] |
|
206 |
for certificate_row in certificate_rows: |
|
207 |
sql = (f"SELECT * FROM {TAB_CERTIFICATE_USAGES} " |
|
208 |
f"WHERE {COL_CERTIFICATE_ID} = ?") |
|
209 |
values = [certificate_row[0]] |
|
210 |
self.cursor.execute(sql, values) |
|
211 |
usage_rows = self.cursor.fetchall() |
|
212 |
|
|
213 |
usage_dict: Dict[int, bool] = {} |
|
214 |
for usage_row in usage_rows: |
|
215 |
usage_dict[usage_row[2]] = True |
|
216 |
|
|
217 |
certificates.append(Certificate(certificate_row[0], # ID |
|
218 |
certificate_row[1], # valid from |
|
219 |
certificate_row[2], # valid to |
|
220 |
certificate_row[3], # pem data |
|
221 |
certificate_row[14], # type ID |
|
222 |
certificate_row[15], # parent ID |
|
223 |
certificate_row[16], # private key ID |
|
224 |
usage_dict, |
|
225 |
certificate_row[4], # common name |
|
226 |
certificate_row[5], # country code |
|
227 |
certificate_row[6], # locality |
|
228 |
certificate_row[7], # province |
|
229 |
certificate_row[8], # organization |
|
230 |
certificate_row[9], # organizational unit |
|
231 |
certificate_row[10], # email address |
|
232 |
certificate_row[11], # revocation date |
|
233 |
certificate_row[12])) # revocation reason |
|
234 |
except IntegrityError: |
|
235 |
Logger.error(INTEGRITY_ERROR_MSG) |
|
236 |
raise DatabaseException(INTEGRITY_ERROR_MSG) |
|
237 |
except ProgrammingError: |
|
238 |
Logger.error(PROGRAMMING_ERROR_MSG) |
|
239 |
raise DatabaseException(PROGRAMMING_ERROR_MSG) |
|
240 |
except OperationalError: |
|
241 |
Logger.error(OPERATIONAL_ERROR_MSG) |
|
242 |
raise DatabaseException(OPERATIONAL_ERROR_MSG) |
|
243 |
except NotSupportedError: |
|
244 |
Logger.error(NOT_SUPPORTED_ERROR_MSG) |
|
245 |
raise DatabaseException(NOT_SUPPORTED_ERROR_MSG) |
|
246 |
except DatabaseError: |
|
247 |
Logger.error(DATABASE_ERROR_MSG) |
|
248 |
raise DatabaseException(DATABASE_ERROR_MSG) |
|
249 |
except Error: |
|
250 |
Logger.error(ERROR_MSG) |
|
251 |
raise DatabaseException(ERROR_MSG) |
|
252 |
|
|
253 |
return certificates |
|
254 |
|
|
255 |
def read_all_filter(self, target_types: Set[int], target_usages: Set[int], target_cn_substring: str, page: int, |
|
256 |
per_page: int): |
|
257 |
""" |
|
258 |
Reads (selects) all certificates according to a specific filtering and pagination options. |
|
259 |
:param target_types: certificate types (filter) |
|
260 |
:param target_usages: certificate usages (filter) |
|
261 |
:param target_cn_substring: certificate CN substring (filter) |
|
262 |
:param page: target page |
|
263 |
:param per_page: target page size |
|
264 |
:return: list of certificates |
|
265 |
""" |
|
449 | 266 |
|
450 |
return {"success": True, "data": trust_chain[-1].pem_data}, C_SUCCESS
|
|
267 |
Logger.debug("Function launched.")
|
|
451 | 268 |
|
452 |
def get_certificate_trust_chain_by_id(self, id): |
|
453 |
"""get certificate's trust chain by ID (including root certificate) |
|
269 |
try: |
|
270 |
values = [] |
|
271 |
values += list(target_types) |
|
272 |
values += list(target_usages) |
|
273 |
|
|
274 |
sql = ( |
|
275 |
f"SELECT a.{COL_ID}, {COL_COMMON_NAME}, {COL_VALID_FROM}, {COL_VALID_TO}, {COL_PEM_DATA}, " |
|
276 |
f"{COL_REVOCATION_DATE}, {COL_REVOCATION_REASON}, {COL_PRIVATE_KEY_ID}, {COL_TYPE_ID}, {COL_PARENT_ID} " |
|
277 |
f"FROM {TAB_CERTIFICATES} a " |
|
278 |
f"WHERE (a.{COL_DELETION_DATE} IS NULL OR a.{COL_DELETION_DATE} = '') " |
|
279 |
f"AND a.{COL_TYPE_ID} IN ({','.join('?' * len(target_types))}) " |
|
280 |
f"AND (SELECT COUNT(*) FROM {TAB_CERTIFICATE_USAGES} " |
|
281 |
f"WHERE {COL_CERTIFICATE_ID} = a.{COL_ID} " |
|
282 |
f"AND {COL_USAGE_TYPE_ID} IN ({','.join('?' * len(target_usages))}) " |
|
283 |
f") > 0 " |
|
284 |
) |
|
454 | 285 |
|
455 |
Get certificate trust chain in PEM format by ID |
|
286 |
if target_cn_substring is not None: |
|
287 |
sql += f" AND a.{COL_COMMON_NAME} LIKE '%' || ? || '%'" |
|
288 |
|
|
289 |
values += [target_cn_substring] |
|
290 |
|
|
291 |
if page is not None and per_page is not None: |
|
292 |
sql += f" LIMIT {per_page} OFFSET {page * per_page}" |
|
293 |
|
|
294 |
self.cursor.execute(sql, values) |
|
295 |
certificate_rows = self.cursor.fetchall() |
|
296 |
|
|
297 |
certificates: List[Certificate] = [] |
|
298 |
for certificate_row in certificate_rows: |
|
299 |
sql = (f"SELECT {COL_USAGE_TYPE_ID} FROM {TAB_CERTIFICATE_USAGES} " |
|
300 |
f"WHERE {COL_CERTIFICATE_ID} = ?") |
|
301 |
types = [certificate_row[0]] |
|
302 |
self.cursor.execute(sql, types) |
|
303 |
usage_rows = self.cursor.fetchall() |
|
304 |
|
|
305 |
usage_dict: Dict[int, bool] = {} |
|
306 |
for usage_row in usage_rows: |
|
307 |
usage_dict[usage_row[0]] = True |
|
308 |
|
|
309 |
certificates.append(Certificate(certificate_row[0], |
|
310 |
certificate_row[1], |
|
311 |
certificate_row[2], |
|
312 |
certificate_row[3], |
|
313 |
certificate_row[4], |
|
314 |
certificate_row[7], |
|
315 |
certificate_row[8], |
|
316 |
certificate_row[9], |
|
317 |
usage_dict, |
|
318 |
certificate_row[5], |
|
319 |
certificate_row[6])) |
|
320 |
except IntegrityError: |
|
321 |
Logger.error(INTEGRITY_ERROR_MSG) |
|
322 |
raise DatabaseException(INTEGRITY_ERROR_MSG) |
|
323 |
except ProgrammingError: |
|
324 |
Logger.error(PROGRAMMING_ERROR_MSG) |
|
325 |
raise DatabaseException(PROGRAMMING_ERROR_MSG) |
|
326 |
except OperationalError: |
|
327 |
Logger.error(OPERATIONAL_ERROR_MSG) |
|
328 |
raise DatabaseException(OPERATIONAL_ERROR_MSG) |
|
329 |
except NotSupportedError: |
|
330 |
Logger.error(NOT_SUPPORTED_ERROR_MSG) |
|
331 |
raise DatabaseException(NOT_SUPPORTED_ERROR_MSG) |
|
332 |
except DatabaseError: |
|
333 |
Logger.error(DATABASE_ERROR_MSG) |
|
334 |
raise DatabaseException(DATABASE_ERROR_MSG) |
|
335 |
except Error: |
|
336 |
Logger.error(ERROR_MSG) |
|
337 |
raise DatabaseException(ERROR_MSG) |
|
338 |
|
|
339 |
return certificates |
|
340 |
|
|
341 |
def update(self, certificate_id: int, certificate: Certificate): |
|
342 |
""" |
|
343 |
Updates a certificate. |
|
344 |
If the parameter of certificate (Certificate object) is not to be changed, |
|
345 |
the same value must be specified. |
|
456 | 346 |
|
457 |
:param id: ID of a child certificate whose chain is to be queried
|
|
458 |
:type id: dict | bytes
|
|
347 |
:param certificate_id: ID of specific certificate
|
|
348 |
:param certificate: Instance of the Certificate object
|
|
459 | 349 |
|
460 |
:rtype: PemResponse
|
|
350 |
:return: the result of whether the updation was successful
|
|
461 | 351 |
""" |
462 | 352 |
|
463 |
Logger.info(f"\n\t{request.referrer}" |
|
464 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
465 |
f"\n\tCertificate ID = {id}") |
|
353 |
Logger.debug("Function launched.") |
|
466 | 354 |
|
467 | 355 |
try: |
468 |
v = int(id) |
|
469 |
except ValueError: |
|
470 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
471 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
472 |
|
|
473 |
cert = self.certificate_service.get_certificate(v) |
|
356 |
sql = (f"UPDATE {TAB_CERTIFICATES} " |
|
357 |
f"SET {COL_VALID_FROM} = ?, " |
|
358 |
f"{COL_VALID_TO} = ?, " |
|
359 |
f"{COL_PEM_DATA} = ?, " |
|
360 |
f"{COL_COMMON_NAME} = ?, " |
|
361 |
f"{COL_COUNTRY_CODE} = ?, " |
|
362 |
f"{COL_LOCALITY} = ?, " |
|
363 |
f"{COL_PROVINCE} = ?, " |
|
364 |
f"{COL_ORGANIZATION} = ?, " |
|
365 |
f"{COL_ORGANIZATIONAL_UNIT} = ?, " |
|
366 |
f"{COL_EMAIL_ADDRESS} = ?, " |
|
367 |
f"{COL_TYPE_ID} = ?, " |
|
368 |
f"{COL_PARENT_ID} = ?, " |
|
369 |
f"{COL_PRIVATE_KEY_ID} = ? " |
|
370 |
f"WHERE {COL_ID} = ?") |
|
371 |
values = [certificate.valid_from, |
|
372 |
certificate.valid_to, |
|
373 |
certificate.pem_data, |
|
374 |
certificate.common_name, |
|
375 |
certificate.country_code, |
|
376 |
certificate.locality, |
|
377 |
certificate.province, |
|
378 |
certificate.organization, |
|
379 |
certificate.organizational_unit, |
|
380 |
certificate.email_address, |
|
381 |
certificate.type_id, |
|
382 |
certificate.parent_id, |
|
383 |
certificate.private_key_id, |
|
384 |
certificate_id] |
|
385 |
|
|
386 |
self.cursor.execute(sql, values) |
|
387 |
self.connection.commit() |
|
388 |
|
|
389 |
sql = (f"DELETE FROM {TAB_CERTIFICATE_USAGES} " |
|
390 |
f"WHERE {COL_CERTIFICATE_ID} = ?") |
|
391 |
values = [certificate_id] |
|
392 |
self.cursor.execute(sql, values) |
|
393 |
self.connection.commit() |
|
394 |
|
|
395 |
check_updated = self.cursor.rowcount > 0 |
|
396 |
|
|
397 |
# iterate over usage pairs |
|
398 |
for usage_id, usage_value in certificate.usages.items(): |
|
399 |
if usage_value: |
|
400 |
sql = (f"INSERT INTO {TAB_CERTIFICATE_USAGES} " |
|
401 |
f"({COL_CERTIFICATE_ID}," |
|
402 |
f"{COL_USAGE_TYPE_ID}) " |
|
403 |
f"VALUES (?,?)") |
|
404 |
values = [certificate_id, usage_id] |
|
405 |
self.cursor.execute(sql, values) |
|
406 |
self.connection.commit() |
|
407 |
except IntegrityError: |
|
408 |
Logger.error(INTEGRITY_ERROR_MSG) |
|
409 |
raise DatabaseException(INTEGRITY_ERROR_MSG) |
|
410 |
except ProgrammingError: |
|
411 |
Logger.error(PROGRAMMING_ERROR_MSG) |
|
412 |
raise DatabaseException(PROGRAMMING_ERROR_MSG) |
|
413 |
except OperationalError: |
|
414 |
Logger.error(OPERATIONAL_ERROR_MSG) |
|
415 |
raise DatabaseException(OPERATIONAL_ERROR_MSG) |
|
416 |
except NotSupportedError: |
|
417 |
Logger.error(NOT_SUPPORTED_ERROR_MSG) |
|
418 |
raise DatabaseException(NOT_SUPPORTED_ERROR_MSG) |
|
419 |
except DatabaseError: |
|
420 |
Logger.error(DATABASE_ERROR_MSG) |
|
421 |
raise DatabaseException(DATABASE_ERROR_MSG) |
|
422 |
except Error: |
|
423 |
Logger.error(ERROR_MSG) |
|
424 |
raise DatabaseException(ERROR_MSG) |
|
425 |
|
|
426 |
return check_updated |
|
427 |
|
|
428 |
def delete(self, certificate_id: int): |
|
429 |
""" |
|
430 |
Deletes a certificate |
|
474 | 431 |
|
475 |
if cert is None: |
|
476 |
Logger.error(f"No such certificate found 'ID = {v}'.") |
|
477 |
return E_NO_CERTIFICATES_FOUND, C_NO_DATA |
|
432 |
:param certificate_id: ID of specific certificate |
|
478 | 433 |
|
479 |
if cert.parent_id is None: |
|
480 |
Logger.error(f"Parent ID is empty in certificate 'ID = {v}'.") |
|
481 |
return E_NO_CERTIFICATES_FOUND, C_NO_DATA |
|
434 |
:return: the result of whether the deletion was successful |
|
435 |
""" |
|
482 | 436 |
|
483 |
trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
|
|
437 |
Logger.debug("Function launched.")
|
|
484 | 438 |
|
485 |
ret = [] |
|
486 |
for intermediate in trust_chain: |
|
487 |
ret.append(intermediate.pem_data) |
|
439 |
try: |
|
440 |
sql = (f"UPDATE {TAB_CERTIFICATES} " |
|
441 |
f"SET {COL_DELETION_DATE} = ? " |
|
442 |
f"WHERE {COL_ID} = ? AND ({COL_DELETION_DATE} IS NULL OR {COL_DELETION_DATE} = '')") |
|
443 |
values = [int(time.time()), |
|
444 |
certificate_id] |
|
445 |
self.cursor.execute(sql, values) |
|
446 |
self.connection.commit() |
|
447 |
except IntegrityError: |
|
448 |
Logger.error(INTEGRITY_ERROR_MSG) |
|
449 |
raise DatabaseException(INTEGRITY_ERROR_MSG) |
|
450 |
except ProgrammingError: |
|
451 |
Logger.error(PROGRAMMING_ERROR_MSG) |
|
452 |
raise DatabaseException(PROGRAMMING_ERROR_MSG) |
|
453 |
except OperationalError: |
|
454 |
Logger.error(OPERATIONAL_ERROR_MSG) |
|
455 |
raise DatabaseException(OPERATIONAL_ERROR_MSG) |
|
456 |
except NotSupportedError: |
|
457 |
Logger.error(NOT_SUPPORTED_ERROR_MSG) |
|
458 |
raise DatabaseException(NOT_SUPPORTED_ERROR_MSG) |
|
459 |
except DatabaseError: |
|
460 |
Logger.error(DATABASE_ERROR_MSG) |
|
461 |
raise DatabaseException(DATABASE_ERROR_MSG) |
|
462 |
except Error: |
|
463 |
Logger.error(ERROR_MSG) |
|
464 |
raise DatabaseException(ERROR_MSG) |
|
465 |
|
|
466 |
return self.cursor.rowcount > 0 |
|
467 |
|
|
468 |
def set_certificate_revoked( |
|
469 |
self, certificate_id: int, revocation_date: str, revocation_reason: str = REV_REASON_UNSPECIFIED): |
|
470 |
""" |
|
471 |
Revoke a certificate |
|
488 | 472 |
|
489 |
return {"success": True, "data": "".join(ret)}, C_SUCCESS |
|
473 |
:param certificate_id: ID of specific certificate |
|
474 |
:param revocation_date: Date, when the certificate is revoked |
|
475 |
:param revocation_reason: Reason of the revocation |
|
490 | 476 |
|
491 |
def set_certificate_status(self, id): |
|
492 |
""" |
|
493 |
Revoke a certificate given by ID |
|
494 |
- revocation request may contain revocation reason |
|
495 |
- revocation reason is verified based on the possible predefined values |
|
496 |
- if revocation reason is not specified 'undefined' value is used |
|
497 |
:param id: Identifier of the certificate to be revoked |
|
498 |
:type id: int |
|
499 |
|
|
500 |
:rtype: SuccessResponse | ErrorResponse (see OpenAPI definition) |
|
477 |
:return: |
|
478 |
the result of whether the revocation was successful OR |
|
479 |
sqlite3.Error if an exception is thrown |
|
501 | 480 |
""" |
502 | 481 |
|
503 |
Logger.info(f"\n\t{request.referrer}" |
|
504 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
505 |
f"\n\tCertificate ID = {id}") |
|
506 |
|
|
507 |
required_keys = {STATUS} # required keys |
|
508 |
|
|
509 |
# check if the request contains a JSON body |
|
510 |
if request.is_json: |
|
511 |
request_body = request.get_json() |
|
512 |
|
|
513 |
Logger.info(f"\n\tRequest body:" |
|
514 |
f"\n{dict_to_string(request_body)}") |
|
515 |
|
|
516 |
# try to parse certificate identifier -> if it is not int return error 400 |
|
517 |
try: |
|
518 |
identifier = int(id) |
|
519 |
except ValueError: |
|
520 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
521 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
522 |
|
|
523 |
# verify that all required keys are present |
|
524 |
if not all(k in request_body for k in required_keys): |
|
525 |
Logger.error(f"Invalid request, missing parameters.") |
|
526 |
return E_MISSING_PARAMETERS, C_BAD_REQUEST |
|
527 |
|
|
528 |
# get status and reason from the request |
|
529 |
status = request_body[STATUS] |
|
530 |
reason = request_body.get(REASON, REASON_UNDEFINED) |
|
531 |
try: |
|
532 |
# set certificate status using certificate_service |
|
533 |
self.certificate_service.set_certificate_revocation_status(identifier, status, reason) |
|
534 |
except (RevocationReasonInvalidException, CertificateStatusInvalidException): |
|
535 |
# these exceptions are thrown in case invalid status or revocation reason is passed to the controller |
|
536 |
Logger.error(f"Invalid request, wrong parameters.") |
|
537 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
538 |
except CertificateAlreadyRevokedException: |
|
539 |
Logger.error(f"Certificate is already revoked 'ID = {identifier}'.") |
|
540 |
return E_NO_CERTIFICATE_ALREADY_REVOKED, C_BAD_REQUEST |
|
541 |
except CertificateNotFoundException: |
|
542 |
Logger.error(f"No such certificate found 'ID = {identifier}'.") |
|
543 |
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND |
|
544 |
except CertificateCannotBeSetToValid as e: |
|
545 |
return {"success": False, "data": str(e)}, C_BAD_REQUEST |
|
546 |
return {"success": True, |
|
547 |
"data": "Certificate status updated successfully."}, C_SUCCESS |
|
548 |
# throw an error in case the request does not contain a json body |
|
549 |
else: |
|
550 |
Logger.error(f"The request must be JSON-formatted.") |
|
551 |
return E_NOT_JSON_FORMAT, C_BAD_REQUEST |
|
552 |
|
|
553 |
def cert_to_dict_partial(self, c): |
|
554 |
""" |
|
555 |
Dictionarizes a certificate directly fetched from the database. Contains partial information. |
|
556 |
:param c: target cert |
|
557 |
:return: certificate dict (compliant with some parts of the REST API) |
|
558 |
""" |
|
482 |
Logger.debug("Function launched.") |
|
559 | 483 |
|
560 |
# TODO check log |
|
561 |
Logger.debug(f"Function launched.") |
|
562 |
|
|
563 |
c_issuer = self.certificate_service.get_certificate(c.parent_id) |
|
564 |
if c_issuer is None: |
|
565 |
return None |
|
566 |
|
|
567 |
return { |
|
568 |
ID: c.certificate_id, |
|
569 |
COMMON_NAME: c.common_name, |
|
570 |
NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(), |
|
571 |
NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(), |
|
572 |
USAGE: {CertController.INVERSE_USAGE_KEY_MAP[k]: v for k, v in c.usages.items()}, |
|
573 |
ISSUER: { |
|
574 |
ID: c_issuer.certificate_id, |
|
575 |
COMMON_NAME: c_issuer.common_name |
|
576 |
} |
|
577 |
} |
|
578 |
|
|
579 |
def cert_to_dict_full(self, c): |
|
580 |
""" |
|
581 |
Dictionarizes a certificate directly fetched from the database, but adds subject info. |
|
582 |
Contains full information. |
|
583 |
:param c: target cert |
|
584 |
:return: certificate dict (compliant with some parts of the REST API) |
|
484 |
try: |
|
485 |
if revocation_date != "" and revocation_reason == "": |
|
486 |
revocation_reason = REV_REASON_UNSPECIFIED |
|
487 |
elif revocation_date == "": |
|
488 |
return False |
|
489 |
|
|
490 |
sql = (f"UPDATE {TAB_CERTIFICATES} " |
|
491 |
f"SET {COL_REVOCATION_DATE} = ?, " |
|
492 |
f"{COL_REVOCATION_REASON} = ? " |
|
493 |
f"WHERE {COL_ID} = ? AND ({COL_REVOCATION_DATE} IS NULL OR {COL_REVOCATION_DATE} = '')") |
|
494 |
values = [revocation_date, |
|
495 |
revocation_reason, |
|
496 |
certificate_id] |
|
497 |
self.cursor.execute(sql, values) |
|
498 |
self.connection.commit() |
|
499 |
except IntegrityError: |
|
500 |
Logger.error(INTEGRITY_ERROR_MSG) |
|
501 |
raise DatabaseException(INTEGRITY_ERROR_MSG) |
|
502 |
except ProgrammingError: |
|
503 |
Logger.error(PROGRAMMING_ERROR_MSG) |
|
504 |
raise DatabaseException(PROGRAMMING_ERROR_MSG) |
|
505 |
except OperationalError: |
|
506 |
Logger.error(OPERATIONAL_ERROR_MSG) |
|
507 |
raise DatabaseException(OPERATIONAL_ERROR_MSG) |
|
508 |
except NotSupportedError: |
|
509 |
Logger.error(NOT_SUPPORTED_ERROR_MSG) |
|
510 |
raise DatabaseException(NOT_SUPPORTED_ERROR_MSG) |
|
511 |
except DatabaseError: |
|
512 |
Logger.error(DATABASE_ERROR_MSG) |
|
513 |
raise DatabaseException(DATABASE_ERROR_MSG) |
|
514 |
except Error: |
|
515 |
Logger.error(ERROR_MSG) |
|
516 |
raise DatabaseException(ERROR_MSG) |
|
517 |
|
|
518 |
return self.cursor.rowcount > 0 |
|
519 |
|
|
520 |
def clear_certificate_revocation(self, certificate_id: int): |
|
585 | 521 |
""" |
522 |
Clear revocation of a certificate |
|
586 | 523 |
|
587 |
Logger.info(f"Function launched.")
|
|
524 |
:param certificate_id: ID of specific certificate
|
|
588 | 525 |
|
589 |
subj = self.certificate_service.get_subject_from_certificate(c)
|
|
590 |
c_issuer = self.certificate_service.get_certificate(c.parent_id)
|
|
591 |
if c_issuer is None:
|
|
592 |
return None
|
|
526 |
:return:
|
|
527 |
the result of whether the clear revocation was successful OR
|
|
528 |
sqlite3.Error if an exception is thrown
|
|
529 |
"""
|
|
593 | 530 |
|
594 |
return { |
|
595 |
SUBJECT: subj.to_dict(), |
|
596 |
NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(), |
|
597 |
NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(), |
|
598 |
USAGE: {CertController.INVERSE_USAGE_KEY_MAP[k]: v for k, v in c.usages.items()}, |
|
599 |
CA: c_issuer.certificate_id |
|
600 |
} |
|
531 |
Logger.debug("Function launched.") |
|
601 | 532 |
|
602 |
def get_private_key_of_a_certificate(self, id): |
|
533 |
try: |
|
534 |
sql = (f"UPDATE {TAB_CERTIFICATES} " |
|
535 |
f"SET {COL_REVOCATION_DATE} = NULL, " |
|
536 |
f"{COL_REVOCATION_REASON} = NULL " |
|
537 |
f"WHERE {COL_ID} = ?") |
|
538 |
values = [certificate_id] |
|
539 |
self.cursor.execute(sql, values) |
|
540 |
self.connection.commit() |
|
541 |
except IntegrityError: |
|
542 |
Logger.error(INTEGRITY_ERROR_MSG) |
|
543 |
raise DatabaseException(INTEGRITY_ERROR_MSG) |
|
544 |
except ProgrammingError: |
|
545 |
Logger.error(PROGRAMMING_ERROR_MSG) |
|
546 |
raise DatabaseException(PROGRAMMING_ERROR_MSG) |
|
547 |
except OperationalError: |
|
548 |
Logger.error(OPERATIONAL_ERROR_MSG) |
|
549 |
raise DatabaseException(OPERATIONAL_ERROR_MSG) |
|
550 |
except NotSupportedError: |
|
551 |
Logger.error(NOT_SUPPORTED_ERROR_MSG) |
|
552 |
raise DatabaseException(NOT_SUPPORTED_ERROR_MSG) |
|
553 |
except DatabaseError: |
|
554 |
Logger.error(DATABASE_ERROR_MSG) |
|
555 |
raise DatabaseException(DATABASE_ERROR_MSG) |
|
556 |
except Error: |
|
557 |
Logger.error(ERROR_MSG) |
|
558 |
raise DatabaseException(ERROR_MSG) |
|
559 |
|
|
560 |
return self.cursor.rowcount > 0 |
|
561 |
|
|
562 |
def get_all_revoked_by(self, certificate_id: int): |
|
603 | 563 |
""" |
604 |
Get a private key used to sign a certificate in PEM format specified by certificate's ID
|
|
564 |
Get list of the revoked certificates that are direct descendants of the certificate with the ID
|
|
605 | 565 |
|
606 |
:param id: ID of a certificate whose private key is to be queried |
|
607 |
:type id: dict | bytes |
|
566 |
:param certificate_id: ID of specific certificate |
|
608 | 567 |
|
609 |
:rtype: PemResponse |
|
568 |
:return: |
|
569 |
list of the certificates OR |
|
570 |
None if the list is empty OR |
|
571 |
sqlite3.Error if an exception is thrown |
|
610 | 572 |
""" |
611 | 573 |
|
612 |
Logger.info(f"\n\t{request.referrer}" |
|
613 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
614 |
f"\n\tCertificate ID = {id}") |
|
574 |
Logger.debug("Function launched.") |
|
615 | 575 |
|
616 |
# try to parse the supplied ID |
|
617 | 576 |
try: |
618 |
v = int(id) |
|
619 |
except ValueError: |
|
620 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
621 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
622 |
|
|
623 |
# find a certificate using the given ID |
|
624 |
cert = self.certificate_service.get_certificate(v) |
|
625 |
|
|
626 |
if cert is None: |
|
627 |
Logger.error(f"No such certificate found 'ID = {v}'.") |
|
628 |
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND |
|
629 |
else: |
|
630 |
# certificate exists, fetch it's private key |
|
631 |
private_key = self.key_service.get_key(cert.private_key_id) |
|
632 |
if cert is None: |
|
633 |
Logger.error(f"Internal server error (certificate's private key cannot be found).") |
|
634 |
return E_NO_CERT_PRIVATE_KEY_FOUND, C_INTERNAL_SERVER_ERROR |
|
635 |
else: |
|
636 |
return {"success": True, "data": private_key.private_key}, C_SUCCESS |
|
637 |
|
|
638 |
def get_public_key_of_a_certificate(self, id): |
|
577 |
sql = (f"SELECT * FROM {TAB_CERTIFICATES} " |
|
578 |
f"WHERE {COL_PARENT_ID} = ? AND {COL_REVOCATION_DATE} IS NOT NULL AND {COL_REVOCATION_DATE} != ''") |
|
579 |
values = [certificate_id] |
|
580 |
self.cursor.execute(sql, values) |
|
581 |
certificate_rows = self.cursor.fetchall() |
|
582 |
|
|
583 |
certificates: List[Certificate] = [] |
|
584 |
for certificate_row in certificate_rows: |
|
585 |
sql = (f"SELECT * FROM {TAB_CERTIFICATE_USAGES} " |
|
586 |
f"WHERE {COL_CERTIFICATE_ID} = ?") |
|
587 |
values = [certificate_row[0]] |
|
588 |
self.cursor.execute(sql, values) |
|
589 |
usage_rows = self.cursor.fetchall() |
|
590 |
|
|
591 |
usage_dict: Dict[int, bool] = {} |
|
592 |
for usage_row in usage_rows: |
|
593 |
usage_dict[usage_row[2]] = True |
|
594 |
|
|
595 |
certificates.append(Certificate(certificate_row[0], # ID |
|
596 |
certificate_row[1], # valid from |
|
597 |
certificate_row[2], # valid to |
|
598 |
certificate_row[3], # pem data |
|
599 |
certificate_row[14], # type ID |
|
600 |
certificate_row[15], # parent ID |
|
601 |
certificate_row[16], # private key ID |
|
602 |
usage_dict, |
|
603 |
certificate_row[4], # common name |
|
604 |
certificate_row[5], # country code |
|
605 |
certificate_row[6], # locality |
|
606 |
certificate_row[7], # province |
|
607 |
certificate_row[8], # organization |
|
608 |
certificate_row[9], # organizational unit |
|
609 |
certificate_row[10], # email address |
|
610 |
certificate_row[11], # revocation date |
|
611 |
certificate_row[12])) # revocation reason |
|
612 |
except IntegrityError: |
|
613 |
Logger.error(INTEGRITY_ERROR_MSG) |
|
614 |
raise DatabaseException(INTEGRITY_ERROR_MSG) |
|
615 |
except ProgrammingError: |
|
616 |
Logger.error(PROGRAMMING_ERROR_MSG) |
|
617 |
raise DatabaseException(PROGRAMMING_ERROR_MSG) |
|
618 |
except OperationalError: |
|
619 |
Logger.error(OPERATIONAL_ERROR_MSG) |
|
620 |
raise DatabaseException(OPERATIONAL_ERROR_MSG) |
|
621 |
except NotSupportedError: |
|
622 |
Logger.error(NOT_SUPPORTED_ERROR_MSG) |
|
623 |
raise DatabaseException(NOT_SUPPORTED_ERROR_MSG) |
|
624 |
except DatabaseError: |
|
625 |
Logger.error(DATABASE_ERROR_MSG) |
|
626 |
raise DatabaseException(DATABASE_ERROR_MSG) |
|
627 |
except Error: |
|
628 |
Logger.error(ERROR_MSG) |
|
629 |
raise DatabaseException(ERROR_MSG) |
|
630 |
|
|
631 |
return certificates |
|
632 |
|
|
633 |
def get_all_issued_by(self, certificate_id: int): |
|
639 | 634 |
""" |
640 |
Get a public key of a certificate in PEM format specified by certificate's ID
|
|
635 |
Get list of the certificates that are direct descendants of the certificate with the ID
|
|
641 | 636 |
|
642 |
:param id: ID of a certificate whose public key is to be queried |
|
643 |
:type id: dict | bytes |
|
637 |
:param certificate_id: ID of specific certificate |
|
644 | 638 |
|
645 |
:rtype: PemResponse |
|
639 |
:return: |
|
640 |
list of the certificates OR |
|
641 |
None if the list is empty OR |
|
642 |
sqlite3.Error if an exception is thrown |
|
646 | 643 |
""" |
647 | 644 |
|
648 |
Logger.info(f"\n\t{request.referrer}" |
|
649 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
650 |
f"\n\tCertificate ID = {id}") |
|
645 |
Logger.debug("Function launched.") |
|
651 | 646 |
|
652 |
# try to parse the supplied ID |
|
653 | 647 |
try: |
654 |
v = int(id) |
|
655 |
except ValueError: |
|
656 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
657 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
658 |
|
|
659 |
# find a certificate using the given ID |
|
660 |
cert = self.certificate_service.get_certificate(v) |
|
661 |
|
|
662 |
if cert is None: |
|
663 |
Logger.error(f"No such certificate found 'ID = {v}'.") |
|
664 |
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND |
|
665 |
else: |
|
666 |
return {"success": True, "data": self.certificate_service.get_public_key_from_certificate(cert)}, C_SUCCESS |
|
667 |
|
|
668 |
def delete_certificate(self, id): |
|
648 |
sql = (f"SELECT * FROM {TAB_CERTIFICATES} " |
|
649 |
f"WHERE {COL_PARENT_ID} = ? AND {COL_ID} != ? AND " |
|
650 |
f"({COL_DELETION_DATE} IS NULL OR {COL_DELETION_DATE} = '')") |
|
651 |
values = [certificate_id, certificate_id] |
|
652 |
self.cursor.execute(sql, values) |
|
653 |
certificate_rows = self.cursor.fetchall() |
|
654 |
|
|
655 |
certificates: List[Certificate] = [] |
|
656 |
for certificate_row in certificate_rows: |
|
657 |
sql = (f"SELECT * FROM {TAB_CERTIFICATE_USAGES} " |
|
658 |
f"WHERE {COL_CERTIFICATE_ID} = ?") |
|
659 |
values = [certificate_row[0]] |
|
660 |
self.cursor.execute(sql, values) |
|
661 |
usage_rows = self.cursor.fetchall() |
|
662 |
|
|
663 |
usage_dict: Dict[int, bool] = {} |
|
664 |
for usage_row in usage_rows: |
|
665 |
usage_dict[usage_row[2]] = True |
|
666 |
|
|
667 |
certificates.append(Certificate(certificate_row[0], # ID |
|
668 |
certificate_row[1], # valid from |
|
669 |
certificate_row[2], # valid to |
|
670 |
certificate_row[3], # pem data |
|
671 |
certificate_row[14], # type ID |
|
672 |
certificate_row[15], # parent ID |
|
673 |
certificate_row[16], # private key ID |
|
674 |
usage_dict, |
|
675 |
certificate_row[4], # common name |
|
676 |
certificate_row[5], # country code |
|
677 |
certificate_row[6], # locality |
|
678 |
certificate_row[7], # province |
|
679 |
certificate_row[8], # organization |
|
680 |
certificate_row[9], # organizational unit |
|
681 |
certificate_row[10], # email address |
|
682 |
certificate_row[11], # revocation date |
|
683 |
certificate_row[12])) # revocation reason |
|
684 |
except IntegrityError: |
|
685 |
Logger.error(INTEGRITY_ERROR_MSG) |
|
686 |
raise DatabaseException(INTEGRITY_ERROR_MSG) |
|
687 |
except ProgrammingError: |
|
688 |
Logger.error(PROGRAMMING_ERROR_MSG) |
|
689 |
raise DatabaseException(PROGRAMMING_ERROR_MSG) |
|
690 |
except OperationalError: |
|
691 |
Logger.error(OPERATIONAL_ERROR_MSG) |
|
692 |
raise DatabaseException(OPERATIONAL_ERROR_MSG) |
|
693 |
except NotSupportedError: |
|
694 |
Logger.error(NOT_SUPPORTED_ERROR_MSG) |
|
695 |
raise DatabaseException(NOT_SUPPORTED_ERROR_MSG) |
|
696 |
except DatabaseError: |
|
697 |
Logger.error(DATABASE_ERROR_MSG) |
|
698 |
raise DatabaseException(DATABASE_ERROR_MSG) |
|
699 |
except Error: |
|
700 |
Logger.error(ERROR_MSG) |
|
701 |
raise DatabaseException(ERROR_MSG) |
|
702 |
|
|
703 |
return certificates |
|
704 |
|
|
705 |
def get_all_issued_by_filter(self, issuer_id, target_types, target_usages, target_cn_substring, page, per_page): |
|
669 | 706 |
""" |
670 |
Deletes a certificate identified by ID, including its corresponding subtree (all descendants). |
|
671 |
:param id: target certificate ID |
|
672 |
:rtype: DeleteResponse |
|
707 |
Get list of the certificates that are direct descendants of the certificate with the ID |
|
708 |
|
|
709 |
:param target_types: certificate types (filter) |
|
710 |
:param target_usages: certificate usages (filter) |
|
711 |
:param target_cn_substring: certificate CN substring (filter) |
|
712 |
:param page: target page |
|
713 |
:param per_page: target page size |
|
714 |
:param issuer_id: ID of specific certificate |
|
715 |
|
|
716 |
:return: |
|
717 |
list of the certificates OR |
|
718 |
None if the list is empty |
|
673 | 719 |
""" |
674 | 720 |
|
675 |
Logger.info(f"\n\t{request.referrer}" |
|
676 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
677 |
f"\n\tCertificate ID = {id}") |
|
721 |
Logger.debug("Function launched.") |
|
678 | 722 |
|
679 | 723 |
try: |
680 |
v = int(id) |
|
681 |
except ValueError: |
|
682 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
683 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
724 |
values = [issuer_id, issuer_id] |
|
725 |
values += list(target_types) |
|
726 |
values += list(target_usages) |
|
727 |
|
|
728 |
sql = ( |
|
729 |
f"SELECT a.{COL_ID}, {COL_COMMON_NAME}, {COL_VALID_FROM}, {COL_VALID_TO}, {COL_PEM_DATA}, " |
|
730 |
f"{COL_REVOCATION_DATE}, {COL_REVOCATION_REASON}, {COL_PRIVATE_KEY_ID}, {COL_TYPE_ID}, {COL_PARENT_ID} " |
|
731 |
f"FROM {TAB_CERTIFICATES} a " |
|
732 |
f"WHERE (a.{COL_DELETION_DATE} IS NULL OR a.{COL_DELETION_DATE} = '') " |
|
733 |
f"AND a.{COL_PARENT_ID} = ? AND a.{COL_ID} != ? " |
|
734 |
f"AND a.{COL_TYPE_ID} IN ({','.join('?' * len(target_types))}) " |
|
735 |
f"AND (SELECT COUNT(*) FROM {TAB_CERTIFICATE_USAGES} " |
|
736 |
f"WHERE {COL_CERTIFICATE_ID} = a.{COL_ID} " |
|
737 |
f"AND {COL_USAGE_TYPE_ID} IN ({','.join('?' * len(target_usages))}) " |
|
738 |
f") > 0 " |
|
739 |
) |
|
684 | 740 |
|
685 |
try: |
|
686 |
self.certificate_service.delete_certificate(v) |
|
687 |
except CertificateNotFoundException: |
|
688 |
Logger.error(f"No such certificate found 'ID = {v}'.") |
|
689 |
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND |
|
690 |
except DatabaseException: |
|
691 |
Logger.error(f"Internal server error (corrupted database).") |
|
692 |
return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR |
|
693 |
except CertificateStatusInvalidException or RevocationReasonInvalidException or UnknownException: |
|
694 |
Logger.error(f"Internal server error (unknown origin).") |
|
695 |
return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR |
|
696 |
|
|
697 |
return {"success": True, "data": "The certificate and its descendants have been successfully deleted."} |
|
698 |
|
|
699 |
def generate_certificate_pkcs_identity(self, id): |
|
741 |
if target_cn_substring is not None: |
|
742 |
sql += f" AND a.{COL_COMMON_NAME} LIKE '%' || ? || '%'" |
|
743 |
|
|
744 |
values += [target_cn_substring] |
|
745 |
|
|
746 |
if page is not None and per_page is not None: |
|
747 |
sql += f" LIMIT {per_page} OFFSET {page * per_page}" |
|
748 |
|
|
749 |
self.cursor.execute(sql, values) |
|
750 |
certificate_rows = self.cursor.fetchall() |
|
751 |
|
|
752 |
certificates: List[Certificate] = [] |
|
753 |
for certificate_row in certificate_rows: |
|
754 |
sql = (f"SELECT * FROM {TAB_CERTIFICATE_USAGES} " |
|
755 |
f"WHERE {COL_CERTIFICATE_ID} = ?") |
|
756 |
values = [certificate_row[0]] |
|
757 |
self.cursor.execute(sql, values) |
|
758 |
usage_rows = self.cursor.fetchall() |
|
759 |
|
|
760 |
usage_dict: Dict[int, bool] = {} |
|
761 |
for usage_row in usage_rows: |
|
762 |
usage_dict[usage_row[2]] = True |
|
763 |
|
|
764 |
certificates.append(Certificate(certificate_row[0], |
|
765 |
certificate_row[1], |
|
766 |
certificate_row[2], |
|
767 |
certificate_row[3], |
|
768 |
certificate_row[4], |
|
769 |
certificate_row[7], |
|
770 |
certificate_row[8], |
|
771 |
certificate_row[9], |
|
772 |
usage_dict, |
|
773 |
certificate_row[5], |
|
774 |
certificate_row[6])) |
|
775 |
except IntegrityError: |
|
776 |
Logger.error(INTEGRITY_ERROR_MSG) |
|
777 |
raise DatabaseException(INTEGRITY_ERROR_MSG) |
|
778 |
except ProgrammingError: |
|
779 |
Logger.error(PROGRAMMING_ERROR_MSG) |
|
780 |
raise DatabaseException(PROGRAMMING_ERROR_MSG) |
|
781 |
except OperationalError: |
|
782 |
Logger.error(OPERATIONAL_ERROR_MSG) |
|
783 |
raise DatabaseException(OPERATIONAL_ERROR_MSG) |
|
784 |
except NotSupportedError: |
|
785 |
Logger.error(NOT_SUPPORTED_ERROR_MSG) |
|
786 |
raise DatabaseException(NOT_SUPPORTED_ERROR_MSG) |
|
787 |
except DatabaseError: |
|
788 |
Logger.error(DATABASE_ERROR_MSG) |
|
789 |
raise DatabaseException(DATABASE_ERROR_MSG) |
|
790 |
except Error: |
|
791 |
Logger.error(ERROR_MSG) |
|
792 |
raise DatabaseException(ERROR_MSG) |
|
793 |
|
|
794 |
return certificates |
|
795 |
|
|
796 |
def get_all_descendants_of(self, certificate_id: int): |
|
700 | 797 |
""" |
701 |
Generates a PKCS12 identity (including the chain of trust) of the certificate given by the specified ID. |
|
702 |
Response is of application/x-pkcs12 type. |
|
703 |
|
|
704 |
:param id: ID of a certificate whose PKCS12 identity should be generated |
|
705 |
:type id: int |
|
706 |
|
|
707 |
:rtype: Response |
|
798 |
Get a list of all certificates C such that the certificate identified by "certificate_id" belongs to a trust chain |
|
799 |
between C and its root certificate authority (i.e. is an ancestor of C). |
|
800 |
:param certificate_id: target certificate ID |
|
801 |
:return: list of all descendants |
|
708 | 802 |
""" |
709 | 803 |
|
710 |
Logger.info(f"\n\t{request.referrer}" |
|
711 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
712 |
f"\n\tCertificate ID = {id}") |
|
804 |
Logger.debug("Function launched.") |
|
713 | 805 |
|
714 |
# try to parse the supplied ID |
|
715 | 806 |
try: |
716 |
v = int(id) |
|
717 |
except ValueError: |
|
718 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}] (expected integer).") |
|
719 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
720 |
|
|
721 |
# find a certificate using the given ID |
|
722 |
cert = self.certificate_service.get_certificate(v) |
|
723 |
|
|
724 |
if request.is_json: # accept JSON only |
|
725 |
body = request.get_json() |
|
726 |
|
|
727 |
# check whether the request is well formed meaning that it contains all required fields |
|
728 |
if NAME not in body.keys(): |
|
729 |
return E_IDENTITY_NAME_NOT_SPECIFIED, C_BAD_REQUEST |
|
730 |
|
|
731 |
if PASSWORD not in body.keys(): |
|
732 |
return E_IDENTITY_PASSWORD_NOT_SPECIFIED, C_BAD_REQUEST |
|
807 |
def dfs(children_of, this, collection: list): |
|
808 |
for child in children_of(this.certificate_id): |
|
809 |
dfs(children_of, child, collection) |
|
810 |
collection.append(this) |
|
811 |
|
|
812 |
subtree_root = self.read(certificate_id) |
|
813 |
if subtree_root is None: |
|
814 |
return None |
|
815 |
|
|
816 |
all_certs = [] |
|
817 |
dfs(self.get_all_issued_by, subtree_root, all_certs) |
|
818 |
except IntegrityError: |
|
819 |
Logger.error(INTEGRITY_ERROR_MSG) |
|
820 |
raise DatabaseException(INTEGRITY_ERROR_MSG) |
|
821 |
except ProgrammingError: |
|
822 |
Logger.error(PROGRAMMING_ERROR_MSG) |
|
823 |
raise DatabaseException(PROGRAMMING_ERROR_MSG) |
|
824 |
except OperationalError: |
|
825 |
Logger.error(OPERATIONAL_ERROR_MSG) |
|
826 |
raise DatabaseException(OPERATIONAL_ERROR_MSG) |
|
827 |
except NotSupportedError: |
|
828 |
Logger.error(NOT_SUPPORTED_ERROR_MSG) |
|
829 |
raise DatabaseException(NOT_SUPPORTED_ERROR_MSG) |
|
830 |
except DatabaseError: |
|
831 |
Logger.error(DATABASE_ERROR_MSG) |
|
832 |
raise DatabaseException(DATABASE_ERROR_MSG) |
|
833 |
except Error: |
|
834 |
Logger.error(ERROR_MSG) |
|
835 |
raise DatabaseException(ERROR_MSG) |
Také k dispozici: Unified diff
[Merge conflict] - reverted controller version from #8702