Revize 364a6830
Přidáno uživatelem Jan Pašek před téměř 4 roky(ů)
src/controllers/certificates_controller.py | ||
---|---|---|
1 |
import time
|
|
2 |
from sqlite3 import Connection, Error, DatabaseError, IntegrityError, ProgrammingError, OperationalError, \
|
|
3 |
NotSupportedError
|
|
4 |
from typing import Dict, List, Set
|
|
1 |
import json
|
|
2 |
from datetime import datetime
|
|
3 |
from itertools import chain
|
|
4 |
from json import JSONDecodeError
|
|
5 | 5 |
|
6 |
from src.exceptions.database_exception import DatabaseException
|
|
6 |
from flask import request, Response
|
|
7 | 7 |
from injector import inject |
8 |
from src.constants import * |
|
9 |
from src.model.certificate import Certificate |
|
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 |
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 |
|
10 | 22 |
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 |
|
|
29 |
FILTERING = "filtering" |
|
30 |
PAGE = "page" |
|
31 |
PER_PAGE = "per_page" |
|
32 |
ISSUER = "issuer" |
|
33 |
US = "usage" |
|
34 |
NOT_AFTER = "notAfter" |
|
35 |
NOT_BEFORE = "notBefore" |
|
36 |
COMMON_NAME = "CN" |
|
37 |
ID = "id" |
|
38 |
CA = "CA" |
|
39 |
USAGE = "usage" |
|
40 |
SUBJECT = "subject" |
|
41 |
VALIDITY_DAYS = "validityDays" |
|
42 |
TYPE = "type" |
|
43 |
ISSUED_BY = "issuedby" |
|
44 |
STATUS = "status" |
|
45 |
REASON = "reason" |
|
46 |
REASON_UNDEFINED = "unspecified" |
|
47 |
NAME = "name" |
|
48 |
PASSWORD = "password" |
|
49 |
|
|
50 |
E_NO_ISSUER_FOUND = {"success": False, "data": "No certificate authority with such unique ID exists."} |
|
51 |
E_NO_CERTIFICATES_FOUND = {"success": False, "data": "No such certificate found."} |
|
52 |
E_NO_CERTIFICATE_ALREADY_REVOKED = {"success": False, "data": "Certificate is already revoked."} |
|
53 |
E_NO_CERT_PRIVATE_KEY_FOUND = {"success": False, |
|
54 |
"data": "Internal server error (certificate's private key cannot be found)."} |
|
55 |
E_NOT_JSON_FORMAT = {"success": False, "data": "The request must be JSON-formatted."} |
|
56 |
E_CORRUPTED_DATABASE = {"success": False, "data": "Internal server error (corrupted database)."} |
|
57 |
E_GENERAL_ERROR = {"success": False, "data": "Internal server error (unknown origin)."} |
|
58 |
E_MISSING_PARAMETERS = {"success": False, "data": "Invalid request, missing parameters."} |
|
59 |
E_WRONG_PARAMETERS = {"success": False, "data": "Invalid request, wrong parameters."} |
|
60 |
E_IDENTITY_NAME_NOT_SPECIFIED = {"success": False, "data": "Invalid request, missing identity name."} |
|
61 |
E_IDENTITY_PASSWORD_NOT_SPECIFIED = {"success": False, "data": "Invalid request, missing identity password."} |
|
62 |
|
|
63 |
|
|
64 |
class CertController: |
|
65 |
USAGE_KEY_MAP = {'CA': CA_ID, 'SSL': SSL_ID, 'digitalSignature': SIGNATURE_ID, 'authentication': AUTHENTICATION_ID} |
|
66 |
INVERSE_USAGE_KEY_MAP = {k: v for v, k in USAGE_KEY_MAP.items()} |
|
67 |
FILTERING_TYPE_KEY_MAP = {'root': ROOT_CA_ID, 'inter': INTERMEDIATE_CA_ID, 'end': CERTIFICATE_ID} |
|
68 |
# INVERSE_FILTERING_TYPE_KEY_MAP = {k: v for v, k in FILTERING_TYPE_KEY_MAP.items()} |
|
69 |
|
|
11 | 70 |
|
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." |
|
71 |
@inject |
|
72 |
def __init__(self, certificate_service: CertificateService, key_service: KeyService): |
|
73 |
self.certificate_service = certificate_service |
|
74 |
self.key_service = key_service |
|
18 | 75 |
|
76 |
def create_certificate(self): |
|
77 |
"""create new certificate |
|
19 | 78 |
|
20 |
class CertificateRepository:
|
|
79 |
Create a new certificate based on given information
|
|
21 | 80 |
|
22 |
@inject |
|
23 |
def __init__(self, connection: Connection): |
|
24 |
""" |
|
25 |
Constructor of the CertificateRepository object |
|
81 |
:param body: Certificate data to be created |
|
82 |
:type body: dict | bytes |
|
26 | 83 |
|
27 |
:param connection: Instance of the Connection object
|
|
84 |
:rtype: CreatedResponse
|
|
28 | 85 |
""" |
29 |
self.connection = connection |
|
30 |
self.cursor = connection.cursor() |
|
31 | 86 |
|
32 |
def create(self, certificate: Certificate): |
|
87 |
Logger.info(f"\n\t{request.referrer}" |
|
88 |
f"\n\t{request.method} {request.path} {request.scheme}") |
|
89 |
|
|
90 |
required_keys = {SUBJECT, USAGE, VALIDITY_DAYS} # required fields of the POST req |
|
91 |
|
|
92 |
if request.is_json: # accept JSON only |
|
93 |
body = request.get_json() |
|
94 |
|
|
95 |
Logger.info(f"\n\tRequest body:" |
|
96 |
f"\n{dict_to_string(body)}") |
|
97 |
|
|
98 |
if not all(k in body for k in required_keys): # verify that all keys are present |
|
99 |
Logger.error(f"Invalid request, missing parameters") |
|
100 |
return E_MISSING_PARAMETERS, C_BAD_REQUEST |
|
101 |
|
|
102 |
if not isinstance(body[VALIDITY_DAYS], int): # type checking |
|
103 |
Logger.error(f"Invalid request, wrong parameter '{VALIDITY_DAYS}'.") |
|
104 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
105 |
|
|
106 |
subject = Subject.from_dict(body[SUBJECT]) # generate Subject from passed dict |
|
107 |
|
|
108 |
if subject is None: # if the format is incorrect |
|
109 |
Logger.error(f"Invalid request, wrong parameter '{SUBJECT}'.") |
|
110 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
111 |
|
|
112 |
usages_dict = {} |
|
113 |
|
|
114 |
if not isinstance(body[USAGE], dict): # type checking |
|
115 |
Logger.error(f"Invalid request, wrong parameter '{USAGE}'.") |
|
116 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
117 |
|
|
118 |
for k, v in body[USAGE].items(): # for each usage |
|
119 |
if k not in CertController.USAGE_KEY_MAP: # check that it is a valid usage |
|
120 |
Logger.error(f"Invalid request, wrong parameter '{USAGE}'[{k}].") |
|
121 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST # and throw if it is not |
|
122 |
usages_dict[CertController.USAGE_KEY_MAP[k]] = v # otherwise translate key and set |
|
123 |
|
|
124 |
key = self.key_service.create_new_key() # TODO pass key |
|
125 |
|
|
126 |
extensions = "" |
|
127 |
if EXTENSIONS in body: |
|
128 |
extensions = body[EXTENSIONS] |
|
129 |
|
|
130 |
try: |
|
131 |
if CA not in body or body[CA] is None: # if issuer omitted (legal) or none |
|
132 |
cert = self.certificate_service.create_root_ca( # create a root CA |
|
133 |
key, |
|
134 |
subject, |
|
135 |
usages=usages_dict, # TODO ignoring usages -> discussion |
|
136 |
days=body[VALIDITY_DAYS], |
|
137 |
extensions=extensions |
|
138 |
) |
|
139 |
else: |
|
140 |
issuer = self.certificate_service.get_certificate(body[CA]) # get base issuer info |
|
141 |
|
|
142 |
if issuer is None: # if such issuer does not exist |
|
143 |
Logger.error(f"No certificate authority with such unique ID exists 'ID = {key.private_key_id}'.") |
|
144 |
self.key_service.delete_key(key.private_key_id) # free |
|
145 |
return E_NO_ISSUER_FOUND, C_BAD_REQUEST # and throw |
|
146 |
|
|
147 |
issuer_key = self.key_service.get_key(issuer.private_key_id) # get issuer's key, which must exist |
|
148 |
|
|
149 |
if issuer_key is None: # if it does not |
|
150 |
Logger.error(f"Internal server error (corrupted database).") |
|
151 |
self.key_service.delete_key(key.private_key_id) # free |
|
152 |
return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR # and throw |
|
153 |
|
|
154 |
f = self.certificate_service.create_ca if CA_ID in usages_dict and usages_dict[CA_ID] else \ |
|
155 |
self.certificate_service.create_end_cert |
|
156 |
|
|
157 |
# noinspection PyArgumentList |
|
158 |
cert = f( # create inter CA or end cert |
|
159 |
key, # according to whether 'CA' is among |
|
160 |
subject, # the usages' fields |
|
161 |
issuer, |
|
162 |
issuer_key, |
|
163 |
usages=usages_dict, |
|
164 |
days=body[VALIDITY_DAYS], |
|
165 |
extensions=extensions |
|
166 |
) |
|
167 |
except CryptographyException as e: |
|
168 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
169 |
|
|
170 |
if cert is not None: |
|
171 |
return {"success": True, |
|
172 |
"data": cert.certificate_id}, C_CREATED_SUCCESSFULLY |
|
173 |
else: # if this fails, then |
|
174 |
Logger.error(f"Internal error: The certificate could not have been created.") |
|
175 |
self.key_service.delete_key(key.private_key_id) # free |
|
176 |
return {"success": False, # and wonder what the cause is, |
|
177 |
"data": "Internal error: The certificate could not have been created."}, C_BAD_REQUEST |
|
178 |
# as obj/None carries only one bit |
|
179 |
# of error information |
|
180 |
else: |
|
181 |
Logger.error(f"The request must be JSON-formatted.") |
|
182 |
return E_NOT_JSON_FORMAT, C_BAD_REQUEST # throw in case of non-JSON format |
|
183 |
|
|
184 |
def get_certificate_by_id(self, id): |
|
185 |
"""get certificate by ID |
|
186 |
|
|
187 |
Get certificate in PEM format by ID |
|
188 |
|
|
189 |
:param id: ID of a certificate to be queried |
|
190 |
:type id: dict | bytes |
|
191 |
|
|
192 |
:rtype: PemResponse |
|
33 | 193 |
""" |
34 |
Creates a certificate. |
|
35 |
For root certificate (CA) the parent certificate id is modified to the same id (id == parent_id). |
|
36 | 194 |
|
37 |
:param certificate: Instance of the Certificate object |
|
195 |
Logger.info(f"\n\t{request.referrer}" |
|
196 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
197 |
f"\n\tCertificate ID = {id}") |
|
198 |
try: |
|
199 |
v = int(id) |
|
200 |
except ValueError: |
|
201 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
202 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
203 |
|
|
204 |
cert = self.certificate_service.get_certificate(v) |
|
38 | 205 |
|
39 |
:return: the result of whether the creation was successful |
|
40 |
""" |
|
206 |
if cert is None: |
|
207 |
Logger.error(f"No such certificate found 'ID = {v}'.") |
|
208 |
return E_NO_CERTIFICATES_FOUND, C_NO_DATA |
|
209 |
else: |
|
210 |
return {"success": True, "data": cert.pem_data}, C_SUCCESS |
|
41 | 211 |
|
42 |
Logger.debug("Function launched.") |
|
212 |
def get_certificate_details_by_id(self, id): |
|
213 |
"""get certificate's details by ID |
|
43 | 214 |
|
44 |
try: |
|
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. |
|
215 |
Get certificate details by ID |
|
115 | 216 |
|
116 |
:param certificate_id: ID of specific certificate |
|
217 |
:param id: ID of a certificate whose details are to be queried |
|
218 |
:type id: dict | bytes |
|
117 | 219 |
|
118 |
:return: instance of the Certificate object
|
|
220 |
:rtype: CertificateResponse
|
|
119 | 221 |
""" |
120 | 222 |
|
121 |
Logger.debug("Function launched.") |
|
223 |
Logger.info(f"\n\t{request.referrer}" |
|
224 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
225 |
f"\n\tCertificate ID = {id}") |
|
122 | 226 |
|
123 | 227 |
try: |
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): |
|
182 |
""" |
|
183 |
Reads (selects) all certificates (with type). |
|
228 |
v = int(id) |
|
229 |
except ValueError: |
|
230 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
231 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
184 | 232 |
|
185 |
:param filter_type: ID of certificate type from CertificateTypes table
|
|
233 |
cert = self.certificate_service.get_certificate(v)
|
|
186 | 234 |
|
187 |
:return: list of certificates |
|
188 |
""" |
|
235 |
if cert is None: |
|
236 |
Logger.error(f"No such certificate found 'ID = {v}'.") |
|
237 |
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND |
|
189 | 238 |
|
190 |
Logger.debug("Function launched.") |
|
239 |
data = self.cert_to_dict_full(cert) |
|
240 |
if data is None: |
|
241 |
return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR |
|
191 | 242 |
|
192 | 243 |
try: |
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 |
""" |
|
244 |
state = self.certificate_service.get_certificate_state(v) |
|
245 |
data["status"] = state |
|
246 |
except CertificateNotFoundException: |
|
247 |
Logger.error(f"No such certificate found 'ID = {id}'.") |
|
266 | 248 |
|
267 |
Logger.debug("Function launched.")
|
|
249 |
return {"success": True, "data": data}, C_SUCCESS
|
|
268 | 250 |
|
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 |
) |
|
251 |
def get_certificate_list(self): |
|
252 |
"""get list of certificates |
|
253 |
|
|
254 |
Lists certificates based on provided filtering options |
|
285 | 255 |
|
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): |
|
256 |
:param filtering: Filter certificate type to be queried |
|
257 |
:type filtering: dict | bytes |
|
258 |
|
|
259 |
:rtype: CertificateListResponse |
|
342 | 260 |
""" |
343 |
Updates a certificate. |
|
344 |
If the parameter of certificate (Certificate object) is not to be changed, |
|
345 |
the same value must be specified. |
|
346 | 261 |
|
347 |
:param certificate_id: ID of specific certificate |
|
348 |
:param certificate: Instance of the Certificate object |
|
262 |
Logger.info(f"\n\t{request.referrer}" |
|
263 |
f"\n\t{request.method} {request.path} {request.scheme}") |
|
264 |
|
|
265 |
|
|
266 |
# the filtering parameter can be read as URL argument or as a request body |
|
267 |
if request.is_json: |
|
268 |
data = request.get_json() |
|
269 |
else: |
|
270 |
data = {} |
|
271 |
|
|
272 |
if FILTERING in request.args.keys(): |
|
273 |
try: |
|
274 |
data[FILTERING] = json.loads(request.args[FILTERING]) |
|
275 |
except JSONDecodeError: |
|
276 |
Logger.error(f"The request must be JSON-formatted.") |
|
277 |
return E_NOT_JSON_FORMAT, C_BAD_REQUEST |
|
278 |
|
|
279 |
if PAGE in request.args.keys(): |
|
280 |
try: |
|
281 |
data[PAGE] = json.loads(request.args[PAGE]) |
|
282 |
except JSONDecodeError: |
|
283 |
Logger.error(f"The request must be JSON-formatted.") |
|
284 |
return E_NOT_JSON_FORMAT, C_BAD_REQUEST |
|
285 |
|
|
286 |
if PER_PAGE in request.args.keys(): |
|
287 |
try: |
|
288 |
data[PER_PAGE] = json.loads(request.args[PER_PAGE]) |
|
289 |
except JSONDecodeError: |
|
290 |
Logger.error(f"The request must be JSON-formatted.") |
|
291 |
return E_NOT_JSON_FORMAT, C_BAD_REQUEST |
|
292 |
|
|
293 |
Logger.info(f"\n\tRequest body:" |
|
294 |
f"\n{dict_to_string(data)}") |
|
295 |
|
|
296 |
target_types = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID} |
|
297 |
target_usages = {v for v in CertController.INVERSE_USAGE_KEY_MAP.keys()} |
|
298 |
target_cn_substring = None |
|
299 |
issuer_id = -1 |
|
300 |
|
|
301 |
unfiltered = True |
|
302 |
|
|
303 |
if PER_PAGE in data: |
|
304 |
unfiltered = False |
|
305 |
page = data.get(PAGE, 0) |
|
306 |
per_page = data[PER_PAGE] |
|
307 |
else: |
|
308 |
page = None |
|
309 |
per_page = None |
|
310 |
|
|
311 |
if FILTERING in data: # if the 'filtering' field exists |
|
312 |
unfiltered = False |
|
313 |
if isinstance(data[FILTERING], dict): # and it is also a 'dict' |
|
314 |
|
|
315 |
# noinspection DuplicatedCode |
|
316 |
if TYPE in data[FILTERING]: # containing 'type' |
|
317 |
if isinstance(data[FILTERING][TYPE], list): # which is a 'list', |
|
318 |
# map every field to id |
|
319 |
try: |
|
320 |
target_types = {CertController.FILTERING_TYPE_KEY_MAP[v] for v in data[FILTERING][TYPE]} |
|
321 |
except KeyError as e: |
|
322 |
Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{TYPE}' - '{e}'.") |
|
323 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
324 |
else: |
|
325 |
Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{TYPE}'.") |
|
326 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
327 |
|
|
328 |
# noinspection DuplicatedCode |
|
329 |
if USAGE in data[FILTERING]: # containing 'usage' |
|
330 |
if isinstance(data[FILTERING][USAGE], list): # which is a 'list', |
|
331 |
# map every field to id |
|
332 |
try: |
|
333 |
target_usages = {CertController.USAGE_KEY_MAP[v] for v in data[FILTERING][USAGE]} |
|
334 |
except KeyError as e: |
|
335 |
Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{USAGE}' - '{e}'.") |
|
336 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
337 |
else: |
|
338 |
Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{USAGE}'.") |
|
339 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
340 |
|
|
341 |
if COMMON_NAME in data[FILTERING]: # containing 'CN' |
|
342 |
if isinstance(data[FILTERING][COMMON_NAME], str): # which is a 'str' |
|
343 |
target_cn_substring = data[FILTERING][COMMON_NAME] |
|
344 |
else: |
|
345 |
Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{COMMON_NAME}'.") |
|
346 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
347 |
|
|
348 |
if ISSUED_BY in data[FILTERING]: # containing 'issuedby' |
|
349 |
if isinstance(data[FILTERING][ISSUED_BY], int): # which is an 'int' |
|
350 |
issuer_id = data[FILTERING][ISSUED_BY] # then get its children only |
|
351 |
|
|
352 |
else: |
|
353 |
Logger.error(f"Invalid request, wrong parameters '{FILTERING}'.") |
|
354 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
355 |
|
|
356 |
if unfiltered: # if not filtering |
|
357 |
certs = self.certificate_service.get_certificates() |
|
358 |
elif issuer_id >= 0: # if filtering by an issuer |
|
359 |
try: |
|
360 |
# get his children, filtered |
|
361 |
certs = self.certificate_service.get_certificates_issued_by_filter( |
|
362 |
issuer_id=issuer_id, |
|
363 |
target_types=target_types, |
|
364 |
target_usages=target_usages, |
|
365 |
target_cn_substring=target_cn_substring, |
|
366 |
page=page, |
|
367 |
per_page=per_page |
|
368 |
) |
|
369 |
except CertificateNotFoundException: # if id does not exist |
|
370 |
Logger.error(f"No such certificate found 'ID = {issuer_id}'.") |
|
371 |
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND # throw |
|
372 |
else: |
|
373 |
certs = self.certificate_service.get_certificates_filter( |
|
374 |
target_types=target_types, |
|
375 |
target_usages=target_usages, |
|
376 |
target_cn_substring=target_cn_substring, |
|
377 |
page=page, |
|
378 |
per_page=per_page |
|
379 |
) |
|
349 | 380 |
|
350 |
:return: the result of whether the updation was successful |
|
381 |
if certs is None: |
|
382 |
Logger.error(f"Internal server error (unknown origin).") |
|
383 |
return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR |
|
384 |
elif len(certs) == 0: |
|
385 |
# TODO check log level |
|
386 |
Logger.warning(f"No such certificate found (empty list).") |
|
387 |
return {"success": True, "data": []}, C_SUCCESS |
|
388 |
else: |
|
389 |
ret = [] |
|
390 |
for c in certs: |
|
391 |
data = self.cert_to_dict_partial(c) |
|
392 |
if data is None: |
|
393 |
Logger.error(f"Internal server error (corrupted database).") |
|
394 |
return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR |
|
395 |
ret.append( |
|
396 |
data |
|
397 |
) |
|
398 |
return {"success": True, "data": ret}, C_SUCCESS |
|
399 |
|
|
400 |
def get_certificate_root_by_id(self, id): |
|
401 |
"""get certificate's root of trust chain by ID |
|
402 |
|
|
403 |
Get certificate's root of trust chain in PEM format by ID |
|
404 |
|
|
405 |
:param id: ID of a child certificate whose root is to be queried |
|
406 |
:type id: dict | bytes |
|
407 |
|
|
408 |
:rtype: PemResponse |
|
351 | 409 |
""" |
352 | 410 |
|
353 |
Logger.debug("Function launched.") |
|
411 |
Logger.info(f"\n\t{request.referrer}" |
|
412 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
413 |
f"\n\tCertificate ID = {id}") |
|
354 | 414 |
|
355 | 415 |
try: |
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 |
|
416 |
v = int(id) |
|
417 |
except ValueError: |
|
418 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
419 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
431 | 420 |
|
432 |
:param certificate_id: ID of specific certificate
|
|
421 |
cert = self.certificate_service.get_certificate(v)
|
|
433 | 422 |
|
434 |
:return: the result of whether the deletion was successful |
|
435 |
""" |
|
423 |
if cert is None: |
|
424 |
Logger.error(f"No such certificate found 'ID = {v}'.") |
|
425 |
return E_NO_CERTIFICATES_FOUND, C_NO_DATA |
|
436 | 426 |
|
437 |
Logger.debug("Function launched.") |
|
427 |
trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False) |
|
428 |
if trust_chain is None or len(trust_chain) == 0: |
|
429 |
Logger.error(f"No such certificate found (empty list).") |
|
430 |
return E_NO_CERTIFICATES_FOUND, C_NO_DATA |
|
438 | 431 |
|
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 |
|
432 |
return {"success": True, "data": trust_chain[-1].pem_data}, C_SUCCESS |
|
472 | 433 |
|
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 |
|
434 |
def get_certificate_trust_chain_by_id(self, id): |
|
435 |
"""get certificate's trust chain by ID (including root certificate) |
|
476 | 436 |
|
477 |
:return: |
|
478 |
the result of whether the revocation was successful OR |
|
479 |
sqlite3.Error if an exception is thrown |
|
437 |
Get certificate trust chain in PEM format by ID |
|
438 |
|
|
439 |
:param id: ID of a child certificate whose chain is to be queried |
|
440 |
:type id: dict | bytes |
|
441 |
|
|
442 |
:rtype: PemResponse |
|
480 | 443 |
""" |
481 | 444 |
|
482 |
Logger.debug("Function launched.") |
|
445 |
Logger.info(f"\n\t{request.referrer}" |
|
446 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
447 |
f"\n\tCertificate ID = {id}") |
|
483 | 448 |
|
484 | 449 |
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): |
|
521 |
""" |
|
522 |
Clear revocation of a certificate |
|
450 |
v = int(id) |
|
451 |
except ValueError: |
|
452 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
453 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
523 | 454 |
|
524 |
:param certificate_id: ID of specific certificate
|
|
455 |
cert = self.certificate_service.get_certificate(v)
|
|
525 | 456 |
|
526 |
:return: |
|
527 |
the result of whether the clear revocation was successful OR |
|
528 |
sqlite3.Error if an exception is thrown |
|
529 |
""" |
|
457 |
if cert is None: |
|
458 |
Logger.error(f"No such certificate found 'ID = {v}'.") |
|
459 |
return E_NO_CERTIFICATES_FOUND, C_NO_DATA |
|
530 | 460 |
|
531 |
Logger.debug("Function launched.") |
|
461 |
if cert.parent_id is None: |
|
462 |
Logger.error(f"Parent ID is empty in certificate 'ID = {v}'.") |
|
463 |
return E_NO_CERTIFICATES_FOUND, C_NO_DATA |
|
532 | 464 |
|
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): |
|
465 |
trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False) |
|
466 |
|
|
467 |
ret = [] |
|
468 |
for intermediate in trust_chain: |
|
469 |
ret.append(intermediate.pem_data) |
|
470 |
|
|
471 |
return {"success": True, "data": "".join(ret)}, C_SUCCESS |
|
472 |
|
|
473 |
def set_certificate_status(self, id): |
|
474 |
""" |
|
475 |
Revoke a certificate given by ID |
|
476 |
- revocation request may contain revocation reason |
|
477 |
- revocation reason is verified based on the possible predefined values |
|
478 |
- if revocation reason is not specified 'undefined' value is used |
|
479 |
:param id: Identifier of the certificate to be revoked |
|
480 |
:type id: int |
|
481 |
|
|
482 |
:rtype: SuccessResponse | ErrorResponse (see OpenAPI definition) |
|
563 | 483 |
""" |
564 |
Get list of the revoked certificates that are direct descendants of the certificate with the ID |
|
565 | 484 |
|
566 |
:param certificate_id: ID of specific certificate |
|
485 |
Logger.info(f"\n\t{request.referrer}" |
|
486 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
487 |
f"\n\tCertificate ID = {id}") |
|
488 |
|
|
489 |
required_keys = {STATUS} # required keys |
|
490 |
|
|
491 |
# check if the request contains a JSON body |
|
492 |
if request.is_json: |
|
493 |
request_body = request.get_json() |
|
494 |
|
|
495 |
Logger.info(f"\n\tRequest body:" |
|
496 |
f"\n{dict_to_string(request_body)}") |
|
497 |
|
|
498 |
# try to parse certificate identifier -> if it is not int return error 400 |
|
499 |
try: |
|
500 |
identifier = int(id) |
|
501 |
except ValueError: |
|
502 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
503 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
504 |
|
|
505 |
# verify that all required keys are present |
|
506 |
if not all(k in request_body for k in required_keys): |
|
507 |
Logger.error(f"Invalid request, missing parameters.") |
|
508 |
return E_MISSING_PARAMETERS, C_BAD_REQUEST |
|
509 |
|
|
510 |
# get status and reason from the request |
|
511 |
status = request_body[STATUS] |
|
512 |
reason = request_body.get(REASON, REASON_UNDEFINED) |
|
513 |
try: |
|
514 |
# set certificate status using certificate_service |
|
515 |
self.certificate_service.set_certificate_revocation_status(identifier, status, reason) |
|
516 |
except (RevocationReasonInvalidException, CertificateStatusInvalidException): |
|
517 |
# these exceptions are thrown in case invalid status or revocation reason is passed to the controller |
|
518 |
Logger.error(f"Invalid request, wrong parameters.") |
|
519 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
520 |
except CertificateAlreadyRevokedException: |
|
521 |
Logger.error(f"Certificate is already revoked 'ID = {identifier}'.") |
|
522 |
return E_NO_CERTIFICATE_ALREADY_REVOKED, C_BAD_REQUEST |
|
523 |
except CertificateNotFoundException: |
|
524 |
Logger.error(f"No such certificate found 'ID = {identifier}'.") |
|
525 |
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND |
|
526 |
except CertificateCannotBeSetToValid as e: |
|
527 |
return {"success": False, "data": str(e)}, C_BAD_REQUEST |
|
528 |
return {"success": True, |
|
529 |
"data": "Certificate status updated successfully."}, C_SUCCESS |
|
530 |
# throw an error in case the request does not contain a json body |
|
531 |
else: |
|
532 |
Logger.error(f"The request must be JSON-formatted.") |
|
533 |
return E_NOT_JSON_FORMAT, C_BAD_REQUEST |
|
534 |
|
|
535 |
def cert_to_dict_partial(self, c): |
|
536 |
""" |
|
537 |
Dictionarizes a certificate directly fetched from the database. Contains partial information. |
|
538 |
:param c: target cert |
|
539 |
:return: certificate dict (compliant with some parts of the REST API) |
|
540 |
""" |
|
567 | 541 |
|
568 |
:return: |
|
569 |
list of the certificates OR |
|
570 |
None if the list is empty OR |
|
571 |
sqlite3.Error if an exception is thrown |
|
542 |
# TODO check log |
|
543 |
Logger.debug(f"Function launched.") |
|
544 |
|
|
545 |
c_issuer = self.certificate_service.get_certificate(c.parent_id) |
|
546 |
if c_issuer is None: |
|
547 |
return None |
|
548 |
|
|
549 |
return { |
|
550 |
ID: c.certificate_id, |
|
551 |
COMMON_NAME: c.common_name, |
|
552 |
NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(), |
|
553 |
NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(), |
|
554 |
USAGE: {CertController.INVERSE_USAGE_KEY_MAP[k]: v for k, v in c.usages.items()}, |
|
555 |
ISSUER: { |
|
556 |
ID: c_issuer.certificate_id, |
|
557 |
COMMON_NAME: c_issuer.common_name |
|
558 |
} |
|
559 |
} |
|
560 |
|
|
561 |
def cert_to_dict_full(self, c): |
|
562 |
""" |
|
563 |
Dictionarizes a certificate directly fetched from the database, but adds subject info. |
|
564 |
Contains full information. |
|
565 |
:param c: target cert |
|
566 |
:return: certificate dict (compliant with some parts of the REST API) |
|
572 | 567 |
""" |
573 | 568 |
|
574 |
Logger.debug("Function launched.")
|
|
569 |
Logger.info(f"Function launched.")
|
|
575 | 570 |
|
576 |
try: |
|
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): |
|
571 |
subj = self.certificate_service.get_subject_from_certificate(c) |
|
572 |
c_issuer = self.certificate_service.get_certificate(c.parent_id) |
|
573 |
if c_issuer is None: |
|
574 |
return None |
|
575 |
|
|
576 |
return { |
|
577 |
SUBJECT: subj.to_dict(), |
|
578 |
NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(), |
|
579 |
NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(), |
|
580 |
USAGE: {CertController.INVERSE_USAGE_KEY_MAP[k]: v for k, v in c.usages.items()}, |
|
581 |
CA: c_issuer.certificate_id |
|
582 |
} |
|
583 |
|
|
584 |
def get_private_key_of_a_certificate(self, id): |
|
634 | 585 |
""" |
635 |
Get list of the certificates that are direct descendants of the certificate with the ID
|
|
586 |
Get a private key used to sign a certificate in PEM format specified by certificate's ID
|
|
636 | 587 |
|
637 |
:param certificate_id: ID of specific certificate |
|
588 |
:param id: ID of a certificate whose private key is to be queried |
|
589 |
:type id: dict | bytes |
|
638 | 590 |
|
639 |
:return: |
|
640 |
list of the certificates OR |
|
641 |
None if the list is empty OR |
|
642 |
sqlite3.Error if an exception is thrown |
|
591 |
:rtype: PemResponse |
|
643 | 592 |
""" |
644 | 593 |
|
645 |
Logger.debug("Function launched.") |
|
594 |
Logger.info(f"\n\t{request.referrer}" |
|
595 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
596 |
f"\n\tCertificate ID = {id}") |
|
646 | 597 |
|
598 |
# try to parse the supplied ID |
|
647 | 599 |
try: |
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): |
|
600 |
v = int(id) |
|
601 |
except ValueError: |
|
602 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
603 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
604 |
|
|
605 |
# find a certificate using the given ID |
|
606 |
cert = self.certificate_service.get_certificate(v) |
|
607 |
|
|
608 |
if cert is None: |
|
609 |
Logger.error(f"No such certificate found 'ID = {v}'.") |
|
610 |
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND |
|
611 |
else: |
|
612 |
# certificate exists, fetch it's private key |
|
613 |
private_key = self.key_service.get_key(cert.private_key_id) |
|
614 |
if cert is None: |
|
615 |
Logger.error(f"Internal server error (certificate's private key cannot be found).") |
|
616 |
return E_NO_CERT_PRIVATE_KEY_FOUND, C_INTERNAL_SERVER_ERROR |
|
617 |
else: |
|
618 |
return {"success": True, "data": private_key.private_key}, C_SUCCESS |
|
619 |
|
|
620 |
def get_public_key_of_a_certificate(self, id): |
|
706 | 621 |
""" |
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 |
|
622 |
Get a public key of a certificate in PEM format specified by certificate's ID |
|
623 |
|
|
624 |
:param id: ID of a certificate whose public key is to be queried |
|
625 |
:type id: dict | bytes |
|
626 |
|
|
627 |
:rtype: PemResponse |
|
719 | 628 |
""" |
720 | 629 |
|
721 |
Logger.debug("Function launched.") |
|
630 |
Logger.info(f"\n\t{request.referrer}" |
|
631 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
632 |
f"\n\tCertificate ID = {id}") |
|
722 | 633 |
|
634 |
# try to parse the supplied ID |
|
723 | 635 |
try: |
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 |
) |
|
636 |
v = int(id) |
|
637 |
except ValueError: |
|
638 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
639 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
640 |
|
|
641 |
# find a certificate using the given ID |
|
642 |
cert = self.certificate_service.get_certificate(v) |
|
643 |
|
|
644 |
if cert is None: |
|
645 |
Logger.error(f"No such certificate found 'ID = {v}'.") |
|
646 |
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND |
|
647 |
else: |
|
648 |
return {"success": True, "data": self.certificate_service.get_public_key_from_certificate(cert)}, C_SUCCESS |
|
740 | 649 |
|
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): |
|
650 |
def delete_certificate(self, id): |
|
797 | 651 |
""" |
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 |
|
652 |
Deletes a certificate identified by ID, including its corresponding subtree (all descendants). |
|
653 |
:param id: target certificate ID |
|
654 |
:rtype: DeleteResponse |
|
802 | 655 |
""" |
803 | 656 |
|
804 |
Logger.debug("Function launched.") |
|
657 |
Logger.info(f"\n\t{request.referrer}" |
|
658 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
659 |
f"\n\tCertificate ID = {id}") |
|
805 | 660 |
|
806 | 661 |
try: |
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) |
|
836 |
|
|
837 |
return all_certs |
|
838 |
|
|
839 |
def get_next_id(self) -> int: |
|
662 |
v = int(id) |
|
663 |
except ValueError: |
|
664 |
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].") |
|
665 |
return E_WRONG_PARAMETERS, C_BAD_REQUEST |
|
666 |
|
|
667 |
try: |
|
668 |
self.certificate_service.delete_certificate(v) |
|
669 |
except CertificateNotFoundException: |
|
670 |
Logger.error(f"No such certificate found 'ID = {v}'.") |
|
671 |
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND |
|
672 |
except DatabaseException: |
|
673 |
Logger.error(f"Internal server error (corrupted database).") |
|
674 |
return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR |
|
675 |
except CertificateStatusInvalidException or RevocationReasonInvalidException or UnknownException: |
|
676 |
Logger.error(f"Internal server error (unknown origin).") |
|
677 |
return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR |
|
678 |
|
|
679 |
return {"success": True, "data": "The certificate and its descendants have been successfully deleted."} |
|
680 |
|
|
681 |
def generate_certificate_pkcs_identity(self, id): |
|
840 | 682 |
""" |
841 |
Get identifier of the next certificate that will be inserted into the database |
|
842 |
:return: identifier of the next certificate that will be added into the database |
|
683 |
Generates a PKCS12 identity (including the chain of trust) of the certificate given by the specified ID. |
|
684 |
Response is of application/x-pkcs12 type. |
|
685 |
|
|
686 |
:param id: ID of a certificate whose PKCS12 identity should be generated |
|
687 |
:type id: int |
|
688 |
|
|
689 |
:rtype: Response |
|
843 | 690 |
""" |
844 | 691 |
|
845 |
Logger.debug("Function launched.") |
|
692 |
Logger.info(f"\n\t{request.referrer}" |
|
693 |
f"\n\t{request.method} {request.path} {request.scheme}" |
|
694 |
f"\n\tCertificate ID = {id}") |
|
846 | 695 |
|
696 |
# try to parse the supplied ID |
|
847 | 697 |
try: |
848 |
# get next IDs of all tables |
|
849 |
self.cursor.execute("SELECT * FROM SQLITE_SEQUENCE") |
|
850 |
results = self.cursor.fetchall() |
|
851 |
|
|
852 |
# search for next ID in Certificates table and return it |
|
853 |
for result in results: |
|
854 |
if result[0] == TAB_CERTIFICATES: |
|
855 |
return result[1] + 1 # current last id + 1 |
|
856 |
# if certificates table is not present in the query results, return 1 |
|
857 |
except IntegrityError: |
|
858 |
Logger.error(INTEGRITY_ERROR_MSG) |
|
859 |
raise DatabaseException(INTEGRITY_ERROR_MSG) |
|
860 |
except ProgrammingError: |
|
861 |
Logger.error(PROGRAMMING_ERROR_MSG) |
|
862 |
raise DatabaseException(PROGRAMMING_ERROR_MSG) |
|
863 |
except OperationalError: |
|
864 |
Logger.error(OPERATIONAL_ERROR_MSG) |
|
865 |
raise DatabaseException(OPERATIONAL_ERROR_MSG) |
|
866 |
except NotSupportedError: |
|
867 |
Logger.error(NOT_SUPPORTED_ERROR_MSG) |
|
868 |
raise DatabaseException(NOT_SUPPORTED_ERROR_MSG) |
|
869 |
except DatabaseError: |
|
870 |
Logger.error(DATABASE_ERROR_MSG) |
|
871 |
raise DatabaseException(DATABASE_ERROR_MSG) |
|
872 |
except Error: |
Také k dispozici: Unified diff
[Merge conflict] - reverted controller version from #8702