static
OSStatus _SecIdentityCopyPreferenceMatchingName(
    CFStringRef name,
    CSSM_KEYUSE keyUsage,
    CFArrayRef validIssuers,
    SecIdentityRef *identity)
{
    // this is NOT exported, and called only from SecIdentityCopyPreference (below), so no BEGIN/END macros here;
    // caller must handle exceptions

	StorageManager::KeychainList keychains;
	globals().storageManager.getSearchList(keychains);
	KCCursor cursor(keychains, kSecGenericPasswordItemClass, NULL);

	char idUTF8[MAXPATHLEN];
    Required(name);
    if (!CFStringGetCString(name, idUTF8, sizeof(idUTF8)-1, kCFStringEncodingUTF8))
        idUTF8[0] = (char)'\0';
    CssmData service(const_cast<char *>(idUTF8), strlen(idUTF8));
	FourCharCode itemType = 'iprf';
    cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecServiceItemAttr), service);
	cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecTypeItemAttr), itemType);
    if (keyUsage)
        cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecScriptCodeItemAttr), (sint32)keyUsage);

	Item prefItem;
	if (!cursor->next(prefItem))
		return errSecItemNotFound;

	// get persistent certificate reference
	SecKeychainAttribute itemAttrs[] = { { kSecGenericItemAttr, 0, NULL } };
	SecKeychainAttributeList itemAttrList = { sizeof(itemAttrs) / sizeof(itemAttrs[0]), itemAttrs };
	prefItem->getContent(NULL, &itemAttrList, NULL, NULL);

	// find certificate, given persistent reference data
	CFDataRef pItemRef = CFDataCreateWithBytesNoCopy(NULL, (const UInt8 *)itemAttrs[0].data, itemAttrs[0].length, kCFAllocatorNull);
	SecKeychainItemRef certItemRef = nil;
	OSStatus status = SecKeychainItemCopyFromPersistentReference(pItemRef, &certItemRef); //%%% need to make this a method of ItemImpl
	prefItem->freeContent(&itemAttrList, NULL);
	if (pItemRef)
		CFRelease(pItemRef);
	if (status)
		return status;

    // filter on valid issuers, if provided
    if (validIssuers) {
        //%%%TBI
    }

	// create identity reference, given certificate
	Item certItem = ItemImpl::required(SecKeychainItemRef(certItemRef));
	SecPointer<Certificate> certificate(static_cast<Certificate *>(certItem.get()));
	SecPointer<Identity> identity_ptr(new Identity(keychains, certificate));
	if (certItemRef)
		CFRelease(certItemRef);

	Required(identity) = identity_ptr->handle();

    return status;
}
Esempio n. 2
0
File: ssu.cpp Progetto: lbt/ssu
bool Ssu::registerDevice(QDomDocument *response){
  QString certificateString = response->elementsByTagName("certificate").at(0).toElement().text();
  QSslCertificate certificate(certificateString.toAscii());
  SsuLog *ssuLog = SsuLog::instance();
  SsuCoreConfig *settings = SsuCoreConfig::instance();

  if (certificate.isNull()){
    // make sure device is in unregistered state on failed registration
    settings->setValue("registered", false);
    setError("Certificate is invalid");
    return false;
  } else
    settings->setValue("certificate", certificate.toPem());

  QString privateKeyString = response->elementsByTagName("privateKey").at(0).toElement().text();
  QSslKey privateKey(privateKeyString.toAscii(), QSsl::Rsa);

  if (privateKey.isNull()){
    settings->setValue("registered", false);
    setError("Private key is invalid");
    return false;
  } else
    settings->setValue("privateKey", privateKey.toPem());

  // oldUser is just for reference purposes, in case we want to notify
  // about owner changes for the device
  QString oldUser = response->elementsByTagName("user").at(0).toElement().text();
  ssuLog->print(LOG_DEBUG, QString("Old user for your device was: %1").arg(oldUser));

  // if we came that far everything required for device registration is done
  settings->setValue("registered", true);
  settings->sync();
  emit registrationStatusChanged();
  return true;
}
Esempio n. 3
0
QT_USE_NAMESPACE

//! [constructor]
SslEchoServer::SslEchoServer(quint16 port, QObject *parent) :
    QObject(parent),
    m_pWebSocketServer(Q_NULLPTR),
    m_clients()
{
    m_pWebSocketServer = new QWebSocketServer(QStringLiteral("SSL Echo Server"),
                                              QWebSocketServer::SecureMode,
                                              this);
    QSslConfiguration sslConfiguration;
    QFile certFile(QStringLiteral("./localhost.cert"));
    QFile keyFile(QStringLiteral("./localhost.key"));
    certFile.open(QIODevice::ReadOnly);
    keyFile.open(QIODevice::ReadOnly);
    QSslCertificate certificate(&certFile, QSsl::Pem);
    QSslKey sslKey(&keyFile, QSsl::Rsa, QSsl::Pem);
    certFile.close();
    keyFile.close();
    sslConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
    sslConfiguration.setLocalCertificate(certificate);
    sslConfiguration.setPrivateKey(sslKey);
    sslConfiguration.setProtocol(QSsl::TlsV1SslV3);
    m_pWebSocketServer->setSslConfiguration(sslConfiguration);

    if (m_pWebSocketServer->listen(QHostAddress::Any, port))
    {
        qDebug() << "SSL Echo Server listening on port" << port;
        connect(m_pWebSocketServer, &QWebSocketServer::newConnection,
                this, &SslEchoServer::onNewConnection);
        connect(m_pWebSocketServer, &QWebSocketServer::sslErrors,
                this, &SslEchoServer::onSslErrors);
    }
}
Esempio n. 4
0
void ErrorReport::AddSSLCertificate()
{
	QFile file(":/startcom.cer", 0);
	if(file.open(QIODevice::ReadOnly))
	{
		QSslCertificate certificate(file.readAll(), QSsl::Der);
		if(certificate.isValid() && !certificate.isNull())
		{
			QSslSocket::addDefaultCaCertificate(certificate);
		}
	}
}
Esempio n. 5
0
void Tpenalty::checkForCert() {
	if (!m_supply->wasFinished() && m_exam->count() >= (m_supply->obligQuestions() + m_exam->penalty()) ) { // maybe enough
		if (m_exam->blackCount()) {
				m_exam->increasePenaltys(m_exam->blackCount());
				qDebug() << "penalties increased. Can't finish this exam yet.";
		} else {
				m_exam->setFinished();
				PROGRESS->setFinished();
				emit certificate();
				m_supply->setFinished();
		}
	}
}
Esempio n. 6
0
ptr_lib::shared_ptr<IdentityCertificate>
IdentityManager::createIdentityCertificate(const Name& certificatePrefix,
                                           const PublicKey& publicKey,
                                           const Name& signerCertificateName,
                                           const MillisecondsSince1970& notBefore,
                                           const MillisecondsSince1970& notAfter)
{
  ptr_lib::shared_ptr<IdentityCertificate> certificate(new IdentityCertificate());
  Name keyName = getKeyNameFromCertificatePrefix(certificatePrefix);

  Name certificateName = certificatePrefix;
  MillisecondsSince1970 ti = ::ndn_getNowMilliseconds();
  // Get the number of seconds.
  ostringstream oss;
  oss << floor(ti / 1000.0);

  certificateName.append("ID-CERT").append(oss.str());

  certificate->setName(certificateName);
  certificate->setNotBefore(notBefore);
  certificate->setNotAfter(notAfter);
  certificate->setPublicKeyInfo(publicKey);
  certificate->addSubjectDescription(CertificateSubjectDescription("2.5.4.41", keyName.toUri()));
  certificate->encode();

  ptr_lib::shared_ptr<Sha256WithRsaSignature> sha256Sig(new Sha256WithRsaSignature());

  KeyLocator keyLocator;
  keyLocator.setType(ndn_KeyLocatorType_KEYNAME);
  keyLocator.setKeyName(signerCertificateName);

  sha256Sig->setKeyLocator(keyLocator);
  sha256Sig->getPublisherPublicKeyDigest().setPublisherPublicKeyDigest(publicKey.getDigest());

  certificate->setSignature(*sha256Sig);

  SignedBlob unsignedData = certificate->wireEncode();

  ptr_lib::shared_ptr<IdentityCertificate> signerCertificate = getCertificate(signerCertificateName);
  Name signerkeyName = signerCertificate->getPublicKeyName();

  Blob sigBits = privateKeyStorage_->sign(unsignedData, signerkeyName);

  sha256Sig->setSignature(sigBits);

  return certificate;
}
Esempio n. 7
0
ItemTreePtr LeafSolver::compute()
{
	const auto nodeStackElement = app.getPrinter().visitNode(decomposition);
	assert(decomposition.getChildren().empty());
	assert(decomposition.getNode().getBag().empty());

	ItemTreePtr result(new ItemTree(ItemTree::Node(new ItemTreeNode({}, {}, {{}}, ItemTreeNode::Type::OR))));
	ItemTreePtr candidate(new ItemTree(ItemTree::Node(new ItemTreeNode({}, {}, {{}}, ItemTreeNode::Type::AND))));
	ItemTreePtr certificate(new ItemTree(ItemTree::Node(new ItemTreeNode)));
	candidate->addChildAndMerge(std::move(certificate));
	result->addChildAndMerge(std::move(candidate));

	if(result->finalize(app, decomposition.isRoot(), app.isPruningDisabled() == false || decomposition.isRoot()) == false)
		result.reset();

	app.getPrinter().solverInvocationResult(decomposition, result.get());

	return result;
}
QT_USE_NAMESPACE

//! [constructor]
BCWebSocketServer::BCWebSocketServer(quint16 port, QObject *parent) :
    QObject(parent),
    m_pWebSocketServer(Q_NULLPTR),
    m_clients()
{
    m_pWebSocketServer = new QWebSocketServer(QStringLiteral("Bitcoin Exchange Server"),
                                              QWebSocketServer::NonSecureMode, //**** To be Changed after setting up OpenSSL
                                              this);
    QSslConfiguration sslConfiguration;
    QFile certFile(QStringLiteral("./localhost.cert"));
    QFile keyFile(QStringLiteral("./localhost.key"));
    /*if ( */
    certFile.open(stderr, QIODevice::ReadOnly | QIODevice::Text ) ; //&&
    keyFile.open(stderr, QIODevice::ReadOnly | QIODevice::Text) ; // )
    {
        QSslCertificate certificate(&certFile, QSsl::Pem);
        QSslKey sslKey(&keyFile, QSsl::Rsa, QSsl::Pem);
        certFile.close();
        keyFile.close();
        sslConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
        sslConfiguration.setLocalCertificate(certificate);
        sslConfiguration.setPrivateKey(sslKey);
        sslConfiguration.setProtocol(QSsl::TlsV1SslV3);
        m_pWebSocketServer->setSslConfiguration(sslConfiguration);

        if (m_pWebSocketServer->listen(QHostAddress::Any, port))
        {
            qDebug() << "Bitcoin Exchange Server listening on port" << port;
            connect(m_pWebSocketServer, &QWebSocketServer::newConnection,
                    this, &BCWebSocketServer::onNewConnection);
            connect(m_pWebSocketServer, &QWebSocketServer::sslErrors,
                    this, &BCWebSocketServer::onSslErrors);
        }

        _logged = false;
        _lang = NULL;

        this->data.rank = 0;
    }
}
Esempio n. 9
0
std::string load_ssl_certificate(const std::string filename) {
  // Open the file
  std::ifstream file_stream(filename.c_str(), std::ios::in | std::ios::binary | std::ios::ate);

  BOOST_REQUIRE_MESSAGE(file_stream.is_open(), "Unable to load certificate file: " << filename);

  // Get the length of the file
  std::ifstream::pos_type file_size = file_stream.tellg();
  file_stream.seekg(0, std::ios::beg);

  BOOST_REQUIRE_MESSAGE(file_size > 0, "No data in certificate file: " << filename);

  // Read the file into memory
  std::vector<char> bytes(file_size);
  file_stream.read(&bytes[0], file_size);

  std::string certificate(&bytes[0], file_size);
  return certificate;
}
bool SerializedScriptValueReaderForModules::readRTCCertificate(
    v8::Local<v8::Value>* value) {
  String pemPrivateKey;
  if (!readWebCoreString(&pemPrivateKey))
    return false;
  String pemCertificate;
  if (!readWebCoreString(&pemCertificate))
    return false;

  std::unique_ptr<WebRTCCertificateGenerator> certificateGenerator =
      wrapUnique(Platform::current()->createRTCCertificateGenerator());

  std::unique_ptr<WebRTCCertificate> certificate(
      certificateGenerator->fromPEM(pemPrivateKey, pemCertificate));
  RTCCertificate* jsCertificate = new RTCCertificate(std::move(certificate));

  *value =
      toV8(jsCertificate, getScriptState()->context()->Global(), isolate());
  return !value->IsEmpty();
}
Esempio n. 11
0
Network::Network(MainWindow *parent) : QObject(0)
{
	// Initialization
	mw = parent;
	this->dm = mw->dm;
	server = 0;
	// Connections
	connect(this, &Network::postToLogArea, mw->getLogArea(), &QPlainTextEdit::appendPlainText);
	// SSL Configuration
	sslConfig.setProtocol(QSsl::TlsV1_2);
	// Disable remote certificate request
	sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
	// TODO:  Replace these temporary certificates with files
	QByteArray certificateText("-----BEGIN CERTIFICATE-----\nMIIGzTCCBLWgAwIBAgIJAL7oZ7T5jFYeMA0GCSqGSIb3DQEBBQUAMIGfMQswCQYD\nVQQGEwJVUzERMA8GA1UECBMIQ29sb3JhZG8xEDAOBgNVBAcTB0JvdWxkZXIxHTAb\nBgNVBAoTFDJCIFRlY2hub2xvZ2llcyBJbmMuMREwDwYDVQQLEwhERFggVGVhbTEV\nMBMGA1UEAxMMSmFzb24gUHJpbmNlMSIwIAYJKoZIhvcNAQkBFhNqYXNvbnBAdHdv\nYnRlY2guY29tMB4XDTE1MDkwODE5NTA0NFoXDTE4MDYyODE5NTA0NFowgZ8xCzAJ\nBgNVBAYTAlVTMREwDwYDVQQIEwhDb2xvcmFkbzEQMA4GA1UEBxMHQm91bGRlcjEd\nMBsGA1UEChMUMkIgVGVjaG5vbG9naWVzIEluYy4xETAPBgNVBAsTCEREWCBUZWFt\nMRUwEwYDVQQDEwxKYXNvbiBQcmluY2UxIjAgBgkqhkiG9w0BCQEWE2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cNAQkBFhNqYXNvbnBAdHdvYnRlY2guY29tggkAvuhntPmMVh4w\nDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAgEAiAOkOiAWHf+9Hq83NO64\n8q57mndINq0p6aU7VZN0Btd77zF03zxYVOqzNzAwscRiSDL/PM4buTzaC9wt+3fZ\nA6QGrcgBaz/4kVt2V3qqX04aPMwDoan/qLcNC6b9/QyVI3N6Cgm7W+60r6vElKdb\nd1EfuR9pQ9iXrcENXSfVj6NxKh3pUkByz4X13ovrkP4xDSsoPRXTQuJl7dYB6mMO\n5ERmRJGLgFWuHBVLONgNo52TAldaiu7fW+Wkv/08UfBD0F+aToo7VVJ2s21ef2T4\necGIIYwcOflT3fKHPCmwuNSOldelV7Vljq8WLVgAJI5d/+PlKOfXpXZlMARuov0Y\n+LdUFXSPuCzb3uyOLidu1YNzDkLIjtU6xj5zC7qipa+AVsd0PtzZJ8cSNjxkHrq8\nDIM3q5yx+zpdc0Pis6NiF4a30DparaE9BOZl+WdaKqb/Dysfp/4SAw7txMIv+hNn\nmBnDfso/3afGZ7sp9nkeo34fqnM1LFDw8F2oQDb8/3RqkuduYBlqCo1OC8fQBfIB\nX8pgOg3yi/2owAb9HjACYGxMYW7g+z39Nh0fgpnaY+XH09vezkeQ+bjIUK6wS2Mb\ntxRLPC/VM97hcUx6Qxi51GuGjSZZpq1DwKg0b/avgnfoBmy8dznsefczwBsqVYjN\n755QBb0PnEV512Lq6rTkIGM=\n-----END CERTIFICATE-----\n");
	QSslCertificate certificate(certificateText);
	if (certificate.isNull()) log(tr("Certificate invalid"));
	else sslConfig.setLocalCertificate(certificate);
	QByteArray keyText("-----BEGIN RSA PRIVATE KEY-----\nMIIJKQIBAAKCAgEAwPb0v0qrLC+suBHZLcuyijnv4guiKlvvbPMabC+u6vD5X3C6\nb024YdMImz2uw2JhxAUKN/cpBhuIWdwpiSr+qS2jCZOV9O7wO+U/+FQoZOLk/g+l\nrhOt+tsWBu1GU81cE3Nv/vm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qAKUu\nUqfTxdHUJehSXUDHzGObKMRcc1i2b7pbSdKwqgO15BsxAjDouIKJVUYoFYiiWozV\ni5ILsdj+yGMyTPYn1PMSgYTqq22sOR0NRhZB84ZneNO6NLuUmoaGR48xg4QkacAM\n+UXhGJJQ/2OmQEWk8a3RpRA9QpgZc7IS9ouv792AvQb0zk7fhfZFxjEsrk1EWVdF\nb4/OJwKCAQEAvVbqxpZVy7+0ZiaQFh+TtE5shp6l62dW2t2BgDqZL0a1vO468O5J\ntwffOAzCzbyUrK+jPTjP326e+bRavQGwC9xXYrowCD/VmqsPJY3d3bZEX7ft4LfM\nrAm9GwhCZBFFCdJw+9imudt76cBPLyaGAHIbs8aFzl7MV3CDKyp2DjumX+kjU7lL\nRNsqrN3a6FMvUxKI/XrwAzUrTVa7mjSEU/BE6iRRAzpCrsuVnzqSfthRFv8/eDRi\ngl1vWT6b9uQxyM7DDjbVxUCdsW2jDlbScTrS2y3Xr7mnuQ1sG1pELoyu0r8JDK76\ncxATP56T3eZNq+A4MskvWxz2femJqWBPNQKCAQAgaBxuHqn7hAvVmKBT+gBazx68\nKeSiBp9/RDl8CRfoxo4W9dZ0OKYdhedqBADDmlRr0pHJOXtk9ODwh8pkr3IFTQ66\nCMjj8MmRv7DCSuOhe9lC3k9qX4tAszZK/MJLgjw+n96kYXBOZw5cqtEyvjd+ThNM\n2JiqPij0w7qmGnnKKTnNxDtwV73X50dPisBYjgYMjGeopy3mj+31+nL6iGBrg2Fy\nH3dfyFjiXls/dr7cFyGaCyTjyHTX7gys1kB/XT9srzjiIC+2xMWgQ481qMueisZa\nY60gvZeZLW2zgOOR1VNhc3QUNE8Wtyxy/9Mqa8PxGSaDY+b8dj3QLMQa/7gz\n-----END RSA PRIVATE KEY-----\n");
	QSslKey key(keyText, QSsl::Rsa);
	if (key.isNull()) log(tr("Private key invalid"));
	else sslConfig.setPrivateKey(key);
	// TODO:  Tailor a list of acceptable ciphers and ECs
#if (QT_VERSION < QT_VERSION_CHECK(5, 5, 0))
	sslConfig.setCiphers(QSslSocket::supportedCiphers());
#else
	sslConfig.setCiphers(QSslConfiguration::supportedCiphers());
	sslConfig.setEllipticCurves(QSslConfiguration::supportedEllipticCurves());
#endif
	// Threading
#ifdef NETWORK_THREAD
	QThread *t = new QThread(daemon);
	moveToThread(t);
	connect(t, &QThread::started, this, &Network::init);
	connect(this, &Network::destroyed, t, &QThread::quit);
	connect(t, &QThread::finished, t, &QThread::deleteLater);
	t->start();
#else
	init();
#endif
}
Esempio n. 12
0
ptr_lib::shared_ptr<IdentityCertificate>
IdentityManager::selfSign(const Name& keyName)
{
  ptr_lib::shared_ptr<IdentityCertificate> certificate(new IdentityCertificate());

  Blob keyBlob = identityStorage_->getKey(keyName);
  ptr_lib::shared_ptr<PublicKey> publicKey(new PublicKey(keyBlob));

#if NDN_CPP_HAVE_GMTIME_SUPPORT
  time_t nowSeconds = time(NULL);
  struct tm current = *gmtime(&nowSeconds);
  current.tm_hour = 0;
  current.tm_min  = 0;
  current.tm_sec  = 0;
  MillisecondsSince1970 notBefore = timegm(&current) * 1000.0;
  current.tm_year = current.tm_year + 2;
  MillisecondsSince1970 notAfter = timegm(&current) * 1000.0;

  certificate->setNotBefore(notBefore);
  certificate->setNotAfter(notAfter);
#else
  // Don't really expect this to happen.
  throw SecurityException("selfSign: Can't set certificate validity because time functions are not supported by the standard library.");
#endif

  Name certificateName = keyName.getPrefix(-1).append("KEY").append
    (keyName.get(-1)).append("ID-CERT").append
    (Name::Component::fromNumber((uint64_t)ndn_getNowMilliseconds()));
  certificate->setName(certificateName);

  certificate->setPublicKeyInfo(*publicKey);
  certificate->addSubjectDescription(CertificateSubjectDescription("2.5.4.41", keyName.toUri()));
  certificate->encode();

  signByCertificate(*certificate, certificate->getName());

  return certificate;
}
Esempio n. 13
0
void ErrorReport::AddSSLCertificate() {
	
	QFile file(":/startcom.cer", 0);
	if(file.open(QIODevice::ReadOnly)) {
		QSslCertificate certificate(file.readAll(), QSsl::Der);
		
		if(certificate.isNull()) {
			return;
		}
		
		#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
		if(!certificate.isValid()) {
			return;
		}
		#else
		if(certificate.isBlacklisted()) {
			return;
		}
		#endif
		
		QSslSocket::addDefaultCaCertificate(certificate);
	}
}
Esempio n. 14
0
   void run(int argc, char* argv[], char* env[])
      {
      U_TRACE(5, "Application::run(%d,%p,%p)", argc, argv, env)

      UApplication::run(argc, argv, env);

      U_SYSCALL_VOID_NO_PARAM(xmlInitParser); // init libxml

      LIBXML_TEST_VERSION

      // manage options

      num_args = (argc - optind);

      U_INTERNAL_DUMP("optind = %d num_args = %d", optind, num_args)

      if (UApplication::isOptions()) cfg_str = opt['c'];

      // manage file configuration

      if (cfg_str.empty()) cfg_str = U_STRING_FROM_CONSTANT("XAdES.ini");

      // ----------------------------------------------------------------------------------------------------------------------------------
      // XAdES - configuration parameters
      // ----------------------------------------------------------------------------------------------------------------------------------
      // DigestAlgorithm   md2 | md5 | sha | sha1 | sha224 | sha256 | sha384 | sha512 | mdc2 | ripmed160
      //
      // SigningTime this property contains the time at which the signer claims to have performed the signing process (yes/no)
      // ClaimedRole this property contains claimed or certified roles assumed by the signer in creating the signature
      //
      // this property contains the indication of the purported place where the signer claims to have produced the signature
      // -------------------------------------------------------------------------------------------------------------------
      // ProductionPlaceCity
      // ProductionPlaceStateOrProvince
      // ProductionPlacePostalCode
      // ProductionPlaceCountryName
      // -------------------------------------------------------------------------------------------------------------------
      //
      // DataObjectFormatMimeType   this property identifies the format of a signed data object (when electronic signatures
      //                            are not exchanged in a restricted context) to enable the presentation to the verifier or
      //                            use by the verifier (text, sound or video) in exactly the same way as intended by the signer
      //
      // CAStore
      // ArchiveTimeStamp           the time-stamp token within this property covers the archive validation data
      //
      // SignatureTimeStamp         the time-stamp token within this property covers the digital signature value element
      // Schema                     the pathname XML Schema of XAdES
      // ----------------------------------------------------------------------------------------------------------------------------------

      (void) cfg.open(cfg_str);

      UString x(U_CAPACITY);

      UServices::readEOF(STDIN_FILENO, x);

      if (x.empty()) U_ERROR("cannot read data from <stdin>...");

      (void) content.reserve(x.size());

      if (UBase64::decode(x, content) == false) U_ERROR("decoding data read failed...");

      // manage arguments...

      schema = ( U_SCHEMA == 0 ||
                *U_SCHEMA == '\0'
                  ? cfg[U_STRING_FROM_CONSTANT("XAdES-L.Schema")]
                  : UString(U_SCHEMA));

      if (schema.empty()) U_ERROR("error on XAdES schema: empty");

      /*
      UString str_CApath       = cfg[U_STRING_FROM_CONSTANT("XAdES-C.CAStore")],
              digest_algorithm = cfg[U_STRING_FROM_CONSTANT("XAdES-C.DigestAlgorithm")];

      if (str_CApath.empty() ||
          UServices::setupOpenSSLStore(0, str_CApath.c_str()) == false)
         {
         U_ERROR("error on setting CA Store: %S", str_CApath.data());
         }
      */

      UXML2Schema XAdES_schema(UFile::contentOf(schema));

      // ---------------------------------------------------------------------------------------------------------------
      // check for OOffice or MS-Word document...
      // ---------------------------------------------------------------------------------------------------------------
      utility.handlerConfig(cfg);

      if (utility.checkDocument(content, "XAdES", false)) content = utility.getSigned();
      // ---------------------------------------------------------------------------------------------------------------

      UApplication::exit_value = 1;

      UXML2Document document(content);

      if (XAdES_schema.validate(document) == false)
         {
         UString content1;

         if (document.getElement(content1, 0, U_CONSTANT_TO_PARAM(U_TAG_SIGNED_INFO)) &&
             content1.empty() == false)
            {
            UXML2Document document1(content1);

            if (XAdES_schema.validate(document1) == false)
               {
               U_ERROR("fail to validate data input based on XAdES schema");
               }
            }
         }

      UDSIGContext dsigCtx;
      UString data, signature;
      const char* digest_algorithm;

      if (dsigCtx.verify(document, digest_algorithm, data, signature))
         {
         UString element = document.getElementData(128, U_CONSTANT_TO_PARAM(U_TAG_X509_CERTIFICATE));

         if (element.empty() == false)
            {
            UString certificate(element.size());

            if (UBase64::decode(element, certificate))
               {
               alg = u_dgst_get_algoritm(digest_algorithm);

               if (alg == -1) U_ERROR("I can't find the digest algorithm for: %s", digest_algorithm);

               X509* x509 = UCertificate::readX509(certificate, "DER");

               u_pkey = UCertificate::getSubjectPublicKey(x509);

               U_SYSCALL_VOID(X509_free, "%p", x509);

               if (UServices::verifySignature(alg, data, signature, UString::getStringNull(), 0))
                  {
                  UApplication::exit_value = 0;

#              ifdef __MINGW32__
                  (void) setmode(1, O_BINARY);
#              endif

               // std::cout.write(U_STRING_TO_PARAM(certificate));
                  std::cout.write(U_STRING_TO_PARAM(content));
                  }

               U_SYSCALL_VOID(EVP_PKEY_free, "%p", u_pkey);
                                                   u_pkey = 0;
               }
            }
         }

      utility.clean();
      }
OSStatus SecIdentitySetPreference(
    SecIdentityRef identity,
    CFStringRef name,
    CSSM_KEYUSE keyUsage)
{
	if (!name) {
		return errSecParam;
	}
	if (!identity) {
		// treat NULL identity as a request to clear the preference
		// (note: if keyUsage is 0, this clears all key usage prefs for name)
		return SecIdentityDeletePreferenceItemWithNameAndKeyUsage(NULL, name, keyUsage);
	}

    BEGIN_SECAPI

	SecPointer<Certificate> certificate(Identity::required(identity)->certificate());

	// determine the account attribute
	//
	// This attribute must be synthesized from certificate label + pref item type + key usage,
	// as only the account and service attributes can make a generic keychain item unique.
	// For 'iprf' type items (but not 'cprf'), we append a trailing space. This insures that
	// we can save a certificate preference if an identity preference already exists for the
	// given service name, and vice-versa.
	// If the key usage is 0 (i.e. the normal case), we omit the appended key usage string.
	//
    CFStringRef labelStr = nil;
	certificate->inferLabel(false, &labelStr);
	if (!labelStr) {
        MacOSError::throwMe(errSecDataTooLarge); // data is "in a format which cannot be displayed"
	}
	CFIndex accountUTF8Len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(labelStr), kCFStringEncodingUTF8) + 1;
	const char *templateStr = "%s [key usage 0x%X]";
	const int keyUsageMaxStrLen = 8;
	accountUTF8Len += strlen(templateStr) + keyUsageMaxStrLen;
	char accountUTF8[accountUTF8Len];
    if (!CFStringGetCString(labelStr, accountUTF8, accountUTF8Len-1, kCFStringEncodingUTF8))
		accountUTF8[0] = (char)'\0';
	if (keyUsage)
		snprintf(accountUTF8, accountUTF8Len-1, templateStr, accountUTF8, keyUsage);
	snprintf(accountUTF8, accountUTF8Len-1, "%s ", accountUTF8);
    CssmData account(const_cast<char *>(accountUTF8), strlen(accountUTF8));
    CFRelease(labelStr);

	// service attribute (name provided by the caller)
	CFIndex serviceUTF8Len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(name), kCFStringEncodingUTF8) + 1;;
	char serviceUTF8[serviceUTF8Len];
    if (!CFStringGetCString(name, serviceUTF8, serviceUTF8Len-1, kCFStringEncodingUTF8))
        serviceUTF8[0] = (char)'\0';
    CssmData service(const_cast<char *>(serviceUTF8), strlen(serviceUTF8));

    // look for existing identity preference item, in case this is an update
	StorageManager::KeychainList keychains;
	globals().storageManager.getSearchList(keychains);
	KCCursor cursor(keychains, kSecGenericPasswordItemClass, NULL);
    FourCharCode itemType = 'iprf';
    cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecServiceItemAttr), service);
	cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecTypeItemAttr), itemType);
    if (keyUsage) {
        cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecScriptCodeItemAttr), (sint32)keyUsage);
	}

	Item item(kSecGenericPasswordItemClass, 'aapl', 0, NULL, false);
    bool add = (!cursor->next(item));
	// at this point, we either have a new item to add or an existing item to update

    // set item attribute values
    item->setAttribute(Schema::attributeInfo(kSecServiceItemAttr), service);
    item->setAttribute(Schema::attributeInfo(kSecTypeItemAttr), itemType);
    item->setAttribute(Schema::attributeInfo(kSecAccountItemAttr), account);
	item->setAttribute(Schema::attributeInfo(kSecScriptCodeItemAttr), (sint32)keyUsage);
    item->setAttribute(Schema::attributeInfo(kSecLabelItemAttr), service);

	// generic attribute (store persistent certificate reference)
	CFDataRef pItemRef = nil;
    certificate->copyPersistentReference(pItemRef);
	if (!pItemRef) {
		MacOSError::throwMe(errSecInvalidItemRef);
    }
	const UInt8 *dataPtr = CFDataGetBytePtr(pItemRef);
	CFIndex dataLen = CFDataGetLength(pItemRef);
	CssmData pref(const_cast<void *>(reinterpret_cast<const void *>(dataPtr)), dataLen);
	item->setAttribute(Schema::attributeInfo(kSecGenericItemAttr), pref);
	CFRelease(pItemRef);

    if (add) {
        Keychain keychain = nil;
        try {
            keychain = globals().storageManager.defaultKeychain();
            if (!keychain->exists())
                MacOSError::throwMe(errSecNoSuchKeychain);	// Might be deleted or not available at this time.
        }
        catch(...) {
            keychain = globals().storageManager.defaultKeychainUI(item);
        }

		try {
			keychain->add(item);
		}
		catch (const MacOSError &err) {
			if (err.osStatus() != errSecDuplicateItem)
				throw; // if item already exists, fall through to update
		}
    }
	item->update();

    END_SECAPI
}
Esempio n. 16
0
void IOSCfgParser::cfgfile() {
	
	try {      // for error handling
		{ // ( ... )+
		int _cnt3=0;
		for (;;) {
			switch ( LA(1)) {
			case LINE_COMMENT:
			{
				comment();
				break;
			}
			case IOSVERSION:
			{
				version();
				break;
			}
			case HOSTNAME:
			{
				hostname();
				break;
			}
			case IP:
			{
				ip_commands();
				break;
			}
			case INTRFACE:
			{
				intrface();
				break;
			}
			case CONTROLLER:
			{
				controller();
				break;
			}
			case VLAN:
			{
				vlan();
				break;
			}
			case ACCESS_LIST:
			{
				access_list_commands();
				break;
			}
			case EXIT:
			{
				exit();
				break;
			}
			case DESCRIPTION:
			{
				description();
				break;
			}
			case SHUTDOWN:
			{
				shutdown();
				break;
			}
			case CERTIFICATE:
			{
				certificate();
				break;
			}
			case QUIT:
			{
				quit();
				break;
			}
			case WORD:
			{
				unknown_command();
				break;
			}
			case NEWLINE:
			{
				match(NEWLINE);
				break;
			}
			default:
			{
				if ( _cnt3>=1 ) { goto _loop3; } else {throw ANTLR_USE_NAMESPACE(antlr)NoViableAltException(LT(1), getFilename());}
			}
			}
			_cnt3++;
		}
		_loop3:;
		}  // ( ... )+
	}
	catch (ANTLR_USE_NAMESPACE(antlr)RecognitionException& ex) {
		if( inputState->guessing == 0 ) {
			reportError(ex);
			recover(ex,_tokenSet_0);
		} else {
			throw;
		}
	}
}
Esempio n. 17
0
RefPtr<DtlsIdentity> DtlsIdentity::Generate() {
    UniquePK11SlotInfo slot(PK11_GetInternalSlot());
    if (!slot) {
        return nullptr;
    }

    uint8_t random_name[16];

    SECStatus rv = PK11_GenerateRandomOnSlot(slot.get(), random_name,
                   sizeof(random_name));
    if (rv != SECSuccess)
        return nullptr;

    std::string name;
    char chunk[3];
    for (size_t i = 0; i < sizeof(random_name); ++i) {
        SprintfLiteral(chunk, "%.2x", random_name[i]);
        name += chunk;
    }

    std::string subject_name_string = "CN=" + name;
    UniqueCERTName subject_name(CERT_AsciiToName(subject_name_string.c_str()));
    if (!subject_name) {
        return nullptr;
    }

    unsigned char paramBuf[12]; // OIDs are small
    SECItem ecdsaParams = { siBuffer, paramBuf, sizeof(paramBuf) };
    SECOidData* oidData = SECOID_FindOIDByTag(SEC_OID_SECG_EC_SECP256R1);
    if (!oidData || (oidData->oid.len > (sizeof(paramBuf) - 2))) {
        return nullptr;
    }
    ecdsaParams.data[0] = SEC_ASN1_OBJECT_ID;
    ecdsaParams.data[1] = oidData->oid.len;
    memcpy(ecdsaParams.data + 2, oidData->oid.data, oidData->oid.len);
    ecdsaParams.len = oidData->oid.len + 2;

    SECKEYPublicKey *pubkey;
    UniqueSECKEYPrivateKey private_key(
        PK11_GenerateKeyPair(slot.get(),
                             CKM_EC_KEY_PAIR_GEN, &ecdsaParams, &pubkey,
                             PR_FALSE, PR_TRUE, nullptr));
    if (private_key == nullptr)
        return nullptr;
    UniqueSECKEYPublicKey public_key(pubkey);
    pubkey = nullptr;

    UniqueCERTSubjectPublicKeyInfo spki(
        SECKEY_CreateSubjectPublicKeyInfo(public_key.get()));
    if (!spki) {
        return nullptr;
    }

    UniqueCERTCertificateRequest certreq(
        CERT_CreateCertificateRequest(subject_name.get(), spki.get(), nullptr));
    if (!certreq) {
        return nullptr;
    }

    // From 1 day before todayto 30 days after.
    // This is a sort of arbitrary range designed to be valid
    // now with some slack in case the other side expects
    // some before expiry.
    //
    // Note: explicit casts necessary to avoid
    //       warning C4307: '*' : integral constant overflow
    static const PRTime oneDay = PRTime(PR_USEC_PER_SEC)
                                 * PRTime(60)  // sec
                                 * PRTime(60)  // min
                                 * PRTime(24); // hours
    PRTime now = PR_Now();
    PRTime notBefore = now - oneDay;
    PRTime notAfter = now + (PRTime(30) * oneDay);

    UniqueCERTValidity validity(CERT_CreateValidity(notBefore, notAfter));
    if (!validity) {
        return nullptr;
    }

    unsigned long serial;
    // Note: This serial in principle could collide, but it's unlikely
    rv = PK11_GenerateRandomOnSlot(slot.get(),
                                   reinterpret_cast<unsigned char *>(&serial),
                                   sizeof(serial));
    if (rv != SECSuccess) {
        return nullptr;
    }

    UniqueCERTCertificate certificate(
        CERT_CreateCertificate(serial, subject_name.get(), validity.get(),
                               certreq.get()));
    if (!certificate) {
        return nullptr;
    }

    PLArenaPool *arena = certificate->arena;

    rv = SECOID_SetAlgorithmID(arena, &certificate->signature,
                               SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE, 0);
    if (rv != SECSuccess)
        return nullptr;

    // Set version to X509v3.
    *(certificate->version.data) = SEC_CERTIFICATE_VERSION_3;
    certificate->version.len = 1;

    SECItem innerDER;
    innerDER.len = 0;
    innerDER.data = nullptr;

    if (!SEC_ASN1EncodeItem(arena, &innerDER, certificate.get(),
                            SEC_ASN1_GET(CERT_CertificateTemplate))) {
        return nullptr;
    }

    SECItem *signedCert = PORT_ArenaZNew(arena, SECItem);
    if (!signedCert) {
        return nullptr;
    }

    rv = SEC_DerSignData(arena, signedCert, innerDER.data, innerDER.len,
                         private_key.get(),
                         SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE);
    if (rv != SECSuccess) {
        return nullptr;
    }
    certificate->derCert = *signedCert;

    RefPtr<DtlsIdentity> identity = new DtlsIdentity(Move(private_key),
            Move(certificate),
            ssl_kea_ecdh);
    return identity.forget();
}
Esempio n. 18
0
File: ssu.cpp Progetto: lbt/ssu
void Ssu::updateCredentials(bool force){
  SsuCoreConfig *settings = SsuCoreConfig::instance();
  errorFlag = false;

  SsuLog *ssuLog = SsuLog::instance();

  if (deviceInfo.deviceUid() == ""){
    setError("No valid UID available for your device. For phones: is your modem online?");
    return;
  }

  QString ssuCaCertificate, ssuCredentialsUrl;
  if (!settings->contains("ca-certificate")){
    setError("CA certificate for SSU not set (config key 'ca-certificate')");
    return;
  } else
    ssuCaCertificate = settings->value("ca-certificate").toString();

  if (!settings->contains("credentials-url")){
    ssuCredentialsUrl = repoUrl("credentials-url");
    if (ssuCredentialsUrl.isEmpty()){
      setError("URL for credentials update not set (config key 'credentials-url')");
      return;
    }
  } else
    ssuCredentialsUrl = settings->value("credentials-url").toString();

  if (!isRegistered()){
    setError("Device is not registered.");
    return;
  }

  if (!force){
    // skip updating if the last update was less than 30 minutes ago
    QDateTime now = QDateTime::currentDateTime();

    if (settings->contains("lastCredentialsUpdate")){
      QDateTime last = settings->value("lastCredentialsUpdate").toDateTime();
      if (last >= now.addSecs(-1800)){
        ssuLog->print(LOG_DEBUG, QString("Skipping credentials update, last update was at %1")
                     .arg(last.toString()));
        emit done();
        return;
      }
    }
  }

  // check when the last update was, decide if an update is required
  QSslConfiguration sslConfiguration;
  if (!useSslVerify())
    sslConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);

  QSslKey privateKey(settings->value("privateKey").toByteArray(), QSsl::Rsa);
  QSslCertificate certificate(settings->value("certificate").toByteArray());

  QList<QSslCertificate> caCertificates;
  caCertificates << QSslCertificate::fromPath(ssuCaCertificate);
  sslConfiguration.setCaCertificates(caCertificates);

  sslConfiguration.setPrivateKey(privateKey);
  sslConfiguration.setLocalCertificate(certificate);

  QNetworkRequest request;
  request.setUrl(QUrl(ssuCredentialsUrl.arg(deviceInfo.deviceUid())));

  ssuLog->print(LOG_DEBUG, QString("Sending credential update request to %1")
               .arg(request.url().toString()));
  request.setSslConfiguration(sslConfiguration);

  pendingRequests++;
  manager->get(request);
}
Esempio n. 19
0
/*!
  Load the virtual hosts from a XML configuration file
  Returns non-null on errors.
  \param filename The XML file to open.
 */
int XmlVhostHandler::load (const char *filename)
{
  XmlParser parser;
  xmlDocPtr doc;
  xmlNodePtr node;
  if (parser.open (filename))
    {
      Server::getInstance ()->log (MYSERVER_LOG_MSG_ERROR,
                                         _("Error opening %s"), filename);
      return -1;
    }
  doc = parser.getDoc ();
  node = doc->children->children;

  for (; node; node = node->next )
    {
      xmlNodePtr lcur;
      Vhost *vh;
      if (xmlStrcmp (node->name, (const xmlChar *) "VHOST"))
        continue;
      lcur = node->children;
      vh = new Vhost (logManager);
      SslContext* sslContext = vh->getVhostSSLContext ();

      while (lcur)
        {
          XmlConf::build (lcur, vh->getHashedDataTrees (),
                          vh->getHashedData ());

          if (!xmlStrcmp (lcur->name, (const xmlChar *) "HOST"))
            {
              int useRegex = 0;
              for (xmlAttr *attrs = lcur->properties; attrs; attrs = attrs->next)
                {
                  if (!xmlStrcmp (attrs->name, (const xmlChar *) "isRegex")
                      && attrs->children && attrs->children->content
                      && (!xmlStrcmp (attrs->children->content,
                                     (const xmlChar *) "YES")))
                        useRegex = 1;
                }

              vh->addHost ((const char *)lcur->children->content, useRegex);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "NAME"))
            {
              vh->setName ((char *) lcur->children->content);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "LOCATION"))
            {
              string loc;

              for (xmlAttr *attrs = lcur->properties; attrs; attrs = attrs->next)
                if (!xmlStrcmp (attrs->name, (const xmlChar *) "path"))
                  loc = ((const char *) attrs->children->content);

              MimeRecord *record = XmlMimeHandler::readRecord (lcur);
              MimeRecord *prev = vh->addLocationMime (loc, record);
              if (prev)
                {
                  Server::getInstance ()->log (MYSERVER_LOG_MSG_ERROR,
                     _("The location `%s' is registered multiple times"),
                                               loc.c_str ());

                  delete prev;
                }

              vh->getLocationsMime ()->put (loc, record);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "SSL_PRIVATEKEY"))
            {
              string pk ((char *) lcur->children->content);
              sslContext->setPrivateKeyFile (pk);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "SSL_CERTIFICATE"))
            {
              string certificate ((char *) lcur->children->content);
              sslContext->setCertificateFile (certificate);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "CONNECTIONS_PRIORITY"))
            {
              vh->setDefaultPriority (atoi ((const char *)lcur->children->content));
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "SSL_PASSWORD"))
            {
              string pw ((char *) lcur->children->content);
              sslContext->setPassword (pw);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "IP"))
            {
              int useRegex = 0;
              xmlAttr *attrs = lcur->properties;

              while (attrs)
                {
                  if (!xmlStrcmp (attrs->name, (const xmlChar *) "isRegex")
                      && !xmlStrcmp (attrs->children->content,
                                     (const xmlChar *) "YES"))
                    useRegex = 1;

                  attrs = attrs->next;
                }

              vh->addIP ((char *) lcur->children->content, useRegex);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "PORT"))
            {
              int val = atoi ((char *) lcur->children->content);
              if (val > (1 << 16) || val <= 0)
                Server::getInstance ()->log (MYSERVER_LOG_MSG_ERROR,
                      _("An invalid port was specified: %s"),
                                             lcur->children->content);
              vh->setPort ((u_short)val);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "PROTOCOL"))
            {
              char* lastChar = (char *) lcur->children->content;
              while (*lastChar != '\0')
                {
                  *lastChar = tolower (*lastChar);
                  lastChar++;
                }
              vh->setProtocolName ((char *) lcur->children->content);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "DOCROOT"))
            {
              char* lastChar = (char *) lcur->children->content;
              while (*(lastChar+1) != '\0')
                lastChar++;

              if (*lastChar == '\\' || *lastChar == '/')
                *lastChar = '\0';

              vh->setDocumentRoot ((const char *)lcur->children->content);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "SYSROOT"))
            {
              char* lastChar = (char *) lcur->children->content;

              while (*(lastChar+1) != '\0')
                lastChar++;

              if (*lastChar == '\\' || *lastChar == '/')
                *lastChar = '\0';

              vh->setSystemRoot ((const char *)lcur->children->content);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "CACHEROOT"))
            {
              char* lastChar = (char *) lcur->children->content;

              while (*(lastChar+1) != '\0')
                lastChar++;

              if (*lastChar == '\\' || *lastChar == '/')
                *lastChar = '\0';

              vh->setCacheRoot ((const char *)lcur->children->content);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "ACCESSLOG"))
            {
              loadXMLlogData ("ACCESSLOG", vh, lcur);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "WARNINGLOG"))
            {
              loadXMLlogData ("WARNINGLOG", vh, lcur);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "MIME_FILE"))
            {
              string hnd ("xml");
              for (xmlAttr *attrs = lcur->properties; attrs; attrs = attrs->next)
                {
                  if (!xmlStrcmp (attrs->name, (const xmlChar *) "name")
                      && attrs->children && attrs->children->content)
                    hnd.assign((const char *) attrs->children->content);
                }

              const char *filename = (const char *) lcur->children->content;
              MimeManagerHandler *handler =
                Server::getInstance ()->getMimeManager ()->buildHandler (hnd);

              try
                {
                  handler->load (filename);
                }
              catch (...)
                {
                  delete handler;
                  handler = NULL;
                  Server::getInstance ()->log (MYSERVER_LOG_MSG_ERROR,
                                         _("Error loading mime types file: %s"),
                                               filename);

                }
              vh->setMimeHandler (handler);
            }
          else if (!xmlStrcmp (lcur->name, (const xmlChar *) "THROTTLING_RATE"))
            {
              u_long rate = (u_long)atoi ((char *) lcur->children->content);
              vh->setThrottlingRate (rate);
            }

          lcur = lcur->next;
        }/* while (lcur)  */

      if (vh->openLogFiles ())
        {
          Server::getInstance ()->log (MYSERVER_LOG_MSG_ERROR,
                                             _("Error opening log files"));
          delete vh;
          vh = 0;
          continue;
        }

      if (vh->initializeSSL () < 0)
        {
          Server::getInstance ()->log (MYSERVER_LOG_MSG_ERROR,
                                             _("Error initializing SSL for %s"),
                                             vh->getName ());
          delete vh;
          vh = 0;
          continue;
        }

      if (addVHost (vh))
        {
          Server::getInstance ()->log (MYSERVER_LOG_MSG_ERROR,
                                             _("Internal error"));
          delete vh;
          vh = 0;
          continue;
        }
    }
  parser.close ();

  changeLocationsOwner ();

  return 0;
}