- // Get our certificates in order.
- // First, create the key/cert directory if it's not there already...
- mkdir(CTDL_CRYPTO_DIR, 0700);
-
- // If we still don't have a private key, generate one.
- generate_key(CTDL_KEY_PATH);
-
- // If there is no certificate file on disk, we will be generating a self-signed certificate
- // in the next step. Therefore, if we have neither a CSR nor a certificate, generate
- // the CSR in this step so that the next step may commence.
- if ((access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0)) {
- syslog(LOG_INFO, "Generating a certificate signing request.");
-
- // Read our key from the file. No, we don't just keep this
- // in memory from the above key-generation function, because
- // there is the possibility that the key was already on disk
- // and we didn't just generate it now.
- fp = fopen(CTDL_KEY_PATH, "r");
- if (fp) {
- rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
- fclose(fp);
- }
-
- if (rsa) {
- // Create a public key from the private key
- if (pk = EVP_PKEY_new(), pk != NULL) {
- EVP_PKEY_assign_RSA(pk, rsa);
- if (req = X509_REQ_new(), req != NULL) {
- const char *env;
- // Set the public key
- X509_REQ_set_pubkey(req, pk);
- X509_REQ_set_version(req, 0L);
- name = X509_REQ_get_subject_name(req);
- X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned char *) "Citadel Server", -1, -1, 0);
- X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC, (unsigned char *) "Default Certificate PLEASE CHANGE", -1, -1, 0);
- X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char *) "*", -1, -1, 0);
- X509_REQ_set_subject_name(req, name);
-
- // Sign the CSR
- if (!X509_REQ_sign(req, pk, EVP_md5())) {
- syslog(LOG_WARNING, "X509_REQ_sign(): error");
- }
- else {
- // Write it to disk
- fp = fopen(CTDL_CSR_PATH, "w");
- if (fp != NULL) {
- chmod(CTDL_CSR_PATH, 0600);
- PEM_write_X509_REQ(fp, req);
- fclose(fp);
- }
- else {
- syslog(LOG_WARNING, "Cannot write key: %s", CTDL_CSR_PATH);
- exit(1);
- }
- }
- X509_REQ_free(req);
- }
- }
- RSA_free(rsa);
- }
- else {
- syslog(LOG_WARNING, "Unable to read private key.");
- }
- }
-
- // Generate a self-signed certificate if we don't have one.
- if (access(CTDL_CER_PATH, R_OK) != 0) {
- syslog(LOG_INFO, "Generating a self-signed certificate.");
-
- // Same deal as before: always read the key from disk because
- // it may or may not have just been generated.
- fp = fopen(CTDL_KEY_PATH, "r");
- if (fp) {
- rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
- fclose(fp);
- }