]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/security/cert_generators/file/certificate_db.cc
2 * Copyright (C) 1996-2018 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
= 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 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(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)),
260 enabled_disk_store(true) {
261 if (db_path
.empty() && !max_db_size
)
262 enabled_disk_store
= false;
263 else if ((db_path
.empty() && max_db_size
) || (!db_path
.empty() && !max_db_size
))
264 throw std::runtime_error("security_file_certgen is missing the required parameter. There should be -s and -M parameters together.");
268 Ssl::CertificateDb::find(std::string
const &key
, const Security::CertPointer
&expectedOrig
, Security::CertPointer
&cert
, Security::PrivateKeyPointer
&pkey
)
270 const Locker
locker(dbLock
, Here
);
272 return pure_find(key
, expectedOrig
, cert
, pkey
);
275 bool Ssl::CertificateDb::purgeCert(std::string
const & key
) {
276 const Locker
locker(dbLock
, Here
);
281 if (!deleteByKey(key
))
289 Ssl::CertificateDb::addCertAndPrivateKey(std::string
const &useKey
, const Security::CertPointer
&cert
, const Security::PrivateKeyPointer
&pkey
, const Security::CertPointer
&orig
)
291 const Locker
locker(dbLock
, Here
);
293 if (!db
|| !cert
|| !pkey
)
299 // Functor to wrap xfree() for std::unique_ptr
300 typedef HardFun
<void, const void*, &xfree
> CharDeleter
;
303 ASN1_INTEGER
* ai
= X509_get_serialNumber(cert
.get());
304 std::string serial_string
;
305 Ssl::BIGNUM_Pointer
serial(ASN1_INTEGER_to_BN(ai
, NULL
));
307 std::unique_ptr
<char, CharDeleter
> hex_bn(BN_bn2hex(serial
.get()));
308 serial_string
= std::string(hex_bn
.get());
310 row
.setValue(cnlSerial
, serial_string
.c_str());
311 char ** rrow
= TXT_DB_get_by_index(db
.get(), cnlSerial
, row
.getRow());
312 // We are creating certificates with unique serial numbers. If the serial
313 // number is found in the database, the same certificate is already stored.
315 // TODO: check if the stored row is valid.
319 // Remove any entry with given key
322 // check db size while trying to minimize calls to size()
323 size_t dbSize
= size();
324 if ((dbSize
== 0 && hasRows()) ||
325 (dbSize
> 0 && !hasRows()) ||
326 (dbSize
> 10 * max_db_size
)) {
327 // Invalid database size, rebuild
328 dbSize
= rebuildSize();
330 while (dbSize
> max_db_size
&& deleteInvalidCertificate()) {
331 dbSize
= size(); // get the current database size
332 // and try to find another invalid certificate if needed
334 // there are no more invalid ones, but there must be valid certificates
335 while (dbSize
> max_db_size
) {
336 if (!deleteOldestCertificate()) {
337 rebuildSize(); // No certificates in database.Update the size file.
338 save(); // Some entries may have been removed. Update the index file.
339 return false; // errors prevented us from freeing enough space
341 dbSize
= size(); // get the current database size
344 ASN1_UTCTIME
* tm
= X509_get_notAfter(cert
.get());
345 row
.setValue(cnlExp_date
, std::string(reinterpret_cast<char *>(tm
->data
), tm
->length
).c_str());
346 std::unique_ptr
<char, CharDeleter
> subject(X509_NAME_oneline(X509_get_subject_name(cert
.get()), nullptr, 0));
347 row
.setValue(cnlName
, subject
.get());
348 row
.setValue(cnlKey
, useKey
.c_str());
350 if (!TXT_DB_insert(db
.get(), row
.getRow())) {
351 // failed to add index (???) but we may have already modified
352 // the database so save before exit
359 std::string
filename(cert_full
+ "/" + serial_string
+ ".pem");
360 if (!WriteEntry(filename
.c_str(), cert
, pkey
, orig
)) {
361 //remove row from txt_db and save
362 sq_TXT_DB_delete(db
.get(), (const char **)rrow
);
373 Ssl::CertificateDb::Create(std::string
const & db_path
) {
375 throw std::runtime_error("Path to db is empty");
376 std::string
db_full(db_path
+ "/" + db_file
);
377 std::string
cert_full(db_path
+ "/" + cert_dir
);
378 std::string
size_full(db_path
+ "/" + size_file
);
380 if (mkdir(db_path
.c_str(), 0777))
381 throw std::runtime_error("Cannot create " + db_path
);
383 if (mkdir(cert_full
.c_str(), 0777))
384 throw std::runtime_error("Cannot create " + cert_full
);
386 std::ofstream
size(size_full
.c_str());
390 throw std::runtime_error("Cannot open " + size_full
+ " to open");
391 std::ofstream
db(db_full
.c_str());
393 throw std::runtime_error("Cannot open " + db_full
+ " to open");
397 Ssl::CertificateDb::Check(std::string
const & db_path
, size_t max_db_size
, size_t fs_block_size
) {
398 CertificateDb
db(db_path
, max_db_size
, fs_block_size
);
401 // Call readSize to force rebuild size file in the case it is corrupted
405 size_t Ssl::CertificateDb::rebuildSize()
408 #if SQUID_SSLTXTDB_PSTRINGDATA
409 for (int i
= 0; i
< sk_OPENSSL_PSTRING_num(db
.get()->data
); ++i
) {
410 #if SQUID_STACKOF_PSTRINGDATA_HACK
411 const char ** current_row
= ((const char **)sk_value(CHECKED_STACK_OF(OPENSSL_PSTRING
, db
.get()->data
), i
));
413 const char ** current_row
= ((const char **)sk_OPENSSL_PSTRING_value(db
.get()->data
, i
));
416 for (int i
= 0; i
< sk_num(db
.get()->data
); ++i
) {
417 const char ** current_row
= ((const char **)sk_value(db
.get()->data
, i
));
419 const std::string
filename(cert_full
+ "/" + current_row
[cnlSerial
] + ".pem");
420 const size_t fSize
= getFileSize(filename
);
428 Ssl::CertificateDb::pure_find(std::string
const &key
, const Security::CertPointer
&expectedOrig
, Security::CertPointer
&cert
, Security::PrivateKeyPointer
&pkey
)
434 row
.setValue(cnlKey
, key
.c_str());
436 char **rrow
= TXT_DB_get_by_index(db
.get(), cnlKey
, row
.getRow());
440 if (!sslDateIsInTheFuture(rrow
[cnlExp_date
]))
443 Security::CertPointer storedOrig
;
444 // read cert and pkey from file.
445 std::string
filename(cert_full
+ "/" + rrow
[cnlSerial
] + ".pem");
446 if (!ReadEntry(filename
.c_str(), cert
, pkey
, storedOrig
))
449 if (!storedOrig
&& !expectedOrig
)
452 return Ssl::CertificatesCmp(expectedOrig
, storedOrig
);
455 size_t Ssl::CertificateDb::size() {
459 void Ssl::CertificateDb::addSize(std::string
const & filename
) {
460 // readSize will rebuild 'size' file if missing or it is corrupted
461 size_t dbSize
= readSize();
462 dbSize
+= getFileSize(filename
);
466 void Ssl::CertificateDb::subSize(std::string
const & filename
) {
467 // readSize will rebuild 'size' file if missing or it is corrupted
468 size_t dbSize
= readSize();
469 const size_t fileSize
= getFileSize(filename
);
470 dbSize
= dbSize
> fileSize
? dbSize
- fileSize
: 0;
474 size_t Ssl::CertificateDb::readSize() {
475 std::ifstream
ifstr(size_full
.c_str());
477 if (!ifstr
|| !(ifstr
>> db_size
))
478 return rebuildSize();
482 void Ssl::CertificateDb::writeSize(size_t db_size
) {
483 std::ofstream
ofstr(size_full
.c_str());
485 throw std::runtime_error("cannot write \"" + size_full
+ "\" file");
489 size_t Ssl::CertificateDb::getFileSize(std::string
const & filename
) {
490 std::ifstream
file(filename
.c_str(), std::ios::binary
);
493 file
.seekg(0, std::ios_base::end
);
494 const std::streampos file_size
= file
.tellg();
497 return ((static_cast<size_t>(file_size
) + fs_block_size
- 1) / fs_block_size
) * fs_block_size
;
500 void Ssl::CertificateDb::load() {
501 // Load db from file.
502 Ssl::BIO_Pointer
in(BIO_new(BIO_s_file()));
503 if (!in
|| BIO_read_filename(in
.get(), db_full
.c_str()) <= 0)
504 throw std::runtime_error("Uninitialized SSL certificate database directory: " + db_path
+ ". To initialize, run \"security_file_certgen -c -s " + db_path
+ "\".");
506 bool corrupt
= false;
507 Ssl::TXT_DB_Pointer
temp_db(TXT_DB_read(in
.get(), cnlNumber
));
511 // Create indexes in db.
512 if (!corrupt
&& !TXT_DB_create_index(temp_db
.get(), cnlSerial
, NULL
, LHASH_HASH_FN(index_serial_hash
), LHASH_COMP_FN(index_serial_cmp
)))
515 if (!corrupt
&& !TXT_DB_create_index(temp_db
.get(), cnlKey
, NULL
, LHASH_HASH_FN(index_name_hash
), LHASH_COMP_FN(index_name_cmp
)))
519 throw std::runtime_error("The SSL certificate database " + db_path
+ " is corrupted. Please rebuild");
521 db
.reset(temp_db
.release());
524 void Ssl::CertificateDb::save() {
526 throw std::runtime_error("The certificates database is not loaded");;
528 // To save the db to file, create a new BIO with BIO file methods.
529 Ssl::BIO_Pointer
out(BIO_new(BIO_s_file()));
530 if (!out
|| !BIO_write_filename(out
.get(), const_cast<char *>(db_full
.c_str())))
531 throw std::runtime_error("Failed to initialize " + db_full
+ " file for writing");;
533 if (TXT_DB_write(out
.get(), db
.get()) < 0)
534 throw std::runtime_error("Failed to write " + db_full
+ " file");
537 // Normally defined in defines.h file
538 void Ssl::CertificateDb::deleteRow(const char **row
, int rowIndex
) {
539 const std::string
filename(cert_full
+ "/" + row
[cnlSerial
] + ".pem");
540 sq_TXT_DB_delete_row(db
.get(), rowIndex
);
543 int ret
= remove(filename
.c_str());
544 if (ret
< 0 && errno
!= ENOENT
)
545 throw std::runtime_error("Failed to remove certficate file " + filename
+ " from db");
548 bool Ssl::CertificateDb::deleteInvalidCertificate() {
552 bool removed_one
= false;
553 #if SQUID_SSLTXTDB_PSTRINGDATA
554 for (int i
= 0; i
< sk_OPENSSL_PSTRING_num(db
.get()->data
); ++i
) {
555 #if SQUID_STACKOF_PSTRINGDATA_HACK
556 const char ** current_row
= ((const char **)sk_value(CHECKED_STACK_OF(OPENSSL_PSTRING
, db
.get()->data
), i
));
558 const char ** current_row
= ((const char **)sk_OPENSSL_PSTRING_value(db
.get()->data
, i
));
561 for (int i
= 0; i
< sk_num(db
.get()->data
); ++i
) {
562 const char ** current_row
= ((const char **)sk_value(db
.get()->data
, i
));
565 if (!sslDateIsInTheFuture(current_row
[cnlExp_date
])) {
566 deleteRow(current_row
, i
);
577 bool Ssl::CertificateDb::deleteOldestCertificate()
582 #if SQUID_SSLTXTDB_PSTRINGDATA
583 #if SQUID_STACKOF_PSTRINGDATA_HACK
584 const char **row
= ((const char **)sk_value(CHECKED_STACK_OF(OPENSSL_PSTRING
, db
.get()->data
), 0));
586 const char **row
= (const char **)sk_OPENSSL_PSTRING_value(db
.get()->data
, 0);
589 const char **row
= (const char **)sk_value(db
.get()->data
, 0);
598 Ssl::CertificateDb::deleteByKey(std::string
const & key
) {
602 #if SQUID_SSLTXTDB_PSTRINGDATA
603 for (int i
= 0; i
< sk_OPENSSL_PSTRING_num(db
.get()->data
); ++i
) {
604 #if SQUID_STACKOF_PSTRINGDATA_HACK
605 const char ** current_row
= ((const char **)sk_value(CHECKED_STACK_OF(OPENSSL_PSTRING
, db
.get()->data
), i
));
607 const char ** current_row
= ((const char **)sk_OPENSSL_PSTRING_value(db
.get()->data
, i
));
610 for (int i
= 0; i
< sk_num(db
.get()->data
); ++i
) {
611 const char ** current_row
= ((const char **)sk_value(db
.get()->data
, i
));
613 if (key
== current_row
[cnlKey
]) {
614 deleteRow(current_row
, i
);
621 bool Ssl::CertificateDb::hasRows() const
626 #if SQUID_SSLTXTDB_PSTRINGDATA
627 if (sk_OPENSSL_PSTRING_num(db
.get()->data
) == 0)
629 if (sk_num(db
.get()->data
) == 0)
635 bool Ssl::CertificateDb::IsEnabledDiskStore() const {
636 return enabled_disk_store
;
640 Ssl::CertificateDb::WriteEntry(const std::string
&filename
, const Security::CertPointer
&cert
, const Security::PrivateKeyPointer
&pkey
, const Security::CertPointer
&orig
)
642 Ssl::BIO_Pointer bio
;
643 if (!Ssl::OpenCertsFileForWriting(bio
, filename
.c_str()))
645 if (!Ssl::WriteX509Certificate(bio
, cert
))
647 if (!Ssl::WritePrivateKey(bio
, pkey
))
649 if (orig
&& !Ssl::WriteX509Certificate(bio
, orig
))
655 Ssl::CertificateDb::ReadEntry(std::string filename
, Security::CertPointer
&cert
, Security::PrivateKeyPointer
&pkey
, Security::CertPointer
&orig
)
657 Ssl::BIO_Pointer bio
;
658 if (!Ssl::OpenCertsFileForReading(bio
, filename
.c_str()))
660 if (!Ssl::ReadX509Certificate(bio
, cert
))
662 if (!Ssl::ReadPrivateKey(bio
, pkey
, NULL
))
664 // The orig certificate is not mandatory
665 (void)Ssl::ReadX509Certificate(bio
, orig
);