]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/security/cert_generators/file/certificate_db.cc
5320da7434837256d0ede786502aeece1cacdf8c
2 * Copyright (C) 1996-2019 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
10 #include "base/HardFun.h"
11 #include "security/cert_generators/file/certificate_db.h"
27 #define HERE "(security_file_certgen) " << __FILE__ << ':' << __LINE__ << ": "
29 Ssl::Lock::Lock(std::string
const &aFilename
) :
32 hFile(INVALID_HANDLE_VALUE
)
39 bool Ssl::Lock::locked() const
42 return hFile
!= INVALID_HANDLE_VALUE
;
48 void Ssl::Lock::lock()
52 hFile
= CreateFile(TEXT(filename
.c_str()), GENERIC_READ
, 0, NULL
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
53 if (hFile
== INVALID_HANDLE_VALUE
)
55 fd
= open(filename
.c_str(), O_RDWR
);
58 throw std::runtime_error("Failed to open file " + filename
);
61 if (!LockFile(hFile
, 0, 0, 1, 0))
63 if (lockf(fd
, F_LOCK
, 0) != 0)
65 if (flock(fd
, LOCK_EX
) != 0)
67 throw std::runtime_error("Failed to get a lock of " + filename
);
70 void Ssl::Lock::unlock()
73 if (hFile
!= INVALID_HANDLE_VALUE
) {
74 UnlockFile(hFile
, 0, 0, 1, 0);
76 hFile
= INVALID_HANDLE_VALUE
;
81 lockf(fd
, F_ULOCK
, 0);
90 throw std::runtime_error("Lock is already unlocked for " + filename
);
99 Ssl::Locker::Locker(Lock
&aLock
, const char *aFileName
, int aLineNo
):
100 weLocked(false), lock(aLock
), fileName(aFileName
), lineNo(aLineNo
)
102 if (!lock
.locked()) {
108 Ssl::Locker::~Locker()
114 Ssl::CertificateDb::Row::Row()
117 row
= (char **)OPENSSL_malloc(sizeof(char *) * (width
+ 1));
118 for (size_t i
= 0; i
< width
+ 1; ++i
)
122 Ssl::CertificateDb::Row::Row(char **aRow
, size_t aWidth
): width(aWidth
)
127 Ssl::CertificateDb::Row::~Row()
133 if ((max
= (void *)row
[width
]) != NULL
) {
134 // It is an openSSL allocated row. The TXT_DB_read function stores the
135 // index and row items one one memory segment. The row[width] points
136 // to the end of buffer. We have to check for items in the array which
137 // are not stored in this segment. These items should released.
138 for (size_t i
= 0; i
< width
+ 1; ++i
) {
139 if (((row
[i
] < (char *)row
) || (row
[i
] > max
)) && (row
[i
] != NULL
))
140 OPENSSL_free(row
[i
]);
143 for (size_t i
= 0; i
< width
+ 1; ++i
) {
145 OPENSSL_free(row
[i
]);
151 void Ssl::CertificateDb::Row::reset()
156 void Ssl::CertificateDb::Row::setValue(size_t cell
, char const * value
)
158 assert(cell
< width
);
163 row
[cell
] = static_cast<char *>(OPENSSL_malloc(sizeof(char) * (strlen(value
) + 1)));
164 memcpy(row
[cell
], value
, sizeof(char) * (strlen(value
) + 1));
169 char ** Ssl::CertificateDb::Row::getRow()
174 void Ssl::CertificateDb::sq_TXT_DB_delete(TXT_DB
*db
, const char **row
)
179 #if SQUID_SSLTXTDB_PSTRINGDATA
180 for (int i
= 0; i
< sk_OPENSSL_PSTRING_num(db
->data
); ++i
) {
181 #if SQUID_STACKOF_PSTRINGDATA_HACK
182 const char ** current_row
= ((const char **)sk_value(CHECKED_STACK_OF(OPENSSL_PSTRING
, db
->data
), i
));
184 const char ** current_row
= ((const char **)sk_OPENSSL_PSTRING_value(db
->data
, i
));
187 for (int i
= 0; i
< sk_num(db
->data
); ++i
) {
188 const char ** current_row
= ((const char **)sk_value(db
->data
, i
));
190 if (current_row
== row
) {
191 sq_TXT_DB_delete_row(db
, i
);
197 #define countof(arr) (sizeof(arr)/sizeof(*arr))
198 void Ssl::CertificateDb::sq_TXT_DB_delete_row(TXT_DB
*db
, int idx
) {
200 #if SQUID_SSLTXTDB_PSTRINGDATA
201 rrow
= (char **)sk_OPENSSL_PSTRING_delete(db
->data
, idx
);
203 rrow
= (char **)sk_delete(db
->data
, idx
);
209 Row
row(rrow
, cnlNumber
); // row wrapper used to free the rrow
211 const Columns db_indexes
[]= {cnlSerial
, cnlKey
};
212 for (unsigned int i
= 0; i
< countof(db_indexes
); ++i
) {
214 #if SQUID_SSLTXTDB_PSTRINGDATA
215 if (LHASH_OF(OPENSSL_STRING
) *fieldIndex
= db
->index
[db_indexes
[i
]])
216 data
= lh_OPENSSL_STRING_delete(fieldIndex
, rrow
);
218 if (LHASH
*fieldIndex
= db
->index
[db_indexes
[i
]])
219 data
= OPENSSL_LH_delete(fieldIndex
, rrow
);
222 assert(data
== rrow
);
226 unsigned long Ssl::CertificateDb::index_serial_hash(const char **a
) {
227 const char *n
= a
[Ssl::CertificateDb::cnlSerial
];
230 return OPENSSL_LH_strhash(n
);
233 int Ssl::CertificateDb::index_serial_cmp(const char **a
, const char **b
) {
235 for (aa
= a
[Ssl::CertificateDb::cnlSerial
]; *aa
== '0'; ++aa
);
236 for (bb
= b
[Ssl::CertificateDb::cnlSerial
]; *bb
== '0'; ++bb
);
237 return strcmp(aa
, bb
);
240 unsigned long Ssl::CertificateDb::index_name_hash(const char **a
) {
241 return(OPENSSL_LH_strhash(a
[Ssl::CertificateDb::cnlKey
]));
244 int Ssl::CertificateDb::index_name_cmp(const char **a
, const char **b
) {
245 return(strcmp(a
[Ssl::CertificateDb::cnlKey
], b
[CertificateDb::cnlKey
]));
248 const std::string
Ssl::CertificateDb::db_file("index.txt");
249 const std::string
Ssl::CertificateDb::cert_dir("certs");
250 const std::string
Ssl::CertificateDb::size_file("size");
252 Ssl::CertificateDb::CertificateDb(std::string
const & aDb_path
, size_t aMax_db_size
, size_t aFs_block_size
)
254 db_full(aDb_path
+ "/" + db_file
),
255 cert_full(aDb_path
+ "/" + cert_dir
),
256 size_full(aDb_path
+ "/" + size_file
),
257 max_db_size(aMax_db_size
),
258 fs_block_size((aFs_block_size
? aFs_block_size
: 2048)),
263 Ssl::CertificateDb::find(std::string
const &key
, const Security::CertPointer
&expectedOrig
, Security::CertPointer
&cert
, Security::PrivateKeyPointer
&pkey
)
265 const Locker
locker(dbLock
, Here
);
267 return pure_find(key
, expectedOrig
, cert
, pkey
);
270 bool Ssl::CertificateDb::purgeCert(std::string
const & key
) {
271 const Locker
locker(dbLock
, Here
);
276 if (!deleteByKey(key
))
284 Ssl::CertificateDb::addCertAndPrivateKey(std::string
const &useKey
, const Security::CertPointer
&cert
, const Security::PrivateKeyPointer
&pkey
, const Security::CertPointer
&orig
)
286 const Locker
locker(dbLock
, Here
);
288 if (!db
|| !cert
|| !pkey
)
294 // Functor to wrap xfree() for std::unique_ptr
295 typedef HardFun
<void, const void*, &xfree
> CharDeleter
;
298 ASN1_INTEGER
* ai
= X509_get_serialNumber(cert
.get());
299 std::string serial_string
;
300 Ssl::BIGNUM_Pointer
serial(ASN1_INTEGER_to_BN(ai
, NULL
));
302 std::unique_ptr
<char, CharDeleter
> hex_bn(BN_bn2hex(serial
.get()));
303 serial_string
= std::string(hex_bn
.get());
305 row
.setValue(cnlSerial
, serial_string
.c_str());
306 char ** rrow
= TXT_DB_get_by_index(db
.get(), cnlSerial
, row
.getRow());
307 // We are creating certificates with unique serial numbers. If the serial
308 // number is found in the database, the same certificate is already stored.
310 // TODO: check if the stored row is valid.
314 // Remove any entry with given key
317 // check db size while trying to minimize calls to size()
318 size_t dbSize
= size();
319 if ((dbSize
== 0 && hasRows()) ||
320 (dbSize
> 0 && !hasRows()) ||
321 (dbSize
> 10 * max_db_size
)) {
322 // Invalid database size, rebuild
323 dbSize
= rebuildSize();
325 while (dbSize
> max_db_size
&& deleteInvalidCertificate()) {
326 dbSize
= size(); // get the current database size
327 // and try to find another invalid certificate if needed
329 // there are no more invalid ones, but there must be valid certificates
330 while (dbSize
> max_db_size
) {
331 if (!deleteOldestCertificate()) {
332 rebuildSize(); // No certificates in database.Update the size file.
333 save(); // Some entries may have been removed. Update the index file.
334 return false; // errors prevented us from freeing enough space
336 dbSize
= size(); // get the current database size
339 const auto tm
= X509_getm_notAfter(cert
.get());
340 row
.setValue(cnlExp_date
, std::string(reinterpret_cast<char *>(tm
->data
), tm
->length
).c_str());
341 std::unique_ptr
<char, CharDeleter
> subject(X509_NAME_oneline(X509_get_subject_name(cert
.get()), nullptr, 0));
342 row
.setValue(cnlName
, subject
.get());
343 row
.setValue(cnlKey
, useKey
.c_str());
345 if (!TXT_DB_insert(db
.get(), row
.getRow())) {
346 // failed to add index (???) but we may have already modified
347 // the database so save before exit
354 std::string
filename(cert_full
+ "/" + serial_string
+ ".pem");
355 if (!WriteEntry(filename
.c_str(), cert
, pkey
, orig
)) {
356 //remove row from txt_db and save
357 sq_TXT_DB_delete(db
.get(), (const char **)rrow
);
368 Ssl::CertificateDb::Create(std::string
const & db_path
) {
370 throw std::runtime_error("Path to db is empty");
371 std::string
db_full(db_path
+ "/" + db_file
);
372 std::string
cert_full(db_path
+ "/" + cert_dir
);
373 std::string
size_full(db_path
+ "/" + size_file
);
375 if (mkdir(db_path
.c_str(), 0777))
376 throw std::runtime_error("Cannot create " + db_path
);
378 if (mkdir(cert_full
.c_str(), 0777))
379 throw std::runtime_error("Cannot create " + cert_full
);
381 std::ofstream
size(size_full
.c_str());
385 throw std::runtime_error("Cannot open " + size_full
+ " to open");
386 std::ofstream
db(db_full
.c_str());
388 throw std::runtime_error("Cannot open " + db_full
+ " to open");
392 Ssl::CertificateDb::Check(std::string
const & db_path
, size_t max_db_size
, size_t fs_block_size
) {
393 CertificateDb
db(db_path
, max_db_size
, fs_block_size
);
396 // Call readSize to force rebuild size file in the case it is corrupted
400 size_t Ssl::CertificateDb::rebuildSize()
403 #if SQUID_SSLTXTDB_PSTRINGDATA
404 for (int i
= 0; i
< sk_OPENSSL_PSTRING_num(db
.get()->data
); ++i
) {
405 #if SQUID_STACKOF_PSTRINGDATA_HACK
406 const char ** current_row
= ((const char **)sk_value(CHECKED_STACK_OF(OPENSSL_PSTRING
, db
.get()->data
), i
));
408 const char ** current_row
= ((const char **)sk_OPENSSL_PSTRING_value(db
.get()->data
, i
));
411 for (int i
= 0; i
< sk_num(db
.get()->data
); ++i
) {
412 const char ** current_row
= ((const char **)sk_value(db
.get()->data
, i
));
414 const std::string
filename(cert_full
+ "/" + current_row
[cnlSerial
] + ".pem");
415 const size_t fSize
= getFileSize(filename
);
423 Ssl::CertificateDb::pure_find(std::string
const &key
, const Security::CertPointer
&expectedOrig
, Security::CertPointer
&cert
, Security::PrivateKeyPointer
&pkey
)
429 row
.setValue(cnlKey
, key
.c_str());
431 char **rrow
= TXT_DB_get_by_index(db
.get(), cnlKey
, row
.getRow());
435 if (!sslDateIsInTheFuture(rrow
[cnlExp_date
]))
438 Security::CertPointer storedOrig
;
439 // read cert and pkey from file.
440 std::string
filename(cert_full
+ "/" + rrow
[cnlSerial
] + ".pem");
441 if (!ReadEntry(filename
.c_str(), cert
, pkey
, storedOrig
))
444 if (!storedOrig
&& !expectedOrig
)
447 return Ssl::CertificatesCmp(expectedOrig
, storedOrig
);
450 size_t Ssl::CertificateDb::size() {
454 void Ssl::CertificateDb::addSize(std::string
const & filename
) {
455 // readSize will rebuild 'size' file if missing or it is corrupted
456 size_t dbSize
= readSize();
457 dbSize
+= getFileSize(filename
);
461 void Ssl::CertificateDb::subSize(std::string
const & filename
) {
462 // readSize will rebuild 'size' file if missing or it is corrupted
463 size_t dbSize
= readSize();
464 const size_t fileSize
= getFileSize(filename
);
465 dbSize
= dbSize
> fileSize
? dbSize
- fileSize
: 0;
469 size_t Ssl::CertificateDb::readSize() {
470 std::ifstream
ifstr(size_full
.c_str());
472 if (!ifstr
|| !(ifstr
>> db_size
))
473 return rebuildSize();
477 void Ssl::CertificateDb::writeSize(size_t db_size
) {
478 std::ofstream
ofstr(size_full
.c_str());
480 throw std::runtime_error("cannot write \"" + size_full
+ "\" file");
484 size_t Ssl::CertificateDb::getFileSize(std::string
const & filename
) {
485 std::ifstream
file(filename
.c_str(), std::ios::binary
);
488 file
.seekg(0, std::ios_base::end
);
489 const std::streampos file_size
= file
.tellg();
492 return ((static_cast<size_t>(file_size
) + fs_block_size
- 1) / fs_block_size
) * fs_block_size
;
495 void Ssl::CertificateDb::load() {
496 // Load db from file.
497 Ssl::BIO_Pointer
in(BIO_new(BIO_s_file()));
498 if (!in
|| BIO_read_filename(in
.get(), db_full
.c_str()) <= 0)
499 throw std::runtime_error("Uninitialized SSL certificate database directory: " + db_path
+ ". To initialize, run \"security_file_certgen -c -s " + db_path
+ "\".");
501 bool corrupt
= false;
502 Ssl::TXT_DB_Pointer
temp_db(TXT_DB_read(in
.get(), cnlNumber
));
506 // Create indexes in db.
507 if (!corrupt
&& !TXT_DB_create_index(temp_db
.get(), cnlSerial
, NULL
, LHASH_HASH_FN(index_serial_hash
), LHASH_COMP_FN(index_serial_cmp
)))
510 if (!corrupt
&& !TXT_DB_create_index(temp_db
.get(), cnlKey
, NULL
, LHASH_HASH_FN(index_name_hash
), LHASH_COMP_FN(index_name_cmp
)))
514 throw std::runtime_error("The SSL certificate database " + db_path
+ " is corrupted. Please rebuild");
516 db
.reset(temp_db
.release());
519 void Ssl::CertificateDb::save() {
521 throw std::runtime_error("The certificates database is not loaded");;
523 // To save the db to file, create a new BIO with BIO file methods.
524 Ssl::BIO_Pointer
out(BIO_new(BIO_s_file()));
525 if (!out
|| !BIO_write_filename(out
.get(), const_cast<char *>(db_full
.c_str())))
526 throw std::runtime_error("Failed to initialize " + db_full
+ " file for writing");;
528 if (TXT_DB_write(out
.get(), db
.get()) < 0)
529 throw std::runtime_error("Failed to write " + db_full
+ " file");
532 // Normally defined in defines.h file
533 void Ssl::CertificateDb::deleteRow(const char **row
, int rowIndex
) {
534 const std::string
filename(cert_full
+ "/" + row
[cnlSerial
] + ".pem");
535 sq_TXT_DB_delete_row(db
.get(), rowIndex
);
538 int ret
= remove(filename
.c_str());
539 if (ret
< 0 && errno
!= ENOENT
)
540 throw std::runtime_error("Failed to remove certficate file " + filename
+ " from db");
543 bool Ssl::CertificateDb::deleteInvalidCertificate() {
547 bool removed_one
= false;
548 #if SQUID_SSLTXTDB_PSTRINGDATA
549 for (int i
= 0; i
< sk_OPENSSL_PSTRING_num(db
.get()->data
); ++i
) {
550 #if SQUID_STACKOF_PSTRINGDATA_HACK
551 const char ** current_row
= ((const char **)sk_value(CHECKED_STACK_OF(OPENSSL_PSTRING
, db
.get()->data
), i
));
553 const char ** current_row
= ((const char **)sk_OPENSSL_PSTRING_value(db
.get()->data
, i
));
556 for (int i
= 0; i
< sk_num(db
.get()->data
); ++i
) {
557 const char ** current_row
= ((const char **)sk_value(db
.get()->data
, i
));
560 if (!sslDateIsInTheFuture(current_row
[cnlExp_date
])) {
561 deleteRow(current_row
, i
);
572 bool Ssl::CertificateDb::deleteOldestCertificate()
577 #if SQUID_SSLTXTDB_PSTRINGDATA
578 #if SQUID_STACKOF_PSTRINGDATA_HACK
579 const char **row
= ((const char **)sk_value(CHECKED_STACK_OF(OPENSSL_PSTRING
, db
.get()->data
), 0));
581 const char **row
= (const char **)sk_OPENSSL_PSTRING_value(db
.get()->data
, 0);
584 const char **row
= (const char **)sk_value(db
.get()->data
, 0);
593 Ssl::CertificateDb::deleteByKey(std::string
const & key
) {
597 #if SQUID_SSLTXTDB_PSTRINGDATA
598 for (int i
= 0; i
< sk_OPENSSL_PSTRING_num(db
.get()->data
); ++i
) {
599 #if SQUID_STACKOF_PSTRINGDATA_HACK
600 const char ** current_row
= ((const char **)sk_value(CHECKED_STACK_OF(OPENSSL_PSTRING
, db
.get()->data
), i
));
602 const char ** current_row
= ((const char **)sk_OPENSSL_PSTRING_value(db
.get()->data
, i
));
605 for (int i
= 0; i
< sk_num(db
.get()->data
); ++i
) {
606 const char ** current_row
= ((const char **)sk_value(db
.get()->data
, i
));
608 if (key
== current_row
[cnlKey
]) {
609 deleteRow(current_row
, i
);
616 bool Ssl::CertificateDb::hasRows() const
621 #if SQUID_SSLTXTDB_PSTRINGDATA
622 if (sk_OPENSSL_PSTRING_num(db
.get()->data
) == 0)
624 if (sk_num(db
.get()->data
) == 0)
631 Ssl::CertificateDb::WriteEntry(const std::string
&filename
, const Security::CertPointer
&cert
, const Security::PrivateKeyPointer
&pkey
, const Security::CertPointer
&orig
)
633 Ssl::BIO_Pointer bio
;
634 if (!Ssl::OpenCertsFileForWriting(bio
, filename
.c_str()))
636 if (!Ssl::WriteX509Certificate(bio
, cert
))
638 if (!Ssl::WritePrivateKey(bio
, pkey
))
640 if (orig
&& !Ssl::WriteX509Certificate(bio
, orig
))
646 Ssl::CertificateDb::ReadEntry(std::string filename
, Security::CertPointer
&cert
, Security::PrivateKeyPointer
&pkey
, Security::CertPointer
&orig
)
648 Ssl::BIO_Pointer bio
;
649 if (!Ssl::OpenCertsFileForReading(bio
, filename
.c_str()))
651 if (!Ssl::ReadX509Certificate(bio
, cert
))
653 if (!Ssl::ReadPrivateKey(bio
, pkey
, NULL
))
655 // The orig certificate is not mandatory
656 (void)Ssl::ReadX509Certificate(bio
, orig
);