static void mkcert(std::shared_ptr<X509> &cert, std::shared_ptr<EVP_PKEY> &pkey, int bits, int serial, int days) { RSA *rsa; X509_NAME *name=NULL; pkey.reset(EVP_PKEY_new(), &EVP_PKEY_free); if (!pkey) throw std::bad_alloc(); cert.reset(X509_new(), &X509_free); if (!cert) throw std::bad_alloc(); rsa = RSA_generate_key(bits,RSA_F4,NULL,NULL); MORDOR_VERIFY(EVP_PKEY_assign_RSA(pkey.get(),rsa)); X509_set_version(cert.get(),2); ASN1_INTEGER_set(X509_get_serialNumber(cert.get()),serial); X509_gmtime_adj(X509_get_notBefore(cert.get()),0); X509_gmtime_adj(X509_get_notAfter(cert.get()),(long)60*60*24*days); X509_set_pubkey(cert.get(),pkey.get()); name=X509_get_subject_name(cert.get()); /* This function creates and adds the entry, working out the * correct string type and performing checks on its length. * Normally we'd check the return value for errors... */ X509_NAME_add_entry_by_txt(name,"C", MBSTRING_ASC, (const unsigned char *)"United States", -1, -1, 0); X509_NAME_add_entry_by_txt(name,"CN", MBSTRING_ASC, (const unsigned char *)"Mordor Default Self-signed Certificate", -1, -1, 0); /* Its self signed so set the issuer name to be the same as the * subject. */ X509_set_issuer_name(cert.get(),name); /* Add various extensions: standard extensions */ add_ext(cert.get(), NID_basic_constraints, "critical,CA:TRUE"); add_ext(cert.get(), NID_key_usage, "critical,keyCertSign,cRLSign"); add_ext(cert.get(), NID_subject_key_identifier, "hash"); /* Some Netscape specific extensions */ add_ext(cert.get(), NID_netscape_cert_type, "sslCA"); MORDOR_VERIFY(X509_sign(cert.get(),pkey.get(),EVP_md5())); }
Settings::KeyPair CertWizard::generateNewCert(QString qsname, const QString &qsemail) { CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); X509 *x509 = X509_new(); EVP_PKEY *pkey = EVP_PKEY_new(); RSA *rsa = RSA_generate_key(2048,RSA_F4,NULL,NULL); EVP_PKEY_assign_RSA(pkey, rsa); X509_set_version(x509, 2); ASN1_INTEGER_set(X509_get_serialNumber(x509),1); X509_gmtime_adj(X509_get_notBefore(x509),0); X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365*20); X509_set_pubkey(x509, pkey); X509_NAME *name=X509_get_subject_name(x509); if (qsname.isEmpty()) qsname = tr("Mumble User"); X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, reinterpret_cast<unsigned char *>(qsname.toUtf8().data()), -1, -1, 0); X509_set_issuer_name(x509, name); add_ext(x509, NID_basic_constraints, SSL_STRING("critical,CA:FALSE")); add_ext(x509, NID_ext_key_usage, SSL_STRING("clientAuth")); add_ext(x509, NID_subject_key_identifier, SSL_STRING("hash")); add_ext(x509, NID_netscape_comment, SSL_STRING("Generated by Mumble")); add_ext(x509, NID_subject_alt_name, QString::fromLatin1("email:%1").arg(qsemail).toUtf8().data()); X509_sign(x509, pkey, EVP_sha1()); QByteArray crt, key; crt.resize(i2d_X509(x509, NULL)); unsigned char *dptr=reinterpret_cast<unsigned char *>(crt.data()); i2d_X509(x509, &dptr); QSslCertificate qscCert = QSslCertificate(crt, QSsl::Der); key.resize(i2d_PrivateKey(pkey, NULL)); dptr=reinterpret_cast<unsigned char *>(key.data()); i2d_PrivateKey(pkey, &dptr); QSslKey qskKey = QSslKey(key, QSsl::Rsa, QSsl::Der); QList<QSslCertificate> qlCert; qlCert << qscCert; return Settings::KeyPair(qlCert, qskKey); }
int main(int argc, char *argv[]){ BIO *root = BIO_new_file("root.crt", "r"); BIO *rootkey = BIO_new_file("root.key", "r"); BIO *out = BIO_new_file("root_256.crt", "w"); X509 *cert = PEM_read_bio_X509(root, NULL, 0, NULL); EVP_PKEY *pkey = PEM_read_bio_PrivateKey(rootkey, NULL, 0, NULL); if (!cert || !pkey){ printf("Reading the keys failed\n"); return -1; } if( !add_ext( cert, cert, NID_crl_distribution_points, "URI:http://crl.cacert.org/revoke.crl" ) ){ printf("Error while adding extension\n"); return -1; } X509_sign(cert, pkey, EVP_sha256()); PEM_write_bio_X509(out, cert); BIO_free(root); BIO_free(rootkey); BIO_free(out); X509_free(cert); EVP_PKEY_free(pkey); ERR_load_crypto_strings(); ERR_print_errors_fp(stdout); printf("Success\n"); ERR_free_strings(); return 0; }
void list_resources(int argc, char *argv[]) { int i; char *model, *model_file, *pml_file; int num_resources; peos_resource_t *resources; if (argc < 2) { printf("usage: %s model\n", argv[0]); return; } model = argv[1]; pml_file = add_ext(model, ".pml"); model_file = (char *)find_file(pml_file); free(pml_file); if (model_file == NULL) { printf("error: model file %s not found\n", model); return; } resources = (peos_resource_t *) peos_get_resource_list(model_file,&num_resources); if (resources == NULL) { printf("error getting resources\n"); return; } for(i = 0; i < num_resources; i++) { printf("%s=%s\n", resources[i].name, resources[i].value) ; } free(resources); }
void create_process(int argc, char *argv[]) { int pid; char *model, *pml_file; int num_resources; peos_resource_t *resources; if (argc < 2) { printf("usage: %s model\n", argv[0]); return; } model = argv[1]; pml_file = add_ext(model, ".pml"); printf("Getting resources for %s\n", pml_file); resources = (peos_resource_t *) peos_get_resource_list(pml_file, &num_resources); if (resources == NULL) { printf("error getting resources\n"); free(pml_file); return; } printf("Executing %s:\n", pml_file); if ((pid = peos_run(pml_file, resources, num_resources)) < 0) { peos_perror("couldn't create process"); } else { printf("Created pid = %d\n", pid); } free(pml_file); }
/* fopen file, found using pth and fnm * fnmUsed is used to return filename used to open file (ignored if NULL) * or NULL if file didn't open */ extern FILE * fopenWithPthAndExt(const char *pth, const char *fnm, const char *ext, const char *mode, char **fnmUsed) { char *fnmFull = NULL; FILE *fh = NULL; bool fAbs; /* if no pth treat fnm as absolute */ fAbs = (pth == NULL || *pth == '\0' || fAbsoluteFnm(fnm)); /* if appropriate, try it without pth */ if (fAbs) { fh = fopen_not_dir(fnm, mode); if (fh) { if (fnmUsed) fnmFull = osstrdup(fnm); } else { if (ext && *ext) { /* we've been given an extension so try using it */ fnmFull = add_ext(fnm, ext); fh = fopen_not_dir(fnmFull, mode); } } } else { /* try using path given - first of all without the extension */ fnmFull = use_path(pth, fnm); fh = fopen_not_dir(fnmFull, mode); if (!fh) { if (ext && *ext) { /* we've been given an extension so try using it */ char *fnmTmp; fnmTmp = fnmFull; fnmFull = add_ext(fnmFull, ext); osfree(fnmTmp); fh = fopen_not_dir(fnmFull, mode); } } } /* either it opened or didn't. If not, fh == NULL from fopen_not_dir() */ /* free name if it didn't open or name isn't wanted */ if (fh == NULL || fnmUsed == NULL) osfree(fnmFull); if (fnmUsed) *fnmUsed = (fh ? fnmFull : NULL); return fh; }
extern FILE * safe_fopen_with_ext(const char *fnm, const char *ext, const char *mode) { FILE *f; char *p; p = add_ext(fnm, ext); f = safe_fopen(p, mode); osfree(p); return f; }
void Server::initializeCert() { QByteArray crt, key, pass; crt = getConf("certificate", QString()).toByteArray(); key = getConf("key", QString()).toByteArray(); pass = getConf("passphrase", QByteArray()).toByteArray(); QList<QSslCertificate> ql; if (! key.isEmpty()) { qskKey = QSslKey(key, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, pass); if (qskKey.isNull()) qskKey = QSslKey(key, QSsl::Dsa, QSsl::Pem, QSsl::PrivateKey, pass); } if (qskKey.isNull() && ! crt.isEmpty()) { qskKey = QSslKey(crt, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, pass); if (qskKey.isNull()) qskKey = QSslKey(crt, QSsl::Dsa, QSsl::Pem, QSsl::PrivateKey, pass); } if (! qskKey.isNull()) { ql << QSslCertificate::fromData(crt); ql << QSslCertificate::fromData(key); for (int i=0;i<ql.size();++i) { const QSslCertificate &c = ql.at(i); if (isKeyForCert(qskKey, c)) { qscCert = c; ql.removeAt(i); } } qlCA = ql; } QString issuer; #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) QStringList issuerNames = qscCert.issuerInfo(QSslCertificate::CommonName); if (! issuerNames.isEmpty()) { issuer = issuerNames.first(); } #else issuer = qscCert.issuerInfo(QSslCertificate::CommonName); #endif if (issuer == QString::fromUtf8("Murmur Autogenerated Certificate")) { log("Old autogenerated certificate is unusable for registration, invalidating it"); qscCert = QSslCertificate(); qskKey = QSslKey(); } if (!qscCert.isNull() && issuer == QString::fromUtf8("Murmur Autogenerated Certificate v2") && ! Meta::mp.qscCert.isNull() && ! Meta::mp.qskKey.isNull() && (Meta::mp.qlBind == qlBind)) { qscCert = Meta::mp.qscCert; qskKey = Meta::mp.qskKey; } if (qscCert.isNull() || qskKey.isNull()) { if (! key.isEmpty() || ! crt.isEmpty()) { log("Certificate specified, but failed to load."); } qskKey = Meta::mp.qskKey; qscCert = Meta::mp.qscCert; if (qscCert.isNull() || qskKey.isNull()) { log("Generating new server certificate."); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); X509 *x509 = X509_new(); EVP_PKEY *pkey = EVP_PKEY_new(); RSA *rsa = RSA_generate_key(2048,RSA_F4,NULL,NULL); EVP_PKEY_assign_RSA(pkey, rsa); X509_set_version(x509, 2); ASN1_INTEGER_set(X509_get_serialNumber(x509),1); X509_gmtime_adj(X509_get_notBefore(x509),0); X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365*20); X509_set_pubkey(x509, pkey); X509_NAME *name=X509_get_subject_name(x509); X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, reinterpret_cast<unsigned char *>(const_cast<char *>("Murmur Autogenerated Certificate v2")), -1, -1, 0); X509_set_issuer_name(x509, name); add_ext(x509, NID_basic_constraints, SSL_STRING("critical,CA:FALSE")); add_ext(x509, NID_ext_key_usage, SSL_STRING("serverAuth,clientAuth")); add_ext(x509, NID_subject_key_identifier, SSL_STRING("hash")); add_ext(x509, NID_netscape_comment, SSL_STRING("Generated from murmur")); X509_sign(x509, pkey, EVP_sha1()); crt.resize(i2d_X509(x509, NULL)); unsigned char *dptr=reinterpret_cast<unsigned char *>(crt.data()); i2d_X509(x509, &dptr); qscCert = QSslCertificate(crt, QSsl::Der); if (qscCert.isNull()) log("Certificate generation failed"); key.resize(i2d_PrivateKey(pkey, NULL)); dptr=reinterpret_cast<unsigned char *>(key.data()); i2d_PrivateKey(pkey, &dptr); qskKey = QSslKey(key, QSsl::Rsa, QSsl::Der); if (qskKey.isNull()) log("Key generation failed"); setConf("certificate", qscCert.toPem()); setConf("key", qskKey.toPem()); } } }
void Server::initializeCert() { QByteArray crt, key, pass, dhparams; crt = getConf("certificate", QString()).toByteArray(); key = getConf("key", QString()).toByteArray(); pass = getConf("passphrase", QByteArray()).toByteArray(); dhparams = getConf("sslDHParams", Meta::mp.qbaDHParams).toByteArray(); QList<QSslCertificate> ql; if (! key.isEmpty()) { qskKey = QSslKey(key, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, pass); if (qskKey.isNull()) qskKey = QSslKey(key, QSsl::Dsa, QSsl::Pem, QSsl::PrivateKey, pass); } if (qskKey.isNull() && ! crt.isEmpty()) { qskKey = QSslKey(crt, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, pass); if (qskKey.isNull()) qskKey = QSslKey(crt, QSsl::Dsa, QSsl::Pem, QSsl::PrivateKey, pass); } if (! qskKey.isNull()) { ql << QSslCertificate::fromData(crt); ql << QSslCertificate::fromData(key); for (int i=0;i<ql.size();++i) { const QSslCertificate &c = ql.at(i); if (isKeyForCert(qskKey, c)) { qscCert = c; ql.removeAt(i); } } qlCA = ql; } #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) if (! dhparams.isEmpty()) { QSslDiffieHellmanParameters qdhp = QSslDiffieHellmanParameters(dhparams); if (qdhp.isValid()) { qsdhpDHParams = qdhp; } else { log(QString::fromLatin1("Unable to use specified Diffie-Hellman parameters (sslDHParams): %1").arg(qdhp.errorString())); } } #else if (! dhparams.isEmpty()) { log("Diffie-Hellman parameters (sslDHParams) were specified, but will not be used. This version of Murmur does not support Diffie-Hellman parameters."); } #endif QString issuer; #if QT_VERSION >= 0x050000 QStringList issuerNames = qscCert.issuerInfo(QSslCertificate::CommonName); if (! issuerNames.isEmpty()) { issuer = issuerNames.first(); } #else issuer = qscCert.issuerInfo(QSslCertificate::CommonName); #endif if (issuer == QString::fromUtf8("Murmur Autogenerated Certificate")) { log("Old autogenerated certificate is unusable for registration, invalidating it"); qscCert = QSslCertificate(); qskKey = QSslKey(); } if (!qscCert.isNull() && issuer == QString::fromUtf8("Murmur Autogenerated Certificate v2") && ! Meta::mp.qscCert.isNull() && ! Meta::mp.qskKey.isNull() && (Meta::mp.qlBind == qlBind)) { qscCert = Meta::mp.qscCert; qskKey = Meta::mp.qskKey; } if (qscCert.isNull() || qskKey.isNull()) { if (! key.isEmpty() || ! crt.isEmpty()) { log("Certificate specified, but failed to load."); } qskKey = Meta::mp.qskKey; qscCert = Meta::mp.qscCert; if (qscCert.isNull() || qskKey.isNull()) { log("Generating new server certificate."); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); X509 *x509 = X509_new(); EVP_PKEY *pkey = EVP_PKEY_new(); RSA *rsa = RSA_generate_key(2048,RSA_F4,NULL,NULL); EVP_PKEY_assign_RSA(pkey, rsa); X509_set_version(x509, 2); ASN1_INTEGER_set(X509_get_serialNumber(x509),1); X509_gmtime_adj(X509_get_notBefore(x509),0); X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365*20); X509_set_pubkey(x509, pkey); X509_NAME *name=X509_get_subject_name(x509); X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, reinterpret_cast<unsigned char *>(const_cast<char *>("Murmur Autogenerated Certificate v2")), -1, -1, 0); X509_set_issuer_name(x509, name); add_ext(x509, NID_basic_constraints, SSL_STRING("critical,CA:FALSE")); add_ext(x509, NID_ext_key_usage, SSL_STRING("serverAuth,clientAuth")); add_ext(x509, NID_subject_key_identifier, SSL_STRING("hash")); add_ext(x509, NID_netscape_comment, SSL_STRING("Generated from murmur")); X509_sign(x509, pkey, EVP_sha1()); crt.resize(i2d_X509(x509, NULL)); unsigned char *dptr=reinterpret_cast<unsigned char *>(crt.data()); i2d_X509(x509, &dptr); qscCert = QSslCertificate(crt, QSsl::Der); if (qscCert.isNull()) log("Certificate generation failed"); key.resize(i2d_PrivateKey(pkey, NULL)); dptr=reinterpret_cast<unsigned char *>(key.data()); i2d_PrivateKey(pkey, &dptr); qskKey = QSslKey(key, QSsl::Rsa, QSsl::Der); if (qskKey.isNull()) log("Key generation failed"); setConf("certificate", qscCert.toPem()); setConf("key", qskKey.toPem()); } } #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) if (qsdhpDHParams.isEmpty()) { log("Generating new server 2048-bit Diffie-Hellman parameters. This could take a while..."); DH *dh = DH_new(); if (dh == NULL) { qFatal("DH_new failed: unable to generate Diffie-Hellman parameters for virtual server"); } // Generate DH params. // We register a status callback in order to update the UI // for Murmur on Windows. We don't show the actual status, // but we do it to keep Murmur on Windows responsive while // generating the parameters. BN_GENCB cb; memset(&cb, 0, sizeof(BN_GENCB)); BN_GENCB_set(&cb, dh_progress, NULL); if (DH_generate_parameters_ex(dh, 2048, 2, &cb) == 0) { qFatal("DH_generate_parameters_ex failed: unable to generate Diffie-Hellman parameters for virtual server"); } BIO *mem = BIO_new(BIO_s_mem()); if (PEM_write_bio_DHparams(mem, dh) == 0) { qFatal("PEM_write_bio_DHparams failed: unable to write generated Diffie-Hellman parameters to memory"); } char *pem = NULL; long len = BIO_get_mem_data(mem, &pem); if (len <= 0) { qFatal("BIO_get_mem_data returned an empty or invalid buffer"); } QByteArray pemdh(pem, len); QSslDiffieHellmanParameters qdhp(pemdh); if (!qdhp.isValid()) { qFatal("QSslDiffieHellmanParameters: unable to import generated Diffie-HellmanParameters: %s", qdhp.errorString().toStdString().c_str()); } qsdhpDHParams = qdhp; setConf("sslDHParams", pemdh); BIO_free(mem); DH_free(dh); } #endif }
int main(int argc, char **argv) { const char *fnm_in, *fnm_out; char *desc; img_point pt; int result; point *fr = NULL, *to; double zMax = -DBL_MAX; point *p; const char *survey = NULL; const char *specfile = NULL; img *pimg; int have_xsect = 0; msg_init(argv); /* TRANSLATORS: Part of extend --help */ cmdline_set_syntax_message(/*INPUT_3D_FILE [OUTPUT_3D_FILE]*/267, 0, NULL); cmdline_init(argc, argv, short_opts, long_opts, NULL, help, 1, 2); while (1) { int opt = cmdline_getopt(); if (opt == EOF) break; if (opt == 's') survey = optarg; if (opt == 'p') specfile = optarg; } fnm_in = argv[optind++]; if (argv[optind]) { fnm_out = argv[optind]; } else { char * base_in = base_from_fnm(fnm_in); char * base_out = osmalloc(strlen(base_in) + 8); strcpy(base_out, base_in); strcat(base_out, "_extend"); fnm_out = add_ext(base_out, EXT_SVX_3D); osfree(base_in); osfree(base_out); } /* try to open image file, and check it has correct header */ pimg = img_open_survey(fnm_in, survey); if (pimg == NULL) fatalerror(img_error2msg(img_error()), fnm_in); putnl(); puts(msg(/*Reading in data - please wait…*/105)); htab = osmalloc(ossizeof(pfx*) * HTAB_SIZE); { int i; for (i = 0; i < HTAB_SIZE; ++i) htab[i] = NULL; } do { result = img_read_item(pimg, &pt); switch (result) { case img_MOVE: fr = find_point(&pt); break; case img_LINE: if (!fr) { result = img_BAD; break; } to = find_point(&pt); if (!(pimg->flags & (img_FLAG_SURFACE|img_FLAG_SPLAY))) add_leg(fr, to, pimg->label, pimg->flags); fr = to; break; case img_LABEL: to = find_point(&pt); add_label(to, pimg->label, pimg->flags); break; case img_BAD: (void)img_close(pimg); fatalerror(img_error2msg(img_error()), fnm_in); break; case img_XSECT: have_xsect = 1; break; } } while (result != img_STOP); desc = osstrdup(pimg->title); if (specfile) { FILE *fs = NULL; char *fnm_used; /* TRANSLATORS: for extend: */ printf(msg(/*Applying specfile: “%s”*/521), specfile); putnl(); fs = fopenWithPthAndExt("", specfile, NULL, "r", &fnm_used); if (fs == NULL) fatalerror(/*Couldn’t open file “%s”*/93, specfile); while (!feof(fs)) { char *lbuf = getline_alloc(fs, 32); lineno++; if (!lbuf) fatalerror_in_file(fnm_used, lineno, /*Error reading file*/18); parseconfigline(fnm_used, lbuf); osfree(lbuf); } osfree(fnm_used); } if (start == NULL) { /* i.e. start wasn't specified in specfile */ /* start at the highest entrance with some legs attached */ for (p = headpoint.next; p != NULL; p = p->next) { if (p->order > 0 && p->p.z > zMax) { const stn *s; for (s = p->stns; s; s = s->next) { if (s->flags & img_SFLAG_ENTRANCE) { start = p; zMax = p->p.z; break; } } } } if (start == NULL) { /* if no entrances with legs, start at the highest 1-node */ for (p = headpoint.next; p != NULL; p = p->next) { if (p->order == 1 && p->p.z > zMax) { start = p; zMax = p->p.z; } } /* of course we may have no 1-nodes... */ if (start == NULL) { for (p = headpoint.next; p != NULL; p = p->next) { if (p->order != 0 && p->p.z > zMax) { start = p; zMax = p->p.z; } } if (start == NULL) { /* There are no legs - just pick the highest station... */ for (p = headpoint.next; p != NULL; p = p->next) { if (p->p.z > zMax) { start = p; zMax = p->p.z; } } if (!start) fatalerror(/*No survey data*/43); } } } } /* TRANSLATORS: for extend: * Used to tell the user that a file is being written - %s is the filename */ printf(msg(/*Writing %s…*/522), fnm_out); putnl(); pimg_out = img_open_write(fnm_out, desc, img_FFLAG_EXTENDED); /* Only does single connected component currently. */ do_stn(start, 0.0, NULL, ERIGHT, 0); if (have_xsect) { img_rewind(pimg); /* Read ahead on pimg before writing pimg_out so we find out if an * img_XSECT_END comes next. */ char * label = NULL; int flags = 0; do { result = img_read_item(pimg, &pt); if (result == img_XSECT || result == img_XSECT_END) { if (label) { if (result == img_XSECT_END) flags |= img_XFLAG_END; img_write_item(pimg_out, img_XSECT, flags, label, 0, 0, 0); osfree(label); label = NULL; } } if (result == img_XSECT) { label = osstrdup(pimg->label); flags = pimg->flags; pimg_out->l = pimg->l; pimg_out->r = pimg->r; pimg_out->u = pimg->u; pimg_out->d = pimg->d; } } while (result != img_STOP); } (void)img_close(pimg); if (!img_close(pimg_out)) { (void)remove(fnm_out); fatalerror(img_error2msg(img_error()), fnm_out); } return EXIT_SUCCESS; }
int32_t mkcert(X509 **x509p, EVP_PKEY **pkeyp, int32_t bits, int32_t serial, int32_t days) { bool bCreatedKey = false; bool bCreatedX509 = false; // ----------------- X509 * x = NULL; EVP_PKEY * pk = NULL; RSA * rsa = NULL; X509_NAME * name = NULL; if ((pkeyp == NULL) || (*pkeyp == NULL)) { if ((pk = EVP_PKEY_new()) == NULL) { abort(); // todo //return(0); unneeded after abort. } bCreatedKey = true; } else pk = *pkeyp; // ----------------------------------------- if ((x509p == NULL) || (*x509p == NULL)) { if ((x = X509_new()) == NULL) { if (bCreatedKey) { EVP_PKEY_free(pk); } return(0); } bCreatedX509 = true; } else x = *x509p; // ----------------------------------------- // pRsaKey = RSA_generate_key(1024, 0x010001, NULL, NULL); #ifdef ANDROID rsa = RSA_new(); BIGNUM * e1 = BN_new(); if ((NULL == rsa) || (NULL == e1)) abort(); // todo // BN_set_word(e1, 65537); BN_set_word(e1, RSA_F4); if (!RSA_generate_key_ex(rsa, bits, e1, NULL)) abort(); // todo BN_free(e1); #else rsa = RSA_generate_key(bits, RSA_F4, callback, NULL); #endif // ----------------------------------------- if (!EVP_PKEY_assign_RSA(pk, rsa)) { abort(); // todo //return(0); undeeded after abort. } // ------------------------------ rsa = NULL; X509_set_version(x, 2); ASN1_INTEGER_set(X509_get_serialNumber(x), serial); X509_gmtime_adj (X509_get_notBefore(x), 0); X509_gmtime_adj (X509_get_notAfter (x), static_cast<int64_t>(60*60*24*days)); X509_set_pubkey (x, pk); name = X509_get_subject_name(x); /* This function creates and adds the entry, working out the * correct string type and performing checks on its length. * Normally we'd check the return value for errors... */ X509_NAME_add_entry_by_txt(name,"C", MBSTRING_ASC, (const uint8_t *)"UK", -1, -1, 0); X509_NAME_add_entry_by_txt(name,"CN", MBSTRING_ASC, (const uint8_t *)"OpenSSL Group", -1, -1, 0); /* Its self signed so set the issuer name to be the same as the * subject. */ X509_set_issuer_name(x, name); // ---------------------------------------------------------------------------- /* Add various extensions: standard extensions */ char * szConstraints = new char[100](); char * szKeyUsage = new char[100](); char * szSubjectKeyID = new char[100](); char * szCertType = new char[100](); char * szComment = new char[100](); // ---------------------------------------------------------------------------- opentxs::OTString::safe_strcpy(szConstraints, "critical,CA:TRUE", 99); opentxs::OTString::safe_strcpy(szKeyUsage, "critical,keyCertSign,cRLSign", 99); opentxs::OTString::safe_strcpy(szSubjectKeyID, "hash", 99); opentxs::OTString::safe_strcpy(szCertType, "sslCA", 99); opentxs::OTString::safe_strcpy(szComment, "example comment extension", 99); // ---------------------------------------------------------------------------- add_ext(x, NID_basic_constraints, szConstraints); add_ext(x, NID_key_usage, szKeyUsage); add_ext(x, NID_subject_key_identifier, szSubjectKeyID); add_ext(x, NID_netscape_cert_type, szCertType); // Some Netscape specific extensions add_ext(x, NID_netscape_comment, szComment); // Some Netscape specific extensions // ---------------------------------------------------------------------------- delete [] szConstraints; szConstraints = NULL; delete [] szKeyUsage; szKeyUsage = NULL; delete [] szSubjectKeyID; szSubjectKeyID = NULL; delete [] szCertType; szCertType = NULL; delete [] szComment; szComment = NULL; // ---------------------------------------------------------------------------- #ifdef CUSTOM_EXT // Maybe even add our own extension based on existing { int32_t nid; nid = OBJ_create("1.2.3.4", "MyAlias", "My Test Alias Extension"); X509V3_EXT_add_alias(nid, NID_netscape_comment); add_ext(x, nid, "example comment alias"); } #endif // ------------------------------ if (!X509_sign(x, pk, EVP_md5()) || // TODO security: md5 ??? (NULL == x509p) || (NULL == pkeyp)) { // ERROR // if (bCreatedX509) X509_free(x); // NOTE: not sure if x owns pk, in which case pk is already freed above. // Todo: find out and then determine whether or not to uncomment this. // (Presumably this would be a rare occurrence anyway.) // // if (bCreatedKey) // EVP_PKEY_free(pk); x = NULL; pk = NULL; return 0; } // ------------------------------ *x509p = x; *pkeyp = pk; return(1); }
void Server::initializeCert() { QByteArray crt, key, pass, dhparams; crt = getConf("certificate", QString()).toByteArray(); key = getConf("key", QString()).toByteArray(); pass = getConf("passphrase", QByteArray()).toByteArray(); dhparams = getConf("sslDHParams", Meta::mp.qbaDHParams).toByteArray(); QList<QSslCertificate> ql; // Attempt to load key as an RSA key or a DSA key if (! key.isEmpty()) { qskKey = QSslKey(key, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, pass); if (qskKey.isNull()) qskKey = QSslKey(key, QSsl::Dsa, QSsl::Pem, QSsl::PrivateKey, pass); } // If we still can't load the key, try loading any keys from the certificate if (qskKey.isNull() && ! crt.isEmpty()) { qskKey = QSslKey(crt, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, pass); if (qskKey.isNull()) qskKey = QSslKey(crt, QSsl::Dsa, QSsl::Pem, QSsl::PrivateKey, pass); } // If have a key, walk the list of certs, find the one for our key, // remove any certs for our key from the list, what's left is part of // the CA certificate chain. if (! qskKey.isNull()) { ql << QSslCertificate::fromData(crt); ql << QSslCertificate::fromData(key); for (int i=0;i<ql.size();++i) { const QSslCertificate &c = ql.at(i); if (isKeyForCert(qskKey, c)) { qscCert = c; ql.removeAt(i); } } qlCA = ql; } #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) if (! dhparams.isEmpty()) { QSslDiffieHellmanParameters qdhp = QSslDiffieHellmanParameters(dhparams); if (qdhp.isValid()) { qsdhpDHParams = qdhp; } else { log(QString::fromLatin1("Unable to use specified Diffie-Hellman parameters (sslDHParams): %1").arg(qdhp.errorString())); } } #else if (! dhparams.isEmpty()) { log("Diffie-Hellman parameters (sslDHParams) were specified, but will not be used. This version of Murmur does not support Diffie-Hellman parameters."); } #endif QString issuer; #if QT_VERSION >= 0x050000 QStringList issuerNames = qscCert.issuerInfo(QSslCertificate::CommonName); if (! issuerNames.isEmpty()) { issuer = issuerNames.first(); } #else issuer = qscCert.issuerInfo(QSslCertificate::CommonName); #endif // Really old certs/keys are no good, throw them away so we can // generate a new one below. if (issuer == QString::fromUtf8("Murmur Autogenerated Certificate")) { log("Old autogenerated certificate is unusable for registration, invalidating it"); qscCert = QSslCertificate(); qskKey = QSslKey(); } // If we have a cert, and it's a self-signed one, but we're binding to // all the same addresses as the Meta server is, use it's cert instead. // This allows a self-signed certificate generated by Murmur to be // replaced by a CA-signed certificate in the .ini file. if (!qscCert.isNull() && issuer == QString::fromUtf8("Murmur Autogenerated Certificate v2") && ! Meta::mp.qscCert.isNull() && ! Meta::mp.qskKey.isNull() && (Meta::mp.qlBind == qlBind)) { qscCert = Meta::mp.qscCert; qskKey = Meta::mp.qskKey; } // If we still don't have a certificate by now, try to load the one from Meta if (qscCert.isNull() || qskKey.isNull()) { if (! key.isEmpty() || ! crt.isEmpty()) { log("Certificate specified, but failed to load."); } qskKey = Meta::mp.qskKey; qscCert = Meta::mp.qscCert; // If loading from Meta doesn't work, build+sign a new one if (qscCert.isNull() || qskKey.isNull()) { log("Generating new server certificate."); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); X509 *x509 = X509_new(); EVP_PKEY *pkey = EVP_PKEY_new(); RSA *rsa = RSA_generate_key(2048,RSA_F4,NULL,NULL); EVP_PKEY_assign_RSA(pkey, rsa); X509_set_version(x509, 2); ASN1_INTEGER_set(X509_get_serialNumber(x509),1); X509_gmtime_adj(X509_get_notBefore(x509),0); X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365*20); X509_set_pubkey(x509, pkey); X509_NAME *name=X509_get_subject_name(x509); X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, reinterpret_cast<unsigned char *>(const_cast<char *>("Murmur Autogenerated Certificate v2")), -1, -1, 0); X509_set_issuer_name(x509, name); add_ext(x509, NID_basic_constraints, SSL_STRING("critical,CA:FALSE")); add_ext(x509, NID_ext_key_usage, SSL_STRING("serverAuth,clientAuth")); add_ext(x509, NID_subject_key_identifier, SSL_STRING("hash")); add_ext(x509, NID_netscape_comment, SSL_STRING("Generated from murmur")); X509_sign(x509, pkey, EVP_sha1()); crt.resize(i2d_X509(x509, NULL)); unsigned char *dptr=reinterpret_cast<unsigned char *>(crt.data()); i2d_X509(x509, &dptr); qscCert = QSslCertificate(crt, QSsl::Der); if (qscCert.isNull()) log("Certificate generation failed"); key.resize(i2d_PrivateKey(pkey, NULL)); dptr=reinterpret_cast<unsigned char *>(key.data()); i2d_PrivateKey(pkey, &dptr); qskKey = QSslKey(key, QSsl::Rsa, QSsl::Der); if (qskKey.isNull()) log("Key generation failed"); setConf("certificate", qscCert.toPem()); setConf("key", qskKey.toPem()); } } #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) if (qsdhpDHParams.isEmpty()) { log("Generating new server 2048-bit Diffie-Hellman parameters. This could take a while..."); DH *dh = DH_new(); if (dh == NULL) { qFatal("DH_new failed: unable to generate Diffie-Hellman parameters for virtual server"); } // Generate DH params. // We register a status callback in order to update the UI // for Murmur on Windows. We don't show the actual status, // but we do it to keep Murmur on Windows responsive while // generating the parameters. BN_GENCB cb; memset(&cb, 0, sizeof(BN_GENCB)); BN_GENCB_set(&cb, dh_progress, NULL); if (DH_generate_parameters_ex(dh, 2048, 2, &cb) == 0) { qFatal("DH_generate_parameters_ex failed: unable to generate Diffie-Hellman parameters for virtual server"); } BIO *mem = BIO_new(BIO_s_mem()); if (PEM_write_bio_DHparams(mem, dh) == 0) { qFatal("PEM_write_bio_DHparams failed: unable to write generated Diffie-Hellman parameters to memory"); } char *pem = NULL; long len = BIO_get_mem_data(mem, &pem); if (len <= 0) { qFatal("BIO_get_mem_data returned an empty or invalid buffer"); } QByteArray pemdh(pem, len); QSslDiffieHellmanParameters qdhp(pemdh); if (!qdhp.isValid()) { qFatal("QSslDiffieHellmanParameters: unable to import generated Diffie-HellmanParameters: %s", qdhp.errorString().toStdString().c_str()); } qsdhpDHParams = qdhp; setConf("sslDHParams", pemdh); BIO_free(mem); DH_free(dh); } #endif // Drain OpenSSL's per-thread error queue // to ensure that errors from the operations // we've done in here do not leak out into // Qt's SSL module. // // If an error leaks, it can break all connections // to the server because each invocation of Qt's SSL // read callback checks OpenSSL's per-thread error // queue (albeit indirectly, via SSL_get_error()). // Qt expects any errors returned from SSL_get_error() // to be related to the QSslSocket it is currently // processing -- which is the obvious thing to expect: // SSL_get_error() takes a pointer to an SSL object // and the return code of the failed operation. // However, it is also documented as: // // "In addition to ssl and ret, SSL_get_error() // inspects the current thread's OpenSSL error // queue." // // So, if any OpenSSL operation on the main thread // forgets to clear the error queue, those errors // *will* leak into other things that *do* error // checking. In our case, into Qt's SSL read callback, // resulting in all clients being disconnected. ERR_clear_error(); }
int mkcert(X509 **x509p, EVP_PKEY **pkeyp, int bits, int serial, int years) { X509 *x; EVP_PKEY *pk; RSA *rsa; X509_NAME *name = NULL; if (*pkeyp == NULL) { if ((pk=EVP_PKEY_new()) == NULL) { return(0); } } else { pk = *pkeyp; } if (*x509p == NULL) { if ((x = X509_new()) == NULL) { goto err; } } else { x = *x509p; } rsa = RSA_generate_key(bits, RSA_F4, NULL, NULL); if (!EVP_PKEY_assign_RSA(pk, rsa)) { goto err; } X509_set_version(x, 2); ASN1_INTEGER_set(X509_get_serialNumber(x), serial); X509_gmtime_adj(X509_get_notBefore(x), 0); X509_gmtime_adj(X509_get_notAfter(x), (long)60*60*24*365*years); X509_set_pubkey(x, pk); name = X509_get_subject_name(x); /* This function creates and adds the entry, working out the * correct string type and performing checks on its length. */ X509_NAME_add_entry_by_txt(name,"CN", MBSTRING_ASC, (unsigned char*)"NVIDIA GameStream Client", -1, -1, 0); /* Its self signed so set the issuer name to be the same as the * subject. */ X509_set_issuer_name(x, name); /* Add various extensions: standard extensions */ add_ext(x, NID_basic_constraints, "critical,CA:TRUE"); add_ext(x, NID_key_usage, "critical,keyCertSign,cRLSign"); add_ext(x, NID_subject_key_identifier, "hash"); if (!X509_sign(x, pk, EVP_sha1())) { goto err; } *x509p = x; *pkeyp = pk; return(1); err: return(0); }
SL::Remote_Access_Library::Crypto::CertSaveLocation SL::Remote_Access_Library::Crypto::CreateCertificate(const CertInfo& info) { assert(INTERNAL::Started);//you must ensure proper startup of the encryption library! CryptoKeys cry; CertSaveLocation svloc; SL_RAT_LOG(Utilities::Logging_Levels::INFO_log_level, "Starting to generate a certifiate and private key!"); if (!cry.x509Certificate || !cry.PrivateKey) { SL_RAT_LOG(Utilities::Logging_Levels::ERROR_log_level, "Failed to allocate space for the certificate and private key!"); return svloc; } auto rsa = RSA_generate_key(info.bits, RSA_F4, NULL, NULL); if (!EVP_PKEY_assign_RSA(cry.PrivateKey, rsa)) { SL_RAT_LOG(Utilities::Logging_Levels::ERROR_log_level, "Failed EVP_PKEY_assign_RSA"); return svloc; } X509_set_version(cry.x509Certificate, 2); ASN1_INTEGER_set(X509_get_serialNumber(cry.x509Certificate), info.Serial); X509_gmtime_adj(X509_get_notBefore(cry.x509Certificate), 0); X509_gmtime_adj(X509_get_notAfter(cry.x509Certificate), (long)60 * 60 * 24 * info.DaysValid); X509_set_pubkey(cry.x509Certificate, cry.PrivateKey); auto name = X509_get_subject_name(cry.x509Certificate); /* This function creates and adds the entry, working out the * correct string type and performing checks on its length. * Normally we'd check the return value for errors... */ X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (const unsigned char*)info.country.c_str(), -1, -1, 0); X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (const unsigned char*)info.companyname.c_str(), -1, -1, 0); X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const unsigned char*)info.commonname.c_str(), -1, -1, 0); /* Its self signed so set the issuer name to be the same as the * subject. */ X509_set_issuer_name(cry.x509Certificate, name); /* Add various extensions: standard extensions */ add_ext(cry.x509Certificate, NID_basic_constraints, (char*)"critical,CA:TRUE"); add_ext(cry.x509Certificate, NID_key_usage, (char*)"critical,keyCertSign,cRLSign"); add_ext(cry.x509Certificate, NID_subject_key_identifier, (char*)"hash"); /* Some Netscape specific extensions */ add_ext(cry.x509Certificate, NID_netscape_cert_type, (char*)"sslCA"); add_ext(cry.x509Certificate, NID_netscape_comment, (char*)"example comment extension"); if (!X509_sign(cry.x509Certificate, cry.PrivateKey, EVP_sha256())) { SL_RAT_LOG(Utilities::Logging_Levels::ERROR_log_level, "Failed to sign the certifiate!"); return svloc; } std::string saveloc = info.savelocation; if (saveloc.back() != '/' && saveloc.back() != '\\') saveloc += '/'; assert(!saveloc.empty()); svloc.Private_Key = saveloc + info.filename + "_private.pem"; cry.priv_keyfile = fopen(svloc.Private_Key.c_str(), "wb"); if(cry.priv_keyfile!=NULL){ SL_RAT_LOG(Utilities::Logging_Levels::ERROR_log_level, "Failed to open the Private Key File '" << svloc.Private_Key << "' for writing!"); svloc.Private_Key = ""; return svloc; } PEM_write_PrivateKey( cry.priv_keyfile, /* write the key to the file we've opened */ cry.PrivateKey, /* our key from earlier */ EVP_des_ede3_cbc(), /* default cipher for encrypting the key on disk */ (unsigned char*)info.password.c_str(), /* passphrase required for decrypting the key on disk */ static_cast<int>(info.password.size()), /* length of the passphrase string */ NULL, /* callback for requesting a password */ NULL /* data to pass to the callback */ ); svloc.Certificate = saveloc + info.filename + "_cert.crt"; cry.certfile = fopen(svloc.Certificate.c_str(), "wb"); if(cry.certfile!=NULL){ SL_RAT_LOG(Utilities::Logging_Levels::ERROR_log_level, "Failed to open the Certificate File '" << svloc.Certificate << "' for writing!"); svloc.Certificate = ""; return svloc; } return svloc; }
int mkcert(X509 **x509p, EVP_PKEY **pkeyp, char* common_name, int bits, int serial, int days) { X509 *x; EVP_PKEY *pk; RSA *rsa; X509_NAME *name=NULL; if ((pkeyp == NULL) || (*pkeyp == NULL)) { if ((pk=EVP_PKEY_new()) == NULL) { abort(); return(0); } } else pk= *pkeyp; if ((x509p == NULL) || (*x509p == NULL)) { if ((x=X509_new()) == NULL) goto err; } else x= *x509p; rsa=RSA_generate_key(bits,RSA_F4,callback,NULL); if (!EVP_PKEY_assign_RSA(pk,rsa)) { abort(); goto err; } rsa=NULL; X509_set_version(x,2); ASN1_INTEGER_set(X509_get_serialNumber(x),serial); X509_gmtime_adj(X509_get_notBefore(x),0); X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days); X509_set_pubkey(x,pk); name=X509_get_subject_name(x); unsigned char* response = (unsigned char*) calloc(1,512); printf("Enter Country: "); scanf("%s",response); X509_NAME_add_entry_by_txt(name,"C", MBSTRING_ASC, response, -1, -1, 0); printf("Enter State: "); memset(response, 0, 512); scanf("%s",response); X509_NAME_add_entry_by_txt(name,"ST", MBSTRING_ASC, response, -1, -1, 0); printf("Enter City: "); memset(response, 0, 512); scanf("%s",response); X509_NAME_add_entry_by_txt(name,"L", MBSTRING_ASC, response, -1, -1, 0); printf("Enter Organization: "); memset(response, 0, 512); scanf("%s",response); X509_NAME_add_entry_by_txt(name,"O", MBSTRING_ASC, response, -1, -1, 0); X509_NAME_add_entry_by_txt(name,"CN", MBSTRING_ASC, (unsigned char*)common_name, -1, -1, 0); X509_set_issuer_name(x,name); add_ext(x, NID_basic_constraints, "critical,CA:TRUE"); add_ext(x, NID_key_usage, "critical,keyCertSign,cRLSign"); add_ext(x, NID_subject_key_identifier, "hash"); add_ext(x, NID_netscape_cert_type, "sslCA"); if (!X509_sign(x,pk,EVP_sha1())) goto err; *x509p=x; *pkeyp=pk; return 1; err: return 0; }
extern CDECL int main(int argc, char **argv) { int d; time_t tmUserStart = time(NULL); clock_t tmCPUStart = clock(); { /* FIXME: localtime? */ struct tm * t = localtime(&tmUserStart); int y = t->tm_year + 1900; current_days_since_1900 = days_since_1900(y, t->tm_mon + 1, t->tm_mday); } /* Always buffer by line for aven's benefit. */ setvbuf(stdout, NULL, _IOLBF, 0); msg_init(argv); #if OS_WIN32 || OS_UNIX_MACOSX pj_set_finder(msg_proj_finder); #endif pcs = osnew(settings); pcs->next = NULL; pcs->Translate = ((short*) osmalloc(ossizeof(short) * 257)) + 1; pcs->meta = NULL; pcs->proj = NULL; pcs->declination = HUGE_REAL; pcs->convergence = 0.0; /* Set up root of prefix hierarchy */ root = osnew(prefix); root->up = root->right = root->down = NULL; root->stn = NULL; root->pos = NULL; root->ident = NULL; root->min_export = root->max_export = 0; root->sflags = BIT(SFLAGS_SURVEY); root->filename = NULL; nosurveyhead = NULL; stnlist = NULL; cLegs = cStns = cComponents = 0; totadj = total = totplan = totvert = 0.0; for (d = 0; d <= 2; d++) { min[d] = HUGE_REAL; max[d] = -HUGE_REAL; pfxHi[d] = pfxLo[d] = NULL; } /* at least one argument must be given */ cmdline_init(argc, argv, short_opts, long_opts, NULL, help, 1, -1); while (1) { int opt = cmdline_getopt(); if (opt == EOF) break; switch (opt) { case 'p': /* Ignore for compatibility with older versions. */ break; case 'o': { osfree(fnm_output_base); /* in case of multiple -o options */ /* can be a directory (in which case use basename of leaf input) * or a file (in which case just trim the extension off) */ if (fDirectory(optarg)) { /* this is a little tricky - we need to note the path here, * and then add the leaf later on (in datain.c) */ fnm_output_base = base_from_fnm(optarg); fnm_output_base_is_dir = 1; } else { fnm_output_base = base_from_fnm(optarg); } break; } case 'q': if (fQuiet) fMute = 1; fQuiet = 1; break; case 's': fSuppress = 1; break; case 'v': { int v = atoi(optarg); if (v < IMG_VERSION_MIN || v > IMG_VERSION_MAX) fatalerror(/*3d file format versions %d to %d supported*/88, IMG_VERSION_MIN, IMG_VERSION_MAX); img_output_version = v; break; } case 'w': f_warnings_are_errors = 1; break; case 'z': { /* Control which network optimisations are used (development tool) */ static int first_opt_z = 1; char c; if (first_opt_z) { optimize = 0; first_opt_z = 0; } /* Lollipops, Parallel legs, Iterate mx, Delta* */ while ((c = *optarg++) != '\0') if (islower((unsigned char)c)) optimize |= BITA(c); break; case 1: fLog = fTrue; break; #if OS_WIN32 case 2: atexit(pause_on_exit); break; #endif } } } if (fLog) { char *fnm; if (!fnm_output_base) { char *p; p = baseleaf_from_fnm(argv[optind]); fnm = add_ext(p, EXT_LOG); osfree(p); } else if (fnm_output_base_is_dir) { char *p; fnm = baseleaf_from_fnm(argv[optind]); p = use_path(fnm_output_base, fnm); osfree(fnm); fnm = add_ext(p, EXT_LOG); osfree(p); } else { fnm = add_ext(fnm_output_base, EXT_LOG); } if (!freopen(fnm, "w", stdout)) fatalerror(/*Failed to open output file “%s”*/47, fnm); osfree(fnm); } if (!fMute) { const char *p = COPYRIGHT_MSG; puts(PRETTYPACKAGE" "VERSION); while (1) { const char *q = p; p = strstr(p, "(C)"); if (p == NULL) { puts(q); break; } fwrite(q, 1, p - q, stdout); fputs(msg(/*©*/0), stdout); p += 3; } } atexit(delete_output_on_error); /* end of options, now process data files */ while (argv[optind]) { const char *fnm = argv[optind]; if (!fExplicitTitle) { char *lf; lf = baseleaf_from_fnm(fnm); if (survey_title) s_catchar(&survey_title, &survey_title_len, ' '); s_cat(&survey_title, &survey_title_len, lf); osfree(lf); } /* Select defaults settings */ default_all(pcs); data_file(NULL, fnm); /* first argument is current path */ optind++; } validate(); solve_network(/*stnlist*/); /* Find coordinates of all points */ validate(); /* close .3d file */ if (!img_close(pimg)) { char *fnm = add_ext(fnm_output_base, EXT_SVX_3D); fatalerror(img_error2msg(img_error()), fnm); } if (fhErrStat) safe_fclose(fhErrStat); out_current_action(msg(/*Calculating statistics*/120)); if (!fMute) do_stats(); if (!fQuiet) { /* clock() typically wraps after 72 minutes, but there doesn't seem * to be a better way. Still 72 minutes means some cave! * We detect if clock() could have wrapped and suppress CPU time * printing in this case. */ double tmUser = difftime(time(NULL), tmUserStart); double tmCPU; clock_t now = clock(); #define CLOCK_T_WRAP \ (sizeof(clock_t)<sizeof(long)?(1ul << (CHAR_BIT * sizeof(clock_t))):0) tmCPU = (now - (unsigned long)tmCPUStart) / (double)CLOCKS_PER_SEC; if (now < tmCPUStart) tmCPU += CLOCK_T_WRAP / (double)CLOCKS_PER_SEC; if (tmUser >= tmCPU + CLOCK_T_WRAP / (double)CLOCKS_PER_SEC) tmCPU = 0; /* tmUser is integer, tmCPU not - equivalent to (ceil(tmCPU) >= tmUser) */ if (tmCPU + 1 > tmUser) { printf(msg(/*CPU time used %5.2fs*/140), tmCPU); } else if (tmCPU == 0) { if (tmUser != 0.0) { printf(msg(/*Time used %5.2fs*/141), tmUser); } else { fputs(msg(/*Time used unavailable*/142), stdout); } } else { printf(msg(/*Time used %5.2fs (%5.2fs CPU time)*/143), tmUser, tmCPU); } putnl(); } if (msg_warnings || msg_errors) { if (msg_errors || (f_warnings_are_errors && msg_warnings)) { printf(msg(/*There were %d warning(s) and %d error(s) - no output files produced.*/113), msg_warnings, msg_errors); putnl(); return EXIT_FAILURE; } printf(msg(/*There were %d warning(s).*/16), msg_warnings); putnl(); } return EXIT_SUCCESS; }
static int mkcert(X509 **x509p, EVP_PKEY **pkeyp, int bits, int serial, int days) { X509 *x; EVP_PKEY *pk; RSA *rsa; X509_NAME *name=NULL; if ((pkeyp == NULL) || (*pkeyp == NULL)) { if ((pk=EVP_PKEY_new()) == NULL) { abort(); return(0); } } else pk= *pkeyp; if ((x509p == NULL) || (*x509p == NULL)) { if ((x=X509_new()) == NULL) goto err; } else x= *x509p; if (bits != 0){ rsa=RSA_generate_key(bits,RSA_F4,callback,NULL); if (!EVP_PKEY_assign_RSA(pk,rsa)) { abort(); goto err; } rsa=NULL; } X509_set_version(x,2); ASN1_INTEGER_set(X509_get_serialNumber(x),serial); X509_gmtime_adj(X509_get_notBefore(x),0); X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days); X509_set_pubkey(x,pk); name=X509_get_subject_name(x); /* This function creates and adds the entry, working out the * correct string type and performing checks on its length. * Normally we'd check the return value for errors... */ X509_NAME_add_entry_by_txt(name,"C", MBSTRING_ASC,(const unsigned char *) "UK", -1, -1, 0); X509_NAME_add_entry_by_txt(name,"CN", MBSTRING_ASC, (const unsigned char *) _cert_cn, -1, -1, 0); /* Its self signed so set the issuer name to be the same as the * subject. */ X509_set_issuer_name(x,name); /* Add various extensions: standard extensions */ add_ext(x, NID_basic_constraints, "critical,CA:TRUE"); add_ext(x, NID_key_usage, "critical,keyCertSign,cRLSign"); add_ext(x, NID_subject_key_identifier, "hash"); /* Some Netscape specific extensions */ add_ext(x, NID_netscape_cert_type, "sslCA"); add_ext(x, NID_netscape_comment, "example comment extension"); #ifdef CUSTOM_EXT /* Maybe even add our own extension based on existing */ { int nid; nid = OBJ_create("1.2.3.4", "MyAlias", "My Test Alias Extension"); X509V3_EXT_add_alias(nid, NID_netscape_comment); add_ext(x, nid, "example comment alias"); } #endif if (!X509_sign(x,pk,EVP_sha1())) goto err; *x509p=x; *pkeyp=pk; return(1); err: return(0); }
/* Creates an X509 certificate from a certificate request. */ EXPORT int IssueUserCertificate(unsigned char *certbuf, int *certlen, unsigned char *reqbuf, int reqlen) { X509_REQ *req = NULL; EVP_PKEY *cakey = NULL, *rakey = NULL, *usrkey = NULL; X509 *cacert = NULL, *racert = NULL, *usrcert = NULL; X509_NAME *subject = NULL, *issuer = NULL; unsigned char *p = NULL; int ret = OPENSSLCA_NO_ERR, len; if (certbuf == NULL || certlen == NULL || reqbuf == NULL || reqlen == 0) return OPENSSLCA_ERR_ARGS; /* Decode request */ if ((req = X509_REQ_new()) == NULL) { ret = OPENSSLCA_ERR_REQ_NEW; goto err; } p = reqbuf; if (d2i_X509_REQ(&req, &p, reqlen) == NULL) { ret = OPENSSLCA_ERR_REQ_DECODE; goto err; } /* Get public key from request */ if ((usrkey = X509_REQ_get_pubkey(req)) == NULL) { ret = OPENSSLCA_ERR_REQ_GET_PUBKEY; goto err; } if (caIni.verifyRequests) { /* Get RA's public key */ /* TODO: Validate RA certificate */ ret = read_cert(&racert, CA_PATH(caIni.raCertFile)); if (ret != OPENSSLCA_NO_ERR) goto err; if ((rakey = X509_get_pubkey(racert)) == NULL) { ret = OPENSSLCA_ERR_CERT_GET_PUBKEY; goto err; } /* Verify signature on request */ if (X509_REQ_verify(req, rakey) != 1) { ret = OPENSSLCA_ERR_REQ_VERIFY; goto err; } } /* Get CA certificate */ /* TODO: Validate CA certificate */ ret = read_cert(&cacert, CA_PATH(caIni.caCertFile)); if (ret != OPENSSLCA_NO_ERR) goto err; /* Get CA private key */ ret = read_key(&cakey, CA_PATH(caIni.caKeyFile), caIni.caKeyPasswd); if (ret != OPENSSLCA_NO_ERR) goto err; /* Create user certificate */ if ((usrcert = X509_new()) == NULL) return OPENSSLCA_ERR_CERT_NEW; /* Set version and serial number for certificate */ if (X509_set_version(usrcert, 2) != 1) { /* V3 */ ret = OPENSSLCA_ERR_CERT_SET_VERSION; goto err; } if (ASN1_INTEGER_set(X509_get_serialNumber(usrcert), get_serial()) != 1) { ret = OPENSSLCA_ERR_CERT_SET_SERIAL; goto err; } /* Set duration for certificate */ if (X509_gmtime_adj(X509_get_notBefore(usrcert), 0) == NULL) { ret = OPENSSLCA_ERR_CERT_SET_NOTBEFORE; goto err; } if (X509_gmtime_adj(X509_get_notAfter(usrcert), EXPIRE_SECS(caIni.daysTillExpire)) == NULL) { ret = OPENSSLCA_ERR_CERT_SET_NOTAFTER; goto err; } /* Set public key */ if (X509_set_pubkey(usrcert, usrkey) != 1) { ret = OPENSSLCA_ERR_CERT_SET_PUBKEY; goto err; } /* Set subject name */ subject = X509_REQ_get_subject_name(req); if (subject == NULL) { ret = OPENSSLCA_ERR_REQ_GET_SUBJECT; goto err; } if (X509_set_subject_name(usrcert, subject) != 1) { ret = OPENSSLCA_ERR_CERT_SET_SUBJECT; goto err; } /* Set issuer name */ issuer = X509_get_issuer_name(cacert); if (issuer == NULL) { ret = OPENSSLCA_ERR_CERT_GET_ISSUER; goto err; } if (X509_set_issuer_name(usrcert, issuer) != 1) { ret = OPENSSLCA_ERR_CERT_SET_ISSUER; goto err; } /* Add extensions */ ret = add_ext(cacert, usrcert); if (ret != OPENSSLCA_NO_ERR) goto err; /* Sign user certificate with CA's private key */ if (!X509_sign(usrcert, cakey, EVP_sha1())) return OPENSSLCA_ERR_CERT_SIGN; if (caIni.verifyAfterSign) { if (X509_verify(usrcert, cakey) != 1) { ret = OPENSSLCA_ERR_CERT_VERIFY; goto err; } } #ifdef _DEBUG /* Output certificate in DER and PEM format */ { FILE *fp = fopen(DBG_PATH("usrcert.der"), "wb"); if (fp != NULL) { i2d_X509_fp(fp, usrcert); fclose(fp); } fp = fopen(DBG_PATH("usrcert.pem"), "w"); if (fp != NULL) { X509_print_fp(fp, usrcert); PEM_write_X509(fp, usrcert); fclose(fp); } } #endif /* Encode user certificate into DER format */ len = i2d_X509(usrcert, NULL); if (len < 0) { ret = OPENSSLCA_ERR_CERT_ENCODE; goto err; } if (len > *certlen) { ret = OPENSSLCA_ERR_BUF_TOO_SMALL; goto err; } *certlen = len; p = certbuf; i2d_X509(usrcert, &p); if (caIni.addToIndex) add_to_index(usrcert); if (caIni.addToNewCerts) write_cert(usrcert); err: print_err("IssueUserCertificate()", ret); /* Clean up */ if (cacert) X509_free(cacert); if (cakey) EVP_PKEY_free(cakey); if (racert) X509_free(racert); if (rakey) EVP_PKEY_free(rakey); if (req) X509_REQ_free(req); if (usrcert != NULL) X509_free(usrcert); if (usrkey) EVP_PKEY_free(usrkey); return ret; }