Пример #1
0
static bool
ConnSSL_LoadServerKey_gnutls(void)
{
	int err;
	const char *cert_file;

	err = gnutls_certificate_allocate_credentials(&x509_cred);
	if (err < 0) {
		Log(LOG_ERR, "gnutls_certificate_allocate_credentials: %s", gnutls_strerror(err));
		return false;
	}

	cert_file = Conf_SSLOptions.CertFile ? Conf_SSLOptions.CertFile:Conf_SSLOptions.KeyFile;
	if (!cert_file) {
		Log(LOG_NOTICE, "No SSL server key configured, SSL disabled.");
		return false;
	}

	if (array_bytes(&Conf_SSLOptions.KeyFilePassword))
		Log(LOG_WARNING,
		    "Ignoring KeyFilePassword: Not supported by GNUTLS.");

	if (!Load_DH_params())
		return false;

	gnutls_certificate_set_dh_params(x509_cred, dh_params);
	err = gnutls_certificate_set_x509_key_file(x509_cred, cert_file, Conf_SSLOptions.KeyFile, GNUTLS_X509_FMT_PEM);
	if (err < 0) {
		Log(LOG_ERR, "gnutls_certificate_set_x509_key_file (cert %s, key %s): %s",
				cert_file, Conf_SSLOptions.KeyFile ? Conf_SSLOptions.KeyFile : "(NULL)", gnutls_strerror(err));
		return false;
	}
	return true;
}
Пример #2
0
struct rfbssl_ctx *rfbssl_init_global(char *key, char *cert)
{
    int ret = GNUTLS_E_SUCCESS;
    struct rfbssl_ctx *ctx = NULL;

    if (NULL == (ctx = malloc(sizeof(struct rfbssl_ctx)))) {
	ret = GNUTLS_E_MEMORY_ERROR;
    } else if (!GNUTLS_E_SUCCESS == (ret = gnutls_global_init())) {
	/* */
    } else if (!GNUTLS_E_SUCCESS == (ret = gnutls_certificate_allocate_credentials(&ctx->x509_cred))) {
	/* */
    } else if ((ret = gnutls_certificate_set_x509_trust_file(ctx->x509_cred, cert, GNUTLS_X509_FMT_PEM)) < 0) {
	/* */
    } else if (!GNUTLS_E_SUCCESS == (ret = gnutls_certificate_set_x509_key_file(ctx->x509_cred, cert, key, GNUTLS_X509_FMT_PEM))) {
	/* */
    } else if (!GNUTLS_E_SUCCESS == (ret = generate_dh_params(ctx))) {
	/* */
#ifdef I_LIKE_RSA_PARAMS_THAT_MUCH
    } else if (!GNUTLS_E_SUCCESS == (ret = generate_rsa_params(ctx))) {
	/* */
#endif
    } else {
	gnutls_global_set_log_function(rfbssl_log_func);
	gnutls_global_set_log_level(1);
	gnutls_certificate_set_dh_params(ctx->x509_cred, ctx->dh_params);
	/* newly allocated memory should be initialized, at least where it is important */
	ctx->peekstart = ctx->peeklen = 0;
	return ctx;
    }

    free(ctx);
    return NULL;
}
Пример #3
0
    void TLSSocket::init(const std::string& caPath,
            const std::string& crlPath,
            const std::string& certPath,
            const std::string& keyPath) {
        gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
        gnutls_global_init();    	
        gnutls_certificate_allocate_credentials(&xcred);
        if (!caPath.empty()) {
            gnutls_certificate_set_x509_trust_file(xcred, 
                    caPath.c_str(), 
                    GNUTLS_X509_FMT_PEM);
            gnutls_certificate_set_verify_flags (xcred,
                    GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
        }
        if (!crlPath.empty()) {
            gnutls_certificate_set_x509_crl_file(xcred,
                    crlPath.c_str(), 
                    GNUTLS_X509_FMT_PEM);
        }
        gnutls_certificate_set_x509_key_file(xcred,
                certPath.c_str(),
                keyPath.c_str(),
                GNUTLS_X509_FMT_PEM);
        gnutls_dh_params_init(&dh_params);
        gnutls_dh_params_generate2(dh_params, 1024);
        gnutls_priority_init(&priority_cache, "NORMAL", NULL);
        gnutls_certificate_set_dh_params(xcred, dh_params);

    }
Пример #4
0
bool    Plugin::onLoad(LightBird::IApi *api)
{
    int         error;
    const char  *err_pos = NULL;

    this->api = api;
    try
    {
        ASSERT_INIT(gnutls_global_init(), "global");
        if (!gnutls_check_version(GNUTLS_CHECK_VERSION))
            throw Properties("error", "Bad GnuTLS version").add("version required", GNUTLS_CHECK_VERSION);
        gnutls_global_set_audit_log_function(Plugin::log);
        this->_loadConfiguration();
        this->_loadPrivateKey();
        this->_loadCertificate();
        this->_loadDHParams();
        ASSERT_INIT(gnutls_certificate_allocate_credentials(&this->x509_cred), "credentials");
        ASSERT(gnutls_certificate_set_x509_key(this->x509_cred, &this->crt, 1, this->key));
        ASSERT_INIT(gnutls_priority_init(&this->priority, this->priorityStrings.data(), &err_pos), "priority");
        gnutls_certificate_set_dh_params(this->x509_cred, this->dhParams);
    }
    catch (Properties p)
    {
        if (err_pos)
            p.add("error position", err_pos).add("priority string", this->priorityStrings);
        LOG_FATAL("Unable to initialize GnuTLS", p.toMap(), "Plugin", "onLoad");
        this->_deinit();
        return (false);
    }
    this->api->contexts().declareInstance("handshake", (this->handshake = new Handshake(this->api, this->handshakeTimeout)));
    this->api->contexts().declareInstance("record", (this->record = new Record(this->api)));
    return (true);
}
Пример #5
0
  //////////////////////////////////////////////////////////////////////
  // GnuTlsX509Cred
  //
  GnuTlsX509Cred::GnuTlsX509Cred(const char* certificateFile, const char* privateKeyFile)
  {
    int ret;

    log_debug("gnutls_certificate_allocate_credentials");
    ret = gnutls_certificate_allocate_credentials(&_x509_cred);
    if (ret != 0)
      throw GnuTlsException("gnutls_certificate_allocate_credentials", ret);
    log_debug("gnutls_certificate_allocate_credentials => " << _x509_cred);

    // gnutls_certificate_set_x509_trust_file(x509_cred, caFile, GNUTLS_X509_FMT_PEM);
    // gnutls_certificate_set_x509_crl_file(x509_cred, crlFile, GNUTLS_X509_FMT_PEM);

    try
    {
      log_debug("gnutls_certificate_set_x509_key_file(x509_cred, \""
        << certificateFile << "\", \"" << privateKeyFile
        << "\", GNUTLS_X509_FMT_PEM)");
      ret = gnutls_certificate_set_x509_key_file(_x509_cred, certificateFile,
        privateKeyFile, GNUTLS_X509_FMT_PEM);
      if (ret < 0)
        throw GnuTlsException("gnutls_certificate_set_x509_key_file", ret);

      log_debug("gnutls_certificate_set_dh_params");
      gnutls_certificate_set_dh_params(_x509_cred, _init.getDhParams());
    }
    catch (...)
    {
      log_debug("gnutls_certificate_free_credentials");
      gnutls_certificate_free_credentials(_x509_cred);
      throw;
    }
  }
Пример #6
0
int
rb_setup_ssl_server(const char *cert, const char *keyfile, const char *dhfile)
{
	int ret;
	gnutls_datum_t *d_cert, *d_key;
	if(cert == NULL)
	{
		rb_lib_log("rb_setup_ssl_server: No certificate file");
		return 0;
	}

	if((d_cert = rb_load_file_into_datum_t(cert)) == NULL)
	{
		rb_lib_log("rb_setup_ssl_server: Error loading certificate: %s", strerror(errno));
		return 0;
	}

	if((d_key = rb_load_file_into_datum_t(keyfile)) == NULL)
	{
		rb_lib_log("rb_setup_ssl_server: Error loading key: %s", strerror(errno));
		return 0;
	}


	if((ret =
	    gnutls_certificate_set_x509_key_mem(x509, d_cert, d_key,
						GNUTLS_X509_FMT_PEM)) != GNUTLS_E_SUCCESS)
	{
		rb_lib_log("rb_setup_ssl_server: Error loading certificate or key file: %s",
			   gnutls_strerror(ret));
		return 0;
	}
	rb_free_datum_t(d_cert);
	rb_free_datum_t(d_key);

	if(dhfile != NULL)
	{
		if(gnutls_dh_params_init(&dh_params) == GNUTLS_E_SUCCESS)
		{
			gnutls_datum_t *data;
			int xret;
			data = rb_load_file_into_datum_t(dhfile);
			if(data != NULL)
			{
				xret = gnutls_dh_params_import_pkcs3(dh_params, data,
								     GNUTLS_X509_FMT_PEM);
				if(xret < 0)
					rb_lib_log
						("rb_setup_ssl_server: Error parsing DH file: %s\n",
						 gnutls_strerror(xret));
				rb_free_datum_t(data);
			}
			gnutls_certificate_set_dh_params(x509, dh_params);
		}
		else
			rb_lib_log("rb_setup_ssl_server: Unable to setup DH parameters");
	}
	return 1;
}
Пример #7
0
/** Generate initial DH and RSA params.
 * Loads the pre-generated DH primes.
 */
static void _crywrap_tls_init(void)
{

	gnutls_dh_params_init(&dh_params);
	gnutls_dh_params_import_pkcs3(dh_params, &dh_file,
				      GNUTLS_X509_FMT_PEM);

	gnutls_certificate_set_dh_params(cred, dh_params);
}
Пример #8
0
void TLSServer::init (
  const std::string& ca,
  const std::string& crl,
  const std::string& cert,
  const std::string& key)
{
  _ca   = ca;
  _crl  = crl;
  _cert = cert;
  _key  = key;

  int ret = gnutls_global_init ();
  if (ret < 0)
    throw format ("TLS init error. {1}", gnutls_strerror (ret));

  ret = gnutls_certificate_allocate_credentials (&_credentials);
  if (ret < 0)
    throw format ("TLS allocation error. {1}", gnutls_strerror (ret));

  if (_ca != "" &&
      (ret = gnutls_certificate_set_x509_trust_file (_credentials, _ca.c_str (), GNUTLS_X509_FMT_PEM)) < 0)
    throw format ("Bad CA file. {1}", gnutls_strerror (ret));

  if ( _crl != "" &&
      (ret = gnutls_certificate_set_x509_crl_file (_credentials, _crl.c_str (), GNUTLS_X509_FMT_PEM)) < 0)
    throw format ("Bad CRL file. {1}", gnutls_strerror (ret));

  if (_cert != "" &&
      _key != "" &&
      (ret = gnutls_certificate_set_x509_key_file (_credentials, _cert.c_str (), _key.c_str (), GNUTLS_X509_FMT_PEM)) < 0)
    throw format ("Bad CERT file. {1}", gnutls_strerror (ret));

#if GNUTLS_VERSION_NUMBER >= 0x020b00
#if GNUTLS_VERSION_NUMBER >= 0x03000d
  unsigned int bits = gnutls_sec_param_to_pk_bits (GNUTLS_PK_DH, GNUTLS_SEC_PARAM_LEGACY);
#else
  unsigned int bits = gnutls_sec_param_to_pk_bits (GNUTLS_PK_DH, GNUTLS_SEC_PARAM_NORMAL);
#endif
#else
  unsigned int bits = DH_BITS;
#endif
  gnutls_dh_params_init (&_params);
  gnutls_dh_params_generate2 (_params, bits);

  if (_ciphers == "")
    _ciphers = "NORMAL";
  gnutls_priority_init (&_priorities, _ciphers.c_str (), NULL);
  gnutls_certificate_set_dh_params (_credentials, _params);

#if GNUTLS_VERSION_NUMBER >= 0x02090a
  // The automatic verification for the client certificate with
  // gnutls_certificate_set_verify_function only works with gnutls
  // >=2.9.10. So with older versions we should call the verify function
  // manually after the gnutls handshake.
  gnutls_certificate_set_verify_function (_credentials, verify_certificate_callback);
#endif
}
Пример #9
0
void
server_start (void)
{
  /* this must be called once in the program
   */
  gnutls_global_init ();

  gnutls_global_set_log_function (tls_log_func);
  gnutls_global_set_log_level (4711);

  gnutls_certificate_allocate_credentials (&x509_cred);
  gnutls_certificate_set_x509_trust_mem (x509_cred, &ca, GNUTLS_X509_FMT_PEM);

  gnutls_certificate_set_x509_key_mem (x509_cred, &server_cert, &server_key,
				       GNUTLS_X509_FMT_PEM);

  success ("Launched, generating DH parameters...\n");

  generate_dh_params ();

  gnutls_certificate_set_dh_params (x509_cred, dh_params);

  /* Socket operations
   */
  listen_sd = socket (AF_INET, SOCK_STREAM, 0);
  if (err == -1)
    {
      perror ("socket");
      fail ("server: socket failed\n");
      return;
    }

  memset (&sa_serv, '\0', sizeof (sa_serv));
  sa_serv.sin_family = AF_INET;
  sa_serv.sin_addr.s_addr = INADDR_ANY;
  sa_serv.sin_port = htons (PORT);	/* Server Port number */

  setsockopt (listen_sd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (int));

  err = bind (listen_sd, (SA *) & sa_serv, sizeof (sa_serv));
  if (err == -1)
    {
      perror ("bind");
      fail ("server: bind failed\n");
      return;
    }

  err = listen (listen_sd, 1024);
  if (err == -1)
    {
      perror ("listen");
      fail ("server: listen failed\n");
      return;
    }

  success ("server: ready. Listening to port '%d'.\n", PORT);
}
Пример #10
0
static gnutls_certificate_credentials_t
CreateX509CertCredential(rfbCredential *cred)
{
  gnutls_certificate_credentials_t x509_cred;
  int ret;

  if (!cred->x509Credential.x509CACertFile)
  {
    rfbClientLog("No CA certificate provided.\n");
    return NULL;
  }

  if ((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0)
  {
    rfbClientLog("Cannot allocate credentials: %s.\n", gnutls_strerror(ret));
    return NULL;
  }
  if ((ret = gnutls_certificate_set_x509_trust_file(x509_cred,
    cred->x509Credential.x509CACertFile, GNUTLS_X509_FMT_PEM)) < 0)
  {
    rfbClientLog("Cannot load CA credentials: %s.\n", gnutls_strerror(ret));
    gnutls_certificate_free_credentials (x509_cred);
    return NULL;
  }
  if (cred->x509Credential.x509ClientCertFile && cred->x509Credential.x509ClientKeyFile)
  {
    if ((ret = gnutls_certificate_set_x509_key_file(x509_cred,
      cred->x509Credential.x509ClientCertFile, cred->x509Credential.x509ClientKeyFile,
      GNUTLS_X509_FMT_PEM)) < 0)
    {
      rfbClientLog("Cannot load client certificate or key: %s.\n", gnutls_strerror(ret));
      gnutls_certificate_free_credentials (x509_cred);
      return NULL;
    }
  } else
  {
    rfbClientLog("No client certificate or key provided.\n");
  }
  if (cred->x509Credential.x509CACrlFile)
  {
    if ((ret = gnutls_certificate_set_x509_crl_file(x509_cred,
      cred->x509Credential.x509CACrlFile, GNUTLS_X509_FMT_PEM)) < 0)
    {
      rfbClientLog("Cannot load CRL: %s.\n", gnutls_strerror(ret));
      gnutls_certificate_free_credentials (x509_cred);
      return NULL;
    }
  } else
  {
    rfbClientLog("No CRL provided.\n");
  }
  gnutls_certificate_set_dh_params (x509_cred, rfbDHParams);
  return x509_cred;
}
Пример #11
0
static gnutls_certificate_credentials_t vnc_tls_initialize_x509_cred(VncDisplay *vd)
{
    gnutls_certificate_credentials_t x509_cred;
    int ret;

    if (!vd->tls.x509cacert) {
        VNC_DEBUG("No CA x509 certificate specified\n");
        return NULL;
    }
    if (!vd->tls.x509cert) {
        VNC_DEBUG("No server x509 certificate specified\n");
        return NULL;
    }
    if (!vd->tls.x509key) {
        VNC_DEBUG("No server private key specified\n");
        return NULL;
    }

    if ((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0) {
        VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
        return NULL;
    }
    if ((ret = gnutls_certificate_set_x509_trust_file(x509_cred,
                                                      vd->tls.x509cacert,
                                                      GNUTLS_X509_FMT_PEM)) < 0) {
        VNC_DEBUG("Cannot load CA certificate %s\n", gnutls_strerror(ret));
        gnutls_certificate_free_credentials(x509_cred);
        return NULL;
    }

    if ((ret = gnutls_certificate_set_x509_key_file (x509_cred,
                                                     vd->tls.x509cert,
                                                     vd->tls.x509key,
                                                     GNUTLS_X509_FMT_PEM)) < 0) {
        VNC_DEBUG("Cannot load certificate & key %s\n", gnutls_strerror(ret));
        gnutls_certificate_free_credentials(x509_cred);
        return NULL;
    }

    if (vd->tls.x509cacrl) {
        if ((ret = gnutls_certificate_set_x509_crl_file(x509_cred,
                                                        vd->tls.x509cacrl,
                                                        GNUTLS_X509_FMT_PEM)) < 0) {
            VNC_DEBUG("Cannot load CRL %s\n", gnutls_strerror(ret));
            gnutls_certificate_free_credentials(x509_cred);
            return NULL;
        }
    }

    gnutls_certificate_set_dh_params (x509_cred, dh_params);

    return x509_cred;
}
Пример #12
0
struct cert* loadCert(const char* ca, const char* cert, const char* key) {
	struct cert* oc = xmalloc(sizeof(struct cert));
	gnutls_certificate_allocate_credentials(&oc->cert);
	if (ca != NULL) gnutls_certificate_set_x509_trust_file(oc->cert, ca, GNUTLS_X509_FMT_PEM);
	int e1 = gnutls_certificate_set_x509_key_file(oc->cert, cert, key, GNUTLS_X509_FMT_PEM);
	if (e1 < 0) {
		return NULL;
	}
	gnutls_priority_init(&oc->priority, "PERFORMANCE:%SERVER_PRECEDENCE", NULL);
	gnutls_certificate_set_dh_params(oc->cert, dh_params);
	return oc;
}
Пример #13
0
int ufwissl_ssl_context_keypair_from_data(ufwissl_ssl_context * ctx,
					ufwissl_ssl_client_cert * cert)
{
	int ret;
	ret = gnutls_certificate_set_x509_key(ctx->cred, &cert->cert.subject,
					    1, cert->pkey);
	if (ret != 0)
		return UFWISSL_ERROR;
	gnutls_certificate_set_dh_params(ctx->cred, ctx->dh);

	return (ret == 0) ? UFWISSL_OK : UFWISSL_ERROR;
}
Пример #14
0
static Ecore_Con_Ssl_Error
_ecore_con_ssl_server_prepare_gnutls(Ecore_Con_Server *svr,
                                     int               ssl_type)
{
   int ret;

   if (ssl_type & ECORE_CON_USE_SSL2)
     return ECORE_CON_SSL_ERROR_SSL2_NOT_SUPPORTED;

   switch (ssl_type)
     {
      case ECORE_CON_USE_SSL3:
      case ECORE_CON_USE_SSL3 | ECORE_CON_LOAD_CERT:
      case ECORE_CON_USE_TLS:
      case ECORE_CON_USE_TLS | ECORE_CON_LOAD_CERT:
      case ECORE_CON_USE_MIXED:
      case ECORE_CON_USE_MIXED | ECORE_CON_LOAD_CERT:
        break;

      default:
        return ECORE_CON_SSL_ERROR_NONE;
     }

   SSL_ERROR_CHECK_GOTO_ERROR(ret = gnutls_certificate_allocate_credentials(&svr->cert));

   if ((!svr->use_cert) && svr->created)
     {
        SSL_ERROR_CHECK_GOTO_ERROR(ret = gnutls_dh_params_init(&svr->dh_params));
        INF("Generating DH params");
        SSL_ERROR_CHECK_GOTO_ERROR(ret = gnutls_dh_params_generate2(svr->dh_params, 1024));

        SSL_ERROR_CHECK_GOTO_ERROR(ret = gnutls_anon_allocate_server_credentials(&svr->anoncred_s));
        /* TODO: implement PSK */
        //  SSL_ERROR_CHECK_GOTO_ERROR(ret = gnutls_psk_allocate_server_credentials(&svr->pskcred_s));

        gnutls_anon_set_server_dh_params(svr->anoncred_s, svr->dh_params);
        gnutls_certificate_set_dh_params(svr->cert, svr->dh_params);
        //gnutls_psk_set_server_dh_params(svr->pskcred_s, svr->dh_params);
        INF("DH params successfully generated and applied!");
     }
   else if (!svr->use_cert)
     {
        //SSL_ERROR_CHECK_GOTO_ERROR(ret = gnutls_psk_allocate_client_credentials(&svr->pskcred_c));
          SSL_ERROR_CHECK_GOTO_ERROR(ret = gnutls_anon_allocate_client_credentials(&svr->anoncred_c));
     }

   return ECORE_CON_SSL_ERROR_NONE;

error:
   _gnutls_print_errors(ret);
   _ecore_con_ssl_server_shutdown_gnutls(svr);
   return ECORE_CON_SSL_ERROR_SERVER_INIT_FAILED;
}
Пример #15
0
static gpointer
server_thread (gpointer user_data)
{
	int listener = GPOINTER_TO_INT (user_data), client;
	gnutls_certificate_credentials creds;
	gnutls_session_t session;
	struct sockaddr_in sin;
	int len;
	char buf[BUFSIZE];
	int status;

	gnutls_certificate_allocate_credentials (&creds);
	if (gnutls_certificate_set_x509_key_file (creds,
						  ssl_cert_file, ssl_key_file,
						  GNUTLS_X509_FMT_PEM) != 0) {
		g_error ("Failed to set SSL certificate and key files "
			 "(%s, %s).", ssl_cert_file, ssl_key_file);
	}
	gnutls_certificate_set_dh_params (creds, dh_params);

	/* Create a new session */
	gnutls_init (&session, GNUTLS_SERVER);
	gnutls_set_default_priority (session);
	gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, creds);
	gnutls_dh_set_prime_bits (session, DH_BITS);

	/* Wait for client thread to connect */
	len = sizeof (sin);
	client = accept (listener, (struct sockaddr *) &sin, (void *)&len);
	gnutls_transport_set_ptr (session, GINT_TO_POINTER (client));

	/* Initial handshake */
	status = gnutls_handshake (session);
	if (status < 0)
		g_error ("initial handshake failed: %d", status);

	/* Synchronous client test. */
	server_read (session, buf, BUFSIZE);
	server_write (session, buf, BUFSIZE);

	/* Async client test. */
	server_read (session, buf, BUFSIZE);
	server_write (session, buf, BUFSIZE);

	/* That's all, folks. */
	gnutls_bye (session, GNUTLS_SHUT_WR);
	gnutls_deinit (session);
	close (client);
	gnutls_certificate_free_credentials (creds);

	return NULL;
}
Пример #16
0
G_GNUC_COLD void
tls_global_init(void)
{
    static const struct {
        const char * const name;
        const int major;
        const int minor;
    } f = {
        "tls", 1, 0
    };
    char *cert_file, *key_file;

#if !defined(REMAP_ZALLOC) && !defined(TRACK_MALLOC) && !defined(TRACK_ZALLOC)
    gnutls_global_set_mem_functions(halloc, halloc, NULL, hrealloc, hfree);
#endif

    if (gnutls_global_init()) {
        g_error("gnutls_global_init() failed");
    }

#ifdef USE_TLS_CUSTOM_IO
    gnutls_global_set_log_level(9);
    gnutls_global_set_log_function(tls_log_function);
#endif	/* USE_TLS_CUSTOM_IO */

    get_dh_params();
    gnutls_certificate_allocate_credentials(&cert_cred);

    key_file = make_pathname(settings_config_dir(), "key.pem");
    cert_file = make_pathname(settings_config_dir(), "cert.pem");

    if (file_exists(key_file) && file_exists(cert_file)) {
        int ret;

        ret = gnutls_certificate_set_x509_key_file(cert_cred,
                cert_file, key_file, GNUTLS_X509_FMT_PEM);
        if (ret < 0) {
            g_warning("gnutls_certificate_set_x509_key_file() failed: %s",
                      gnutls_strerror(ret));
        } else {
            gnutls_certificate_set_dh_params(cert_cred, get_dh_params());
        }
    }
    HFREE_NULL(key_file);
    HFREE_NULL(cert_file);

    header_features_add(FEATURES_CONNECTIONS, f.name, f.major, f.minor);
    header_features_add(FEATURES_G2_CONNECTIONS, f.name, f.major, f.minor);
    header_features_add(FEATURES_DOWNLOADS, f.name, f.major, f.minor);
    header_features_add(FEATURES_UPLOADS, f.name, f.major, f.minor);
}
Пример #17
0
void Gobby::CertificateManager::make_credentials()
{
	InfCertificateCredentials* creds = inf_certificate_credentials_new();
	gnutls_certificate_credentials_t gnutls_creds =
		inf_certificate_credentials_get(creds);

	if(m_preferences.security.authentication_enabled &&
	   m_key != NULL && m_certificates != NULL)
	{
		gnutls_certificate_set_x509_key(
			gnutls_creds,
			inf_certificate_chain_get_raw(m_certificates),
			inf_certificate_chain_get_n_certificates(m_certificates),
			m_key
		);
	}

	if(m_preferences.security.use_system_trust)
	{
		const int n_cas = gnutls_certificate_set_x509_system_trust(
			gnutls_creds);
		if(n_cas < 0)
		{
			g_warning("Failed to add system CAs: %s\n",
				gnutls_strerror(n_cas));
		}
	}

	if(!m_trust.empty())
	{
		gnutls_certificate_set_x509_trust(
			gnutls_creds,
			&m_trust[0],
			m_trust.size()
		);
	}

	if(m_dh_params != NULL)
		gnutls_certificate_set_dh_params(gnutls_creds, m_dh_params);

	gnutls_certificate_set_verify_flags(
		gnutls_creds, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);

	InfCertificateCredentials* old_creds = m_credentials;
	m_credentials = creds;

	m_signal_credentials_changed.emit();

	if(old_creds != NULL)
		inf_certificate_credentials_unref(old_creds);
}
Пример #18
0
void initialize_tls_global(void)
{
	gnutls_global_init ();

	gnutls_certificate_allocate_credentials (&x509_cred);
	gnutls_certificate_set_x509_trust_file (x509_cred, CACERT,
						GNUTLS_X509_FMT_PEM);
	gnutls_certificate_set_x509_crl_file (x509_cred, CACRL,
						GNUTLS_X509_FMT_PEM);
	gnutls_certificate_set_x509_key_file (x509_cred, SERVERCERT, SERVERKEY,
						GNUTLS_X509_FMT_PEM);
	gnutls_dh_params_init (&dh_params);
	gnutls_dh_params_generate2 (dh_params, DH_BITS);

	gnutls_certificate_set_dh_params (x509_cred, dh_params);
}
Пример #19
0
void TLSServer::init (
  const std::string& ca,
  const std::string& crl,
  const std::string& cert,
  const std::string& key)
{
  _ca   = ca;
  _crl  = crl;
  _cert = cert;
  _key  = key;

  gnutls_global_init ();
  gnutls_certificate_allocate_credentials (&_credentials);
  if (_ca != "" &&
      gnutls_certificate_set_x509_trust_file (_credentials, _ca.c_str (), GNUTLS_X509_FMT_PEM) < 0)
    throw std::string ("Missing CA file.");

  if ( _crl != "" &&
      gnutls_certificate_set_x509_crl_file (_credentials, _crl.c_str (), GNUTLS_X509_FMT_PEM) < 0)
    throw std::string ("Missing CRL file.");

  if (_cert != "" &&
      _key != "" &&
      gnutls_certificate_set_x509_key_file (_credentials, _cert.c_str (), _key.c_str (), GNUTLS_X509_FMT_PEM) < 0)
    throw std::string ("Missing CERT file.");

#if GNUTLS_VERSION_NUMBER >= 0x020b00
#if GNUTLS_VERSION_NUMBER >= 0x03000d
  unsigned int bits = gnutls_sec_param_to_pk_bits (GNUTLS_PK_DH, GNUTLS_SEC_PARAM_LEGACY);
#else
  unsigned int bits = gnutls_sec_param_to_pk_bits (GNUTLS_PK_DH, GNUTLS_SEC_PARAM_NORMAL);
#endif
#else
  unsigned int bits = DH_BITS;
#endif
  gnutls_dh_params_init (&_params);
  gnutls_dh_params_generate2 (_params, bits);

  if (_ciphers == "")
    _ciphers = "NORMAL";
  gnutls_priority_init (&_priorities, _ciphers.c_str (), NULL);
  gnutls_certificate_set_dh_params (_credentials, _params);

#if GNUTLS_VERSION_NUMBER >= 0x02090a
  gnutls_certificate_set_verify_function (_credentials, verify_certificate_callback);
#endif
}
Пример #20
0
void ssl_init(struct sockifo* ifo, const char* key, const char* cert, const char* ca, int server) {
	int rv;
	rv = gnutls_certificate_allocate_credentials(&ifo->xcred);
	if (rv < 0) goto out_err;
	if (cert && *cert) {
		rv = gnutls_certificate_set_x509_key_file(ifo->xcred, cert, key, GNUTLS_X509_FMT_PEM);
		if (rv < 0) goto out_err_cred;
	}
	if (ca && *ca) {
		if (!access(ca, R_OK)) {
			ifo->state.ssl_verify_type = VERIFY_CA;
			rv = gnutls_certificate_set_x509_trust_file(ifo->xcred, ca, GNUTLS_X509_FMT_PEM);
			if (rv < 0) goto out_err_cred;
		} else {
			ifo->state.ssl_verify_type = VERIFY_FP;
			ifo->fingerprint = strdup(ca);
		}
	}
	gnutls_certificate_set_dh_params(ifo->xcred, dh_params);
	rv = gnutls_init(&ifo->ssl, server ? GNUTLS_SERVER : GNUTLS_CLIENT);
	if (rv < 0) goto out_err_cred;
	rv = gnutls_set_default_priority(ifo->ssl);
	if (rv < 0) goto out_err_all;
	rv = gnutls_credentials_set(ifo->ssl, GNUTLS_CRD_CERTIFICATE, ifo->xcred);
	if (rv < 0) goto out_err_all;

	if (server) {
		gnutls_dh_set_prime_bits(ifo->ssl, 1024);
		gnutls_certificate_server_set_request(ifo->ssl, GNUTLS_CERT_REQUEST);
	}

	gnutls_transport_set_ptr(ifo->ssl, (gnutls_transport_ptr_t)(long) ifo->fd);

	ifo->state.ssl = SSL_HSHK;
	if (!ifo->state.connpend)
		ssl_handshake(ifo);
	return;

out_err_all:
	gnutls_deinit(ifo->ssl);
out_err_cred:
	gnutls_certificate_free_credentials(ifo->xcred);
	if (ifo->fingerprint)
		free(ifo->fingerprint);
out_err:
	esock(ifo, gnutls_strerror(rv));
}
Пример #21
0
/// Enables TLS on the given server.
static void onion_enable_tls(onion *o){
#ifdef HAVE_PTHREADS
	gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
#endif
	if (!(o->flags&O_USE_DEV_RANDOM)){
		gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
	}
	gnutls_global_init ();
  gnutls_certificate_allocate_credentials (&o->x509_cred);

	gnutls_dh_params_init (&o->dh_params);
  gnutls_dh_params_generate2 (o->dh_params, 1024);
  gnutls_certificate_set_dh_params (o->x509_cred, o->dh_params);
  gnutls_priority_init (&o->priority_cache, "NORMAL", NULL);
	
	o->flags|=O_SSL_ENABLED;
}
Пример #22
0
         gtlsGlobalServerData::gtlsGlobalServerData(std::string const& _CAfile,
                                                    /*std::string const& _CRLFile,*/
                                                    std::string const& _CertFile,
                                                    std::string const& _keyFile)
            : cert_cred(0),
              initialized_(true)
         {
            int ret = 0;

            // Logging.
            gnutls_global_set_log_level(loglevel);
            gnutls_global_set_log_function(gtlsGeneric::logCallback);

            // Allocate the structures used to keep certificates in.
            ret = gnutls_certificate_allocate_credentials(&cert_cred);
            // printerror("gnutls_certificate_allocate_credentials", ret);
            if (ret < 0) { initialized_ = false; }

            // Set the CA certificate.
            // GNUTLS_NOTICE("Setting CA, file='" << _CAfile << "'");
            ret = gnutls_certificate_set_x509_trust_file(cert_cred,
                                                         _CAfile.c_str(),
                                                         GNUTLS_X509_FMT_PEM);
            // printerror("gnutls_certificate_set_x509_trust_file", ret);
            if (ret < 0) { initialized_ = false; }
            // GNUTLS_NOTICE("Processed " << ret << " certificates.");

            // Set the certificate and priate key pair.
            //GNUTLS_NOTICE("Setting certificate, file='" << _CertFile << "'");
            //GNUTLS_NOTICE("Setting private key, file='" << _keyFile << "'");
            ret = gnutls_certificate_set_x509_key_file(cert_cred,
                                                       _CertFile.c_str(),
                                                       _keyFile.c_str(),
                                                       GNUTLS_X509_FMT_PEM);
            // printerror("gnutls_certificate_set_x509_key_file", ret);
            if (ret < 0) { initialized_ = false; }
            // GNUTLS_NOTICE("Processed " << ret << " certificate/key pair(s).");

            // Generate and set DH params.
            generate_dh_params();
            gnutls_certificate_set_dh_params(cert_cred, dh_params);
         }
Пример #23
0
static sni_cert_data* creds_from_gstring(mod_context *ctx, GString *str) {
	sni_cert_data* data = NULL;
	gnutls_certificate_credentials_t creds = NULL;
	liGnuTLSOCSP* ocsp = NULL;
	gnutls_datum_t pemfile;
	int r;

	if (NULL == str) return NULL;

	if (GNUTLS_E_SUCCESS > (r = gnutls_certificate_allocate_credentials(&creds))) return NULL;

	pemfile.data = (unsigned char*) str->str;
	pemfile.size = str->len;

#if defined(HAVE_PIN)
	gnutls_certificate_set_pin_function(creds, pin_callback, ctx->pin);
#endif

	if (GNUTLS_E_SUCCESS > (r = gnutls_certificate_set_x509_key_mem(creds, &pemfile, &pemfile, GNUTLS_X509_FMT_PEM))) {
		goto error;
	}

	gnutls_certificate_set_dh_params(creds, ctx->dh_params);

	ocsp = li_gnutls_ocsp_new();
	if (!li_gnutls_ocsp_search_datum(ctx->srv, ocsp, &pemfile)) {
		goto error;
	}
	li_gnutls_ocsp_use(ocsp, creds);

	data = g_slice_new0(sni_cert_data);
	data->creds = creds;
	data->ocsp = ocsp;

	return data;

error:
	if (NULL != creds) gnutls_certificate_free_credentials(creds);
	if (NULL != ocsp) li_gnutls_ocsp_free(ocsp);
	return NULL;
}
Пример #24
0
bool SslContext::post_config()
{
	TRACE("SslContext.postConfig()");

	if (error_) return false;
	if (!enabled) return false;

//	if (rsaParams_)
//		gnutls_certificate_set_rsa_export_params(certs_, rsaParams_);

	if (dhParams_) {
		TRACE("setting DH params");
		gnutls_certificate_set_dh_params(certs_, dhParams_);
		gnutls_anon_set_server_dh_params(anonCreds_, dhParams_);
	}

	gnutls_certificate_server_set_retrieve_function(certs_, &SslContext::onRetrieveCert);

	// SRP...

	return true;
}
Пример #25
0
void SSLi_init()
{
	unsigned const bitCount = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_MEDIUM);

	gnutls_priority_init(&cipherCache, ciphers, NULL);
	initializeCertificate();

	gnutls_dh_params_init(&dhParameters);

	Log_info("Generating Diffie-Hellman parameters (%i bits)", bitCount);
	int error = gnutls_dh_params_generate2(dhParameters, bitCount);

	if(!error) {
		Log_info("Successfully generated Diffie-Hellman parameters");
	} else {
		Log_warn("Failed to generate Diffie-Hellman parameters: %s", gnutls_strerror(error));
	}

	gnutls_certificate_set_dh_params(certificate, dhParameters);

	Log_info("Sucessfully initialized GNUTLS version %s", gnutls_check_version(NULL));

}
Пример #26
0
void
server (void)
{
  /* this must be called once in the program
   */
  gnutls_global_init ();

  gnutls_global_set_log_function (tls_log_func);
  if (debug)
    gnutls_global_set_log_level (4711);

  gnutls_certificate_allocate_credentials (&x509_cred);
  gnutls_certificate_set_x509_trust_mem (x509_cred, &ca, GNUTLS_X509_FMT_PEM);

  gnutls_certificate_set_x509_key_mem (x509_cred, &server_cert, &server_key,
				       GNUTLS_X509_FMT_PEM);

  success ("Launched, generating DH parameters...\n");

  generate_dh_params ();

  gnutls_certificate_set_dh_params (x509_cred, dh_params);

  client_len = sizeof (sa_cli);

  session = initialize_tls_session ();

  sd = accept (listen_sd, (SA *) & sa_cli, &client_len);

  success ("server: connection from %s, port %d\n",
	   inet_ntop (AF_INET, &sa_cli.sin_addr, topbuf,
		      sizeof (topbuf)), ntohs (sa_cli.sin_port));

  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd);
  ret = gnutls_handshake (session);
  if (ret < 0)
    {
      close (sd);
      gnutls_deinit (session);
      fail ("server: Handshake has failed (%s)\n\n", gnutls_strerror (ret));
      return;
    }
  success ("server: Handshake was completed\n");

  success ("server: TLS version is: %s\n",
	   gnutls_protocol_get_name (gnutls_protocol_get_version (session)));

  /* see the Getting peer's information example */
  print_info (session);

  i = 0;
  for (;;)
    {
      bzero (buffer, MAX_BUF + 1);
      ret = gnutls_record_recv (session, buffer, MAX_BUF);

      if (ret == 0)
	{
	  success ("server: Peer has closed the GNUTLS connection\n");
	  break;
	}
      else if (ret < 0)
	{
	  fail ("server: Received corrupted data(%d). Closing...\n", ret);
	  break;
	}
      else if (ret > 0)
	{
	  /* echo data back to the client
	   */
	  gnutls_record_send (session, buffer, strlen (buffer));
	}
    }
  /* do not wait for the peer to close the connection.
   */
  gnutls_bye (session, GNUTLS_SHUT_WR);

  close (sd);
  gnutls_deinit (session);

  close (listen_sd);

  gnutls_certificate_free_credentials (x509_cred);

  gnutls_dh_params_deinit (dh_params);

  gnutls_global_deinit ();

  success ("server: finished\n");
}
Пример #27
0
static void server(int sd)
{
gnutls_certificate_credentials_t x509_cred;
int ret;
gnutls_session_t session;
char buffer[MAX_BUF + 1];
	/* this must be called once in the program
	 */
	global_init();

	gnutls_global_set_log_function(tls_log_func);
	if (debug)
		gnutls_global_set_log_level(4711);

	gnutls_certificate_allocate_credentials(&x509_cred);
	ret = gnutls_certificate_set_x509_trust_mem(x509_cred, &ca3_cert,
					      GNUTLS_X509_FMT_PEM);
	if (ret == 0) {
		fail("server: no CAs loaded\n");
	}

	gnutls_certificate_set_x509_key_mem(x509_cred,
					    &server_ca3_localhost_cert,
					    &server_ca3_key,
					    GNUTLS_X509_FMT_PEM);

	if (debug)
		success("Launched, generating DH parameters...\n");

	generate_dh_params();

	gnutls_certificate_set_dh_params(x509_cred, dh_params);

	gnutls_init(&session, GNUTLS_SERVER);

	/* avoid calling all the priority functions, since the defaults
	 * are adequate.
	 */
	gnutls_priority_set_direct(session, "NORMAL", NULL);

	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, x509_cred);

	/* request client certificate if any.
	 */
	gnutls_certificate_server_set_request(session,
					      GNUTLS_CERT_REQUEST);

	gnutls_dh_set_prime_bits(session, DH_BITS);

	gnutls_transport_set_int(session, sd);
	gnutls_handshake_set_timeout(session, 20 * 1000);

	ret = gnutls_handshake(session);
	if (ret < 0) {
		close(sd);
		gnutls_deinit(session);
		fail("server: Handshake has failed (%s)\n\n",
		     gnutls_strerror(ret));
		return;
	}
	if (debug)
		success("server: Handshake was completed\n");

	if (debug)
		success("server: TLS version is: %s\n",
			gnutls_protocol_get_name
			(gnutls_protocol_get_version(session)));

	/* see the Getting peer's information example */
	if (debug)
		print_info(session);

	for (;;) {
		memset(buffer, 0, MAX_BUF + 1);
		ret = gnutls_record_recv(session, buffer, MAX_BUF);

		if (ret == 0) {
			if (debug)
				success
				    ("server: Peer has closed the GnuTLS connection\n");
			break;
		} else if (ret < 0) {
			fail("server: Received corrupted data(%d). Closing...\n", ret);
			break;
		} else if (ret > 0) {
			/* echo data back to the client
			 */
			gnutls_record_send(session, buffer,
					   strlen(buffer));
		}
	}
	/* do not wait for the peer to close the connection.
	 */
	gnutls_bye(session, GNUTLS_SHUT_WR);

	close(sd);
	gnutls_deinit(session);

	gnutls_certificate_free_credentials(x509_cred);

	gnutls_dh_params_deinit(dh_params);

	gnutls_global_deinit();

	if (debug)
		success("server: finished\n");
}
Пример #28
0
static void server(int sd)
{
	/* this must be called once in the program
	 */
	global_init();

	gnutls_global_set_log_function(tls_log_func);
	if (debug)
		gnutls_global_set_log_level(6);

	gnutls_certificate_allocate_credentials(&x509_cred);
	gnutls_certificate_set_x509_trust_mem(x509_cred, &ca,
					      GNUTLS_X509_FMT_PEM);

	gnutls_certificate_set_x509_key_mem(x509_cred, &server_cert,
					    &server_key,
					    GNUTLS_X509_FMT_PEM);

	if (debug)
		success("Launched, generating DH parameters...\n");

	generate_dh_params();

	gnutls_certificate_set_dh_params(x509_cred, dh_params);

	session = initialize_tls_session();

	gnutls_transport_set_int(session, sd);
	ret = gnutls_handshake(session);
	if (ret < 0) {
		close(sd);
		gnutls_deinit(session);
		fail("server: Handshake has failed (%s)\n\n",
		     gnutls_strerror(ret));
		return;
	}
	if (debug) {
		success("server: Handshake was completed\n");
		success("server: TLS version is: %s\n",
			gnutls_protocol_get_name
			(gnutls_protocol_get_version(session)));
	}

	/* see the Getting peer's information example */
	if (debug)
		print_info(session);

	for (;;) {
		memset(buffer, 0, MAX_BUF + 1);
		ret = gnutls_record_recv(session, buffer, MAX_BUF);

		if (ret == 0) {
			if (debug)
				success
				    ("server: Peer has closed the GnuTLS connection\n");
			break;
		} else if (ret < 0) {
			fail("server: Received corrupted data(%d). Closing...\n", ret);
			break;
		} else if (ret > 0) {
			gnutls_certificate_server_set_request(session,
							      GNUTLS_CERT_REQUEST);

			if (debug)
				success
				    ("server: got data, forcing rehandshake.\n");

			ret = gnutls_rehandshake(session);
			if (ret < 0) {
				fail("server: rehandshake failed\n");
				gnutls_perror(ret);
				break;
			}

			ret = gnutls_handshake(session);
			if (ret < 0) {
				fail("server: (re)handshake failed\n");
				gnutls_perror(ret);
				break;
			}

			if (debug)
				success("server: rehandshake complete.\n");

			/* echo data back to the client
			 */
			gnutls_record_send(session, buffer,
					   strlen(buffer));
		}
	}
	/* do not wait for the peer to close the connection.
	 */
	gnutls_bye(session, GNUTLS_SHUT_WR);

	close(sd);
	gnutls_deinit(session);

	gnutls_certificate_free_credentials(x509_cred);

	gnutls_dh_params_deinit(dh_params);

	gnutls_global_deinit();

	if (debug)
		success("server: finished\n");
}
Пример #29
0
int
main (void)
{
  int err, listen_sd;
  int sd, ret;
  struct sockaddr_in sa_serv;
  struct sockaddr_in sa_cli;
  int client_len;
  char topbuf[512];
  gnutls_session_t session;
  char buffer[MAX_BUF + 1];
  int optval = 1;
  char name[256];

  strcpy (name, "Echo Server");

  /* this must be called once in the program
   */
  gnutls_global_init ();

  gnutls_certificate_allocate_credentials (&cred);
  gnutls_certificate_set_openpgp_keyring_file (cred, RINGFILE,
					       GNUTLS_OPENPGP_FMT_BASE64);

  gnutls_certificate_set_openpgp_key_file (cred, CERTFILE, KEYFILE,
					   GNUTLS_OPENPGP_FMT_BASE64);

  generate_dh_params ();

  gnutls_certificate_set_dh_params (cred, dh_params);

  /* Socket operations
   */
  listen_sd = socket (AF_INET, SOCK_STREAM, 0);
  SOCKET_ERR (listen_sd, "socket");

  memset (&sa_serv, '\0', sizeof (sa_serv));
  sa_serv.sin_family = AF_INET;
  sa_serv.sin_addr.s_addr = INADDR_ANY;
  sa_serv.sin_port = htons (PORT);	/* Server Port number */

  setsockopt (listen_sd, SOL_SOCKET, SO_REUSEADDR, (void *) &optval,
	      sizeof (int));

  err = bind (listen_sd, (SA *) & sa_serv, sizeof (sa_serv));
  SOCKET_ERR (err, "bind");
  err = listen (listen_sd, 1024);
  SOCKET_ERR (err, "listen");

  printf ("%s ready. Listening to port '%d'.\n\n", name, PORT);

  client_len = sizeof (sa_cli);
  for (;;)
    {
      session = initialize_tls_session ();

      sd = accept (listen_sd, (SA *) & sa_cli, &client_len);

      printf ("- connection from %s, port %d\n",
	      inet_ntop (AF_INET, &sa_cli.sin_addr, topbuf,
			 sizeof (topbuf)), ntohs (sa_cli.sin_port));

      gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd);
      ret = gnutls_handshake (session);
      if (ret < 0)
	{
	  close (sd);
	  gnutls_deinit (session);
	  fprintf (stderr, "*** Handshake has failed (%s)\n\n",
		   gnutls_strerror (ret));
	  continue;
	}
      printf ("- Handshake was completed\n");

      /* see the Getting peer's information example */
      /* print_info(session); */

      for (;;)
	{
	  memset (buffer, 0, MAX_BUF + 1);
	  ret = gnutls_record_recv (session, buffer, MAX_BUF);

	  if (ret == 0)
	    {
	      printf ("\n- Peer has closed the GnuTLS connection\n");
	      break;
	    }
	  else if (ret < 0)
	    {
	      fprintf (stderr, "\n*** Received corrupted "
		       "data(%d). Closing the connection.\n\n", ret);
	      break;
	    }
	  else if (ret > 0)
	    {
	      /* echo data back to the client
	       */
	      gnutls_record_send (session, buffer, strlen (buffer));
	    }
	}
      printf ("\n");
      /* do not wait for the peer to close the connection.
       */
      gnutls_bye (session, GNUTLS_SHUT_WR);

      close (sd);
      gnutls_deinit (session);

    }
  close (listen_sd);

  gnutls_certificate_free_credentials (cred);

  gnutls_global_deinit ();

  return 0;

}
Пример #30
0
int
main (void)
{
    int listen_sd;
    int sock, ret;
    struct sockaddr_in sa_serv;
    struct sockaddr_in cli_addr;
    socklen_t cli_addr_size;
    gnutls_session_t session;
    char buffer[MAX_BUFFER];
    priv_data_st priv;
    gnutls_datum_t cookie_key;
    gnutls_dtls_prestate_st prestate;
    int mtu = 1400;
    unsigned char sequence[8];

    /* this must be called once in the program
     */
    gnutls_global_init ();

    gnutls_certificate_allocate_credentials (&x509_cred);
    gnutls_certificate_set_x509_trust_file (x509_cred, CAFILE,
                                            GNUTLS_X509_FMT_PEM);

    gnutls_certificate_set_x509_crl_file (x509_cred, CRLFILE,
                                          GNUTLS_X509_FMT_PEM);

    ret = gnutls_certificate_set_x509_key_file (x509_cred, CERTFILE, KEYFILE,
            GNUTLS_X509_FMT_PEM);
    if (ret < 0)
    {
        printf("No certificate or key were found\n");
        exit(1);
    }

    generate_dh_params ();

    gnutls_certificate_set_dh_params (x509_cred, dh_params);

    gnutls_priority_init (&priority_cache,
                          "PERFORMANCE:-VERS-TLS-ALL:+VERS-DTLS1.0:%SERVER_PRECEDENCE",
                          NULL);

    gnutls_key_generate (&cookie_key, GNUTLS_COOKIE_KEY_SIZE);

    /* Socket operations
     */
    listen_sd = socket (AF_INET, SOCK_DGRAM, 0);

    memset (&sa_serv, '\0', sizeof (sa_serv));
    sa_serv.sin_family = AF_INET;
    sa_serv.sin_addr.s_addr = INADDR_ANY;
    sa_serv.sin_port = htons (PORT);

    {   /* DTLS requires the IP don't fragment (DF) bit to be set */
#if defined(IP_DONTFRAG)
        int optval = 1;
        setsockopt (listen_sd, IPPROTO_IP, IP_DONTFRAG,
                    (const void *) &optval, sizeof (optval));
#elif defined(IP_MTU_DISCOVER)
        int optval = IP_PMTUDISC_DO;
        setsockopt(listen_sd, IPPROTO_IP, IP_MTU_DISCOVER,
                   (const void*) &optval, sizeof (optval));
#endif
    }

    bind (listen_sd, (struct sockaddr *) &sa_serv, sizeof (sa_serv));

    printf ("UDP server ready. Listening to port '%d'.\n\n", PORT);

    for (;;)
    {
        printf ("Waiting for connection...\n");
        sock = wait_for_connection (listen_sd);
        if (sock < 0)
            continue;

        cli_addr_size = sizeof (cli_addr);
        ret = recvfrom (sock, buffer, sizeof (buffer), MSG_PEEK,
                        (struct sockaddr *) &cli_addr, &cli_addr_size);
        if (ret > 0)
        {
            memset (&prestate, 0, sizeof (prestate));
            ret = gnutls_dtls_cookie_verify (&cookie_key, &cli_addr,
                                             sizeof (cli_addr), buffer, ret,
                                             &prestate);
            if (ret < 0)          /* cookie not valid */
            {
                priv_data_st s;

                memset (&s, 0, sizeof (s));
                s.fd = sock;
                s.cli_addr = (void *) &cli_addr;
                s.cli_addr_size = sizeof (cli_addr);

                printf ("Sending hello verify request to %s\n",
                        human_addr ((struct sockaddr *) &cli_addr,
                                    sizeof (cli_addr), buffer,
                                    sizeof (buffer)));

                gnutls_dtls_cookie_send (&cookie_key, &cli_addr,
                                         sizeof (cli_addr), &prestate,
                                         (gnutls_transport_ptr_t) & s,
                                         push_func);

                /* discard peeked data */
                recvfrom (sock, buffer, sizeof (buffer), 0,
                          (struct sockaddr *) &cli_addr, &cli_addr_size);
                usleep (100);
                continue;
            }
            printf ("Accepted connection from %s\n",
                    human_addr ((struct sockaddr *)
                                &cli_addr, sizeof (cli_addr), buffer,
                                sizeof (buffer)));
        }
        else
            continue;

        session = initialize_tls_session ();
        gnutls_dtls_prestate_set (session, &prestate);
        gnutls_dtls_set_mtu (session, mtu);

        priv.session = session;
        priv.fd = sock;
        priv.cli_addr = (struct sockaddr *) &cli_addr;
        priv.cli_addr_size = sizeof (cli_addr);

        gnutls_transport_set_ptr (session, &priv);
        gnutls_transport_set_push_function (session, push_func);
        gnutls_transport_set_pull_function (session, pull_func);
        gnutls_transport_set_pull_timeout_function (session, pull_timeout_func);

        do
        {
            ret = gnutls_handshake (session);
        }
        while (ret < 0 && gnutls_error_is_fatal (ret) == 0);

        if (ret < 0)
        {
            fprintf (stderr, "Error in handshake(): %s\n",
                     gnutls_strerror (ret));
            gnutls_deinit (session);
            continue;
        }

        printf ("- Handshake was completed\n");

        for (;;)
        {
            do
            {
                ret = gnutls_record_recv_seq (session, buffer, MAX_BUFFER,
                                              sequence);
            }
            while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);

            if (ret < 0)
            {
                fprintf (stderr, "Error in recv(): %s\n",
                         gnutls_strerror (ret));
                break;
            }
            if (ret == 0)
            {
                printf ("EOF\n\n");
                break;
            }
            buffer[ret] = 0;
            printf ("received[%.2x%.2x%.2x%.2x%.2x%.2x%.2x%.2x]: %s\n",
                    sequence[0], sequence[1], sequence[2], sequence[3],
                    sequence[4], sequence[5], sequence[6], sequence[7], buffer);

            /* reply back */
            ret = gnutls_record_send (session, buffer, ret);
            if (ret < 0)
            {
                fprintf (stderr, "Error in send(): %s\n",
                         gnutls_strerror (ret));
                break;
            }
        }

        gnutls_bye (session, GNUTLS_SHUT_WR);
        gnutls_deinit (session);

    }
    close (listen_sd);

    gnutls_certificate_free_credentials (x509_cred);
    gnutls_priority_deinit (priority_cache);

    gnutls_global_deinit ();

    return 0;

}