Пример #1
0
void global_erase_plug(int id){
	if(id >= 0 && id < GLOBAL_DEVICE_DEFAULT){
		global_init();
		hashmap_erase(self.plugs, id);
	}
}
Пример #2
0
void global_erase_device(int id){
	if(id >= 0 && id < GLOBAL_DEVICE_DEFAULT){
		global_init();
		hashmap_erase(self.devices, id);
	}
}
Пример #3
0
void * global_get_plug(int id){
	if(id < 0) return NULL;
	global_init();
	return hashmap_search(self.plugs, id);
}
Пример #4
0
void doit(void)
{
	int ret;
	const char *lib;
	gnutls_privkey_t key;
	gnutls_datum_t sig = {NULL, 0}, data;
	pid_t pid;

	data.data = (void*)"\x38\x17\x0c\x08\xcb\x45\x8f\xd4\x87\x9c\x34\xb6\xf6\x08\x29\x4c\x50\x31\x2b\xbb";
	data.size = 20;

	ret = global_init();
	if (ret != 0) {
		fail("%d: %s\n", ret, gnutls_strerror(ret));
		exit(1);
	}

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

	lib = getenv("P11MOCKLIB1");
	if (lib == NULL)
		lib = P11LIB;

	ret = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
	if (ret != 0) {
		fail("%d: %s\n", ret, gnutls_strerror(ret));
		exit(1);
	}

	ret = gnutls_pkcs11_add_provider(lib, NULL);
	if (ret != 0) {
		fail("%d: %s\n", ret, gnutls_strerror(ret));
		exit(1);
	}

	ret = gnutls_privkey_init(&key);
	assert(ret>=0);

	gnutls_privkey_set_pin_function(key, pin_func, NULL);

	ret = gnutls_privkey_import_url(key, "pkcs11:object=test", GNUTLS_PKCS11_OBJ_FLAG_LOGIN);
	if (ret < 0) {
		fail("%d: %s\n", ret, gnutls_strerror(ret));
		exit(1);
	}

	ret = gnutls_privkey_sign_hash(key, GNUTLS_DIG_SHA1, 0, &data, &sig);
	if (ret < 0) {
		fail("%d: %s\n", ret, gnutls_strerror(ret));
		exit(1);
	}

	gnutls_free(sig.data);

	pid = fork();
	if (pid != 0) {
		int status;
		assert(waitpid(pid, &status, 0) >= 0);

		if (WEXITSTATUS(status) != 0) {
			fail("child return status was unexpected: %d\n", WEXITSTATUS(status));
			exit(1);
		}
	} else { /* child */

		ret = gnutls_pkcs11_reinit();
		assert(ret == 0);

		ret = gnutls_privkey_sign_hash(key, GNUTLS_DIG_SHA1, 0, &data, &sig);
		if (ret < 0) {
			fail("%d: %s\n", ret, gnutls_strerror(ret));
			exit(1);
		}

		gnutls_free(sig.data);		
		gnutls_privkey_deinit(key);
		gnutls_pkcs11_deinit();
		gnutls_global_deinit();
		exit(0);
	}

	if (debug)
		printf("done\n\n\n");

	gnutls_privkey_deinit(key);
	gnutls_pkcs11_deinit();
	gnutls_global_deinit();
}
Пример #5
0
void * global_get_device(int id){
	if(id < 0) return NULL;
	global_init();
	return hashmap_search(self.devices, id);
}
Пример #6
0
int test(char *URL)
{
  int res = 0;
  CURL *curl = NULL;
  int running;
  CURLM *m = NULL;
  int current=0;

  start_test_timing();

  global_init(CURL_GLOBAL_ALL);

  easy_init(curl);

  easy_setopt(curl, CURLOPT_URL, URL);
  easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  easy_setopt(curl, CURLOPT_FAILONERROR, 1L);

  multi_init(m);

  multi_add_handle(m, curl);

  fprintf(stderr, "Start at URL 0\n");

  for(;;) {
    struct timeval interval;
    fd_set rd, wr, exc;
    int maxfd = -99;

    interval.tv_sec = 1;
    interval.tv_usec = 0;

    multi_perform(m, &running);

    abort_on_test_timeout();

    if(!running) {
      if(!current++) {
        fprintf(stderr, "Advancing to URL 1\n");
        /* remove the handle we use */
        curl_multi_remove_handle(m, curl);

        /* make us re-use the same handle all the time, and try resetting
           the handle first too */
        curl_easy_reset(curl);
        easy_setopt(curl, CURLOPT_URL, libtest_arg2);
        easy_setopt(curl, CURLOPT_VERBOSE, 1L);
        easy_setopt(curl, CURLOPT_FAILONERROR, 1L);

        /* re-add it */
        multi_add_handle(m, curl);
      }
      else
        break; /* done */
    }

    FD_ZERO(&rd);
    FD_ZERO(&wr);
    FD_ZERO(&exc);

    multi_fdset(m, &rd, &wr, &exc, &maxfd);

    /* At this point, maxfd is guaranteed to be greater or equal than -1. */

    select_test(maxfd+1, &rd, &wr, &exc, &interval);

    abort_on_test_timeout();
  }

test_cleanup:

  /* undocumented cleanup sequence - type UB */

  curl_easy_cleanup(curl);
  curl_multi_cleanup(m);
  curl_global_cleanup();

  return res;
}
Пример #7
0
static void client(int fd, const char *prio, unsigned overhead)
{
	int ret;
	gnutls_anon_client_credentials_t anoncred;
	gnutls_certificate_credentials_t x509_cred;
	gnutls_session_t session;
	/* Need to enable anonymous KX specifically. */

	global_init();

	if (debug) {
		gnutls_global_set_log_function(client_log_func);
		gnutls_global_set_log_level(7);
	}

	gnutls_anon_allocate_client_credentials(&anoncred);
	gnutls_certificate_allocate_credentials(&x509_cred);

	/* Initialize TLS session
	 */
	gnutls_init(&session, GNUTLS_CLIENT | GNUTLS_DATAGRAM);

	/* Use default priorities */
	ret = gnutls_priority_set_direct(session, prio, NULL);
	if (ret < 0) {
		fail("error in setting priority: %s\n", prio);
		exit(1);
	}

	/* put the anonymous credentials to the current session
	 */
	gnutls_credentials_set(session, GNUTLS_CRD_ANON, anoncred);
	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, x509_cred);

	gnutls_transport_set_int(session, fd);

	/* Perform the TLS handshake
	 */
	do {
		ret = gnutls_handshake(session);
	}
	while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

	if (ret < 0) {
		fail("client: Handshake failed for %s\n", prio);
		gnutls_perror(ret);
		exit(1);
	} else {
		if (debug)
			success("client: Handshake was completed\n");
	}

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

	gnutls_dtls_set_mtu(session, MTU);
	ret = gnutls_dtls_get_data_mtu(session);

	if (MTU - ret != (int) overhead) {
		fail("overhead for %s is %d, expected %u\n", prio,
		     MTU - ret, overhead);
		exit(1);
	}

	close(fd);

	gnutls_deinit(session);

	gnutls_anon_free_client_credentials(anoncred);
	gnutls_certificate_free_credentials(x509_cred);

	gnutls_global_deinit();
}
Пример #8
0
 void init() {
     global_init();
 }
Пример #9
0
void doit(void)
{
	/* Server stuff. */
	gnutls_certificate_credentials_t serverx509cred;
	gnutls_session_t server;
	int sret = GNUTLS_E_AGAIN;
	/* Client stuff. */
	gnutls_certificate_credentials_t clientx509cred;
	gnutls_session_t client;
	int cret = GNUTLS_E_AGAIN;

	/* General init. */
	global_init();
	gnutls_global_set_log_function(tls_log_func);
	if (debug)
		gnutls_global_set_log_level(2);

	/* Init server */
	gnutls_certificate_allocate_credentials(&serverx509cred);
	gnutls_certificate_set_x509_key_mem(serverx509cred,
					    &server_cert, &server_key,
					    GNUTLS_X509_FMT_PEM);
	gnutls_init(&server, GNUTLS_SERVER);
	gnutls_credentials_set(server, GNUTLS_CRD_CERTIFICATE,
				serverx509cred);
	gnutls_priority_set_direct(server, "NORMAL", NULL);
	gnutls_transport_set_push_function(server, server_push);
	gnutls_transport_set_pull_function(server, server_pull);
	gnutls_transport_set_ptr(server, server);
	gnutls_certificate_set_verify_function(serverx509cred,
						server_callback);
	gnutls_certificate_server_set_request(server, GNUTLS_CERT_REQUEST);
	gnutls_handshake_set_post_client_hello_function(server,
							post_client_hello_callback);
	gnutls_handshake_set_hook_function(server, GNUTLS_HANDSHAKE_ANY,
					   GNUTLS_HOOK_POST,
					   handshake_callback);
	append_alpn(server);

	/* Init client */
	gnutls_certificate_allocate_credentials(&clientx509cred);
	gnutls_init(&client, GNUTLS_CLIENT);
	gnutls_credentials_set(client, GNUTLS_CRD_CERTIFICATE,
				clientx509cred);
	gnutls_priority_set_direct(client, "NORMAL", NULL);
	gnutls_transport_set_push_function(client, client_push);
	gnutls_transport_set_pull_function(client, client_pull);
	gnutls_transport_set_ptr(client, client);
	gnutls_certificate_set_verify_function(clientx509cred,
						client_callback);
	append_alpn(client);

	HANDSHAKE(client, server);

	gnutls_bye(client, GNUTLS_SHUT_RDWR);
	gnutls_bye(server, GNUTLS_SHUT_RDWR);

	gnutls_deinit(client);
	gnutls_deinit(server);

	gnutls_certificate_free_credentials(serverx509cred);
	gnutls_certificate_free_credentials(clientx509cred);

	gnutls_global_deinit();

	if (pch_ok == 0)
		fail("Post client hello callback wasn't called\n");

	if (server_ok == 0)
		fail("Server certificate verify callback wasn't called\n");

	if (client_ok == 0)
		fail("Client certificate verify callback wasn't called\n");
}
Пример #10
0
int test(char *URL)
{
  int res = 0;
  CURL *curl[NUM_HANDLES];
  int running;
  CURLM *m = NULL;
  int current = 0;
  int i;

  for(i=0; i < NUM_HANDLES; i++)
    curl[i] = NULL;

  start_test_timing();

  global_init(CURL_GLOBAL_ALL);

  /* get NUM_HANDLES easy handles */
  for(i=0; i < NUM_HANDLES; i++) {
    easy_init(curl[i]);
    /* specify target */
    easy_setopt(curl[i], CURLOPT_URL, URL);
    /* go verbose */
    easy_setopt(curl[i], CURLOPT_VERBOSE, 1L);
  }

  multi_init(m);

  multi_add_handle(m, curl[current]);

  fprintf(stderr, "Start at URL 0\n");

  for(;;) {
    struct timeval interval;
    fd_set rd, wr, exc;
    int maxfd = -99;

    interval.tv_sec = 1;
    interval.tv_usec = 0;

    multi_perform(m, &running);

    abort_on_test_timeout();

    if(!running) {
#ifdef LIB527
      /* NOTE: this code does not remove the handle from the multi handle
         here, which would be the nice, sane and documented way of working.
         This however tests that the API survives this abuse gracefully. */
      curl_easy_cleanup(curl[current]);
      curl[current] = NULL;
#endif
      if(++current < NUM_HANDLES) {
        fprintf(stderr, "Advancing to URL %d\n", current);
#ifdef LIB532
        /* first remove the only handle we use */
        curl_multi_remove_handle(m, curl[0]);

        /* make us re-use the same handle all the time, and try resetting
           the handle first too */
        curl_easy_reset(curl[0]);
        easy_setopt(curl[0], CURLOPT_URL, URL);
        /* go verbose */
        easy_setopt(curl[0], CURLOPT_VERBOSE, 1L);

        /* re-add it */
        multi_add_handle(m, curl[0]);
#else
        multi_add_handle(m, curl[current]);
#endif
      }
      else {
        break; /* done */
      }
    }

    FD_ZERO(&rd);
    FD_ZERO(&wr);
    FD_ZERO(&exc);

    multi_fdset(m, &rd, &wr, &exc, &maxfd);

    /* At this point, maxfd is guaranteed to be greater or equal than -1. */

    select_test(maxfd+1, &rd, &wr, &exc, &interval);

    abort_on_test_timeout();
  }

test_cleanup:

#if defined(LIB526)

  /* test 526 and 528 */
  /* proper cleanup sequence - type PB */

  for(i=0; i < NUM_HANDLES; i++) {
    curl_multi_remove_handle(m, curl[i]);
    curl_easy_cleanup(curl[i]);
  }
  curl_multi_cleanup(m);
  curl_global_cleanup();

#elif defined(LIB527)

  /* test 527 */

  /* Upon non-failure test flow the easy's have already been cleanup'ed. In
     case there is a failure we arrive here with easy's that have not been
     cleanup'ed yet, in this case we have to cleanup them or otherwise these
     will be leaked, let's use undocumented cleanup sequence - type UB */

  if(res)
    for(i=0; i < NUM_HANDLES; i++)
      curl_easy_cleanup(curl[i]);

  curl_multi_cleanup(m);
  curl_global_cleanup();

#elif defined(LIB532)

  /* test 532 */
  /* undocumented cleanup sequence - type UB */

  for(i=0; i < NUM_HANDLES; i++)
    curl_easy_cleanup(curl[i]);
  curl_multi_cleanup(m);
  curl_global_cleanup();

#endif

  return res;
}
Пример #11
0
void doit(void)
{
	int ret;
	gnutls_datum_t pem_cert = { (unsigned char *) pem, sizeof(pem) };
	gnutls_x509_crt_t cert;
	gnutls_datum_t strdn;
	gnutls_x509_dn_t xdn;

	ret = global_init();
	if (ret < 0)
		fail("init %d\n", ret);

	ret = gnutls_x509_crt_init(&cert);
	if (ret < 0)
		fail("crt_init %d\n", ret);

	ret = gnutls_x509_crt_import(cert, &pem_cert, GNUTLS_X509_FMT_PEM);
	if (ret < 0)
		fail("crt_import %d\n", ret);

	ret = gnutls_x509_crt_get_issuer(cert, &xdn);
	if (ret < 0)
		fail("get_issuer %d\n", ret);

	if (debug) {
		printf("Issuer:\n");
		print_dn(xdn);
	}

	ret = gnutls_x509_crt_get_subject(cert, &xdn);
	if (ret < 0)
		fail("get_subject %d\n", ret);

	/* test the original function behavior */
	ret = gnutls_x509_dn_get_str(xdn, &strdn);
	if (ret < 0)
		fail("gnutls_x509_dn_get_str %d\n", ret);

	if (strdn.size != 44 || strcmp((char*)strdn.data, "CN=CAcert WoT User,[email protected]") != 0) {
		fail("gnutls_x509_dn_get_str string comparison failed: '%s'/%d\n", strdn.data, strdn.size);
	}
	gnutls_free(strdn.data);

	/* test the new function behavior */
	ret = gnutls_x509_dn_get_str2(xdn, &strdn, 0);
	if (ret < 0)
		fail("gnutls_x509_dn_get_str2 %d\n", ret);
	if (strdn.size != 44 || strcmp((char*)strdn.data, "[email protected],CN=CAcert WoT User") != 0) {
		fail("gnutls_x509_dn_get_str2 string comparison failed: '%s'/%d\n", strdn.data, strdn.size);
	}
	gnutls_free(strdn.data);

	/* test the new/compat function behavior */
	ret = gnutls_x509_dn_get_str2(xdn, &strdn, GNUTLS_X509_DN_FLAG_COMPAT);
	if (ret < 0)
		fail("gnutls_x509_dn_get_str2 %d\n", ret);
	if (strdn.size != 44 || strcmp((char*)strdn.data, "CN=CAcert WoT User,[email protected]") != 0) {
		fail("gnutls_x509_dn_get_str2 string comparison failed: '%s'/%d\n", strdn.data, strdn.size);
	}
	gnutls_free(strdn.data);

	if (debug) {
		printf("Subject:\n");
		print_dn(xdn);
	}

	if (debug)
		success("done\n");

	gnutls_x509_crt_deinit(cert);
	gnutls_global_deinit();
}
Пример #12
0
static
int check_x509_privkey(void)
{
	gnutls_x509_privkey_t key;
	gnutls_datum_t p, q, g, y, x;
	gnutls_datum_t m, e, u, e1, e2, d;
	gnutls_ecc_curve_t curve;
	int ret;

	global_init();

	ret = gnutls_x509_privkey_init(&key);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_x509_privkey_import(key, &dsa_key, GNUTLS_X509_FMT_PEM);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_x509_privkey_export_dsa_raw(key, &p, &q, &g, &y, &x);
	if (ret < 0)
		fail("error\n");

	CMP("p", &p, dsa_p);
	CMP("q", &q, dsa_q);
	CMP("g", &g, dsa_g);
	CMP("y", &y, dsa_y);
	CMP("x", &x, dsa_x);
	gnutls_free(p.data);
	gnutls_free(q.data);
	gnutls_free(g.data);
	gnutls_free(y.data);
	gnutls_free(x.data);
	gnutls_x509_privkey_deinit(key);

	/* RSA */
	ret = gnutls_x509_privkey_init(&key);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_x509_privkey_import(key, &rsa_key, GNUTLS_X509_FMT_PEM);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_x509_privkey_export_rsa_raw2(key, &m, &e, &d, &p, &q, &u, &e1, &e2);
	if (ret < 0)
		fail("error\n");

	CMP("m", &m, rsa_m);
	CMP("e", &e, rsa_e);
	CMP("d", &d, rsa_d);
	CMP("p", &p, rsa_p);
	CMP("q", &q, rsa_q);
	CMP("u", &u, rsa_u);
	CMP("e1", &e1, rsa_e1);
	CMP("e2", &e2, rsa_e2);
	gnutls_free(m.data);
	gnutls_free(e.data);
	gnutls_free(d.data);
	gnutls_free(p.data);
	gnutls_free(q.data);
	gnutls_free(u.data);
	gnutls_free(e1.data);
	gnutls_free(e2.data);
	gnutls_x509_privkey_deinit(key);

	/* ECC */
	ret = gnutls_x509_privkey_init(&key);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_x509_privkey_import(key, &server_ecc_key, GNUTLS_X509_FMT_PEM);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_x509_privkey_export_ecc_raw(key, &curve, &x, &y, &p);
	if (ret < 0)
		fail("error\n");

	if (curve != GNUTLS_ECC_CURVE_SECP256R1) {
		fprintf(stderr, "unexpected curve value: %d\n", (int)curve);
		exit(1);
	}
	CMP("x", &x, ecc_x);
	CMP("y", &y, ecc_y);
	CMP("k", &p, ecc_k);
	gnutls_free(x.data);
	gnutls_free(y.data);
	gnutls_free(p.data);
	gnutls_x509_privkey_deinit(key);

	return 0;
}
Пример #13
0
static
int check_privkey_import_export(void)
{
	gnutls_privkey_t key;
	gnutls_datum_t p, q, g, y, x;
	gnutls_datum_t m, e, u, e1, e2, d;
	gnutls_ecc_curve_t curve;
	gnutls_digest_algorithm_t digest;
	gnutls_gost_paramset_t paramset;
	int ret;

	global_init();

	ret = gnutls_privkey_init(&key);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_privkey_import_dsa_raw(key, &_dsa_p, &_dsa_q, &_dsa_g, &_dsa_y, &_dsa_x);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_privkey_export_dsa_raw2(key, &p, &q, &g, &y, &x, 0);
	if (ret < 0)
		fail("error: %s\n", gnutls_strerror(ret));

	CMP("p", &p, dsa_p);
	CMP("q", &q, dsa_q);
	CMP("g", &g, dsa_g);
	CMP("y", &y, dsa_y);
	CMP("x", &x, dsa_x);
	gnutls_free(p.data);
	gnutls_free(q.data);
	gnutls_free(g.data);
	gnutls_free(y.data);
	gnutls_free(x.data);

	ret = gnutls_privkey_export_dsa_raw2(key, &p, &q, &g, &y, &x, GNUTLS_EXPORT_FLAG_NO_LZ);
	if (ret < 0)
		fail("error: %s\n", gnutls_strerror(ret));

	CMP_NO_LZ("p", &p, dsa_p);
	CMP_NO_LZ("q", &q, dsa_q);
	CMP_NO_LZ("g", &g, dsa_g);
	CMP_NO_LZ("y", &y, dsa_y);
	CMP_NO_LZ("x", &x, dsa_x);
	gnutls_free(p.data);
	gnutls_free(q.data);
	gnutls_free(g.data);
	gnutls_free(y.data);
	gnutls_free(x.data);
	gnutls_privkey_deinit(key);

	/* RSA */
	ret = gnutls_privkey_init(&key);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_privkey_import_rsa_raw(key, &_rsa_m, &_rsa_e, &_rsa_d, &_rsa_p, &_rsa_q, &_rsa_u, &_rsa_e1, &_rsa_e2);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_privkey_export_rsa_raw2(key, &m, &e, &d, &p, &q, &u, &e1, &e2, 0);
	if (ret < 0)
		fail("error\n");

	CMP("m", &m, rsa_m);
	CMP("e", &e, rsa_e);
	CMP("d", &d, rsa_d);
	CMP("p", &p, rsa_p);
	CMP("q", &q, rsa_q);
	CMP("u", &u, rsa_u);
	CMP("e1", &e1, rsa_e1);
	CMP("e2", &e2, rsa_e2);
	gnutls_free(m.data);
	gnutls_free(e.data);
	gnutls_free(d.data);
	gnutls_free(p.data);
	gnutls_free(q.data);
	gnutls_free(u.data);
	gnutls_free(e1.data);
	gnutls_free(e2.data);

	ret = gnutls_privkey_export_rsa_raw2(key, &m, &e, &d, &p, &q, &u, &e1, &e2, GNUTLS_EXPORT_FLAG_NO_LZ);
	if (ret < 0)
		fail("error\n");

	CMP_NO_LZ("m", &m, rsa_m);
	CMP_NO_LZ("e", &e, rsa_e);
	CMP_NO_LZ("d", &d, rsa_d);
	CMP_NO_LZ("p", &p, rsa_p);
	CMP_NO_LZ("q", &q, rsa_q);
	CMP_NO_LZ("u", &u, rsa_u);
	CMP_NO_LZ("e1", &e1, rsa_e1);
	CMP_NO_LZ("e2", &e2, rsa_e2);
	gnutls_free(m.data);
	gnutls_free(e.data);
	gnutls_free(d.data);
	gnutls_free(p.data);
	gnutls_free(q.data);
	gnutls_free(u.data);
	gnutls_free(e1.data);
	gnutls_free(e2.data);
	gnutls_privkey_deinit(key);

	/* ECC */
	ret = gnutls_privkey_init(&key);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_privkey_import_ecc_raw(key, GNUTLS_ECC_CURVE_SECP256R1, &_ecc_x, &_ecc_y, &_ecc_k);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_privkey_export_ecc_raw2(key, &curve, &x, &y, &p, 0);
	if (ret < 0)
		fail("error\n");

	if (curve != GNUTLS_ECC_CURVE_SECP256R1) {
		fprintf(stderr, "unexpected curve value: %d\n", (int)curve);
		exit(1);
	}
	CMP("x", &x, ecc_x);
	CMP("y", &y, ecc_y);
	CMP("k", &p, ecc_k);
	gnutls_free(x.data);
	gnutls_free(y.data);
	gnutls_free(p.data);

	ret = gnutls_privkey_export_ecc_raw2(key, &curve, &x, &y, &p, GNUTLS_EXPORT_FLAG_NO_LZ);
	if (ret < 0)
		fail("error\n");

	if (curve != GNUTLS_ECC_CURVE_SECP256R1) {
		fprintf(stderr, "unexpected curve value: %d\n", (int)curve);
		exit(1);
	}
	CMP_NO_LZ("x", &x, ecc_x);
	CMP_NO_LZ("y", &y, ecc_y);
	CMP_NO_LZ("k", &p, ecc_k);
	gnutls_free(x.data);
	gnutls_free(y.data);
	gnutls_free(p.data);
	gnutls_privkey_deinit(key);

	/* Ed25519 */
	ret = gnutls_privkey_init(&key);
	if (ret < 0)
		fail("error\n");

	/* test whether an invalid size would fail */
	ret = gnutls_privkey_import_ecc_raw(key, GNUTLS_ECC_CURVE_ED25519, &_rsa_m, NULL, &_rsa_m);
	if (ret != GNUTLS_E_INVALID_REQUEST)
		fail("error\n");

	ret = gnutls_privkey_import_ecc_raw(key, GNUTLS_ECC_CURVE_ED25519, &_ed25519_x, NULL, &_ed25519_k);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_privkey_verify_params(key);
	if (ret != 0)
		fail("error: %s\n", gnutls_strerror(ret));

	ret = gnutls_privkey_export_ecc_raw(key, &curve, &x, NULL, &p);
	if (ret < 0)
		fail("error\n");

	if (curve != GNUTLS_ECC_CURVE_ED25519) {
		fail("unexpected curve value: %d\n", (int)curve);
	}
	CMP("x", &x, ed25519_x);
	CMP("k", &p, ed25519_k);
	gnutls_free(x.data);
	gnutls_free(p.data);
	gnutls_privkey_deinit(key);

	/* Ed25519 with incorrect public key */
	ret = gnutls_privkey_init(&key);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_privkey_import_ecc_raw(key, GNUTLS_ECC_CURVE_ED25519, &_false_ed25519_x, NULL, &_ed25519_k);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_privkey_verify_params(key);
	if (ret != GNUTLS_E_ILLEGAL_PARAMETER)
		fail("error: %s\n", gnutls_strerror(ret));

	gnutls_privkey_deinit(key);

	/* GOST */
	ret = gnutls_privkey_init(&key);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_privkey_import_gost_raw(key, GNUTLS_ECC_CURVE_GOST256CPXA, GNUTLS_DIG_GOSTR_94, GNUTLS_GOST_PARAMSET_CP_A, &_gost_x, &_gost_y, &_gost_k);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_privkey_export_gost_raw2(key, &curve, &digest, &paramset, &x, &y, &p, 0);
	if (ret < 0)
		fail("error\n");

	if (curve != GNUTLS_ECC_CURVE_GOST256CPXA) {
		fprintf(stderr, "unexpected curve value: %d\n", (int)curve);
		exit(1);
	}
	if (digest != GNUTLS_DIG_GOSTR_94) {
		fprintf(stderr, "unexpected digest value: %d\n", (int)digest);
		exit(1);
	}
	if (paramset != GNUTLS_GOST_PARAMSET_CP_A) {
		fprintf(stderr, "unexpected paramset value: %d\n", (int)paramset);
		exit(1);
	}
	CMP("x", &x, gost_x);
	CMP("y", &y, gost_y);
	CMP("k", &p, gost_k);
	gnutls_free(x.data);
	gnutls_free(y.data);
	gnutls_free(p.data);

	ret = gnutls_privkey_export_gost_raw2(key, &curve, &digest, &paramset, &x, &y, &p, GNUTLS_EXPORT_FLAG_NO_LZ);
	if (ret < 0)
		fail("error\n");

	if (curve != GNUTLS_ECC_CURVE_GOST256CPXA) {
		fprintf(stderr, "unexpected curve value: %d\n", (int)curve);
		exit(1);
	}
	if (digest != GNUTLS_DIG_GOSTR_94) {
		fprintf(stderr, "unexpected digest value: %d\n", (int)digest);
		exit(1);
	}
	if (paramset != GNUTLS_GOST_PARAMSET_CP_A) {
		fprintf(stderr, "unexpected paramset value: %d\n", (int)paramset);
		exit(1);
	}
	CMP_NO_LZ("x", &x, gost_x);
	CMP_NO_LZ("y", &y, gost_y);
	CMP_NO_LZ("k", &p, gost_k);
	gnutls_free(x.data);
	gnutls_free(y.data);
	gnutls_free(p.data);
	gnutls_privkey_deinit(key);

	return 0;
}
Пример #14
0
static void server(int sds[])
{
    int j;
    /* 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(5);

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

    generate_dh_params();

    for (j = 0; j < SESSIONS; j++) {
        int sd = sds[j];

        if (j == 0) {
            gnutls_certificate_allocate_credentials(&pgp_cred);
            ret =
                gnutls_certificate_set_openpgp_key_mem2
                (pgp_cred, &server_crt, &server_key, "auto",
                 GNUTLS_OPENPGP_FMT_BASE64);
        } else {
            gnutls_certificate_free_credentials(pgp_cred);
            gnutls_certificate_allocate_credentials(&pgp_cred);
            ret =
                gnutls_certificate_set_openpgp_key_mem2
                (pgp_cred, &cert2048, &key2048, "auto",
                 GNUTLS_OPENPGP_FMT_BASE64);
        }

        if (ret < 0) {
            fail("Could not set server key files...\n");
            goto end;
        }

        gnutls_certificate_set_dh_params(pgp_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 %d has failed (%s)\n\n",
                 j, gnutls_strerror(ret));
            goto end;
        }
        if (debug)
            success("server: Handshake %d was completed\n", j);

        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);
                goto end;
            } 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);
    }

end:
    gnutls_certificate_free_credentials(pgp_cred);

    gnutls_dh_params_deinit(dh_params);

    gnutls_global_deinit();

    if (debug)
        success("server: finished\n");
}
int test(char *URL)
{
  CURL *handle = NULL;
  CURLM *mhandle = NULL;
  int res = 0;
  int still_running = 0;

  start_test_timing();

  global_init(CURL_GLOBAL_ALL);

  easy_init(handle);

  easy_setopt(handle, CURLOPT_URL, URL);
  easy_setopt(handle, CURLOPT_VERBOSE, 1L);

  multi_init(mhandle);

  multi_add_handle(mhandle, handle);

  multi_perform(mhandle, &still_running);

  abort_on_test_timeout();

  while(still_running) {
    struct timeval timeout;
    fd_set fdread;
    fd_set fdwrite;
    fd_set fdexcep;
    int maxfd = -99;
    struct timeval before;
    struct timeval after;
    long e;

    timeout.tv_sec = 0;
    timeout.tv_usec = 100000L; /* 100 ms */

    FD_ZERO(&fdread);
    FD_ZERO(&fdwrite);
    FD_ZERO(&fdexcep);

    multi_fdset(mhandle, &fdread, &fdwrite, &fdexcep, &maxfd);

    /* At this point, maxfd is guaranteed to be greater or equal than -1. */

    select_test(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);

    abort_on_test_timeout();

    fprintf(stderr, "ping\n");
    before = tutil_tvnow();

    multi_perform(mhandle, &still_running);

    abort_on_test_timeout();

    after = tutil_tvnow();
    e = tutil_tvdiff(after, before);
    fprintf(stderr, "pong = %ld\n", e);

    if(e > MAX_BLOCKED_TIME_MS) {
      res = 100;
      break;
    }
  }

test_cleanup:

  /* undocumented cleanup sequence - type UA */

  curl_multi_cleanup(mhandle);
  curl_easy_cleanup(handle);
  curl_global_cleanup();

  return res;
}
Пример #16
0
static void
server (int fd, const char* prio)
{
int ret;
char buffer[MAX_BUF + 1];
gnutls_session_t session;
gnutls_certificate_credentials_t x509_cred;
const char* err;
struct timespec start, stop;
static unsigned long measurement;

  setpriority(PRIO_PROCESS, getpid(), -15);

  /* this must be called once in the program
   */
  global_init ();
  memset(buffer, 0, sizeof(buffer));

#ifdef DEBUG
  gnutls_global_set_log_function (server_log_func);
  gnutls_global_set_log_level (6);
#endif

  gnutls_certificate_allocate_credentials (&x509_cred);
  ret = gnutls_certificate_set_x509_key_mem (x509_cred, &server_cert, &server_key,
                                       GNUTLS_X509_FMT_PEM);
  if (ret < 0)
    {
      fprintf(stderr, "Could not set certificate\n");
      return;
    }

#ifdef REHANDSHAKE
restart:
#endif
  gnutls_init (&session, GNUTLS_SERVER);

  /* avoid calling all the priority functions, since the defaults
   * are adequate.
   */
  if ((ret=gnutls_priority_set_direct (session, prio, &err)) < 0) {
    fprintf(stderr, "Error in priority string %s: %s\n", gnutls_strerror(ret), err);
    return;
  }

  gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, x509_cred);
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) fd);

  do 
    {
      ret = gnutls_handshake (session);
    }
  while (ret < 0 && gnutls_error_is_fatal(ret) == 0);
  if (ret < 0)
    {
#ifdef GNUTLS_E_PREMATURE_TERMINATION
      if (ret != GNUTLS_E_PREMATURE_TERMINATION && ret != GNUTLS_E_UNEXPECTED_PACKET_LENGTH)
#else
      if (ret != GNUTLS_E_UNEXPECTED_PACKET_LENGTH)
#endif
        {
          fprintf( stderr, "server: Handshake has failed (%s)\n\n", gnutls_strerror (ret));
        }
      goto finish;
    }

#ifndef REHANDSHAKE
restart:
#endif

  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
 
  do {
    ret = gnutls_record_recv (session, buffer, sizeof (buffer));
  } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);

  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &stop);

  if (ret == GNUTLS_E_DECRYPTION_FAILED)
    {
      gnutls_session_force_valid(session);
      measurement = timespec_sub_ns(&stop, &start);
      do {
        ret = gnutls_record_send(session, &measurement, sizeof(measurement));
        /* GNUTLS_AL_FATAL, GNUTLS_A_BAD_RECORD_MAC); */
      } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);

#ifdef REHANDSHAKE
      gnutls_deinit(session);
#endif
      if (ret >= 0)
        goto restart;
    }
  else if (ret < 0)
    fprintf(stderr, "err: %s\n", gnutls_strerror(ret));
  

  /* do not wait for the peer to close the connection.
   */
  gnutls_bye (session, GNUTLS_SHUT_WR);

finish:
  close (fd);
  gnutls_deinit (session);

  gnutls_certificate_free_credentials (x509_cred);

  gnutls_global_deinit ();
}
Пример #17
0
static void client(int sds[])
{
    int ret, ii, j;
    gnutls_session_t session;
    char buffer[MAX_BUF + 1];
    gnutls_certificate_credentials_t xcred;

    global_init();

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

    gnutls_certificate_allocate_credentials(&xcred);

    /* sets the trusted cas file
     */
    if (debug)
        success("Setting key files...\n");

    ret = gnutls_certificate_set_openpgp_key_mem(xcred, &cert, &key,
            GNUTLS_OPENPGP_FMT_BASE64);
    if (ret < 0) {
        fail("Could not set key files...\n");
        return;
    }

    for (j = 0; j < SESSIONS; j++) {
        int sd = sds[j];

        /* Initialize TLS session
         */
        gnutls_init(&session, GNUTLS_CLIENT);

        /* Use default priorities */
        gnutls_priority_set_direct(session,
                                   "NORMAL:+CTYPE-OPENPGP", NULL);

        /* put the x509 credentials to the current session
         */
        gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
                               xcred);

        gnutls_transport_set_int(session, sd);

        /* Perform the TLS handshake
         */
        ret = gnutls_handshake(session);

        if (ret < 0) {
            fail("client: Handshake %d failed\n", j);
            gnutls_perror(ret);
            goto end;
        } else if (debug) {
            success("client: Handshake %d was completed\n", j);
        }

        if (debug)
            success("client: 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);

        gnutls_record_send(session, MSG, strlen(MSG));

        ret = gnutls_record_recv(session, buffer, MAX_BUF);
        if (ret == 0) {
            if (debug)
                success
                ("client: Peer has closed the TLS connection\n");
            goto end;
        } else if (ret < 0) {
            fail("client: Error: %s\n", gnutls_strerror(ret));
            goto end;
        }

        if (debug) {
            printf("- Received %d bytes: ", ret);
            for (ii = 0; ii < ret; ii++) {
                fputc(buffer[ii], stdout);
            }
            fputs("\n", stdout);
        }

        gnutls_bye(session, GNUTLS_SHUT_RDWR);

        close(sd);

        gnutls_deinit(session);

    }

end:

    gnutls_certificate_free_credentials(xcred);

    gnutls_global_deinit();
}
Пример #18
0
int test(char *URL)
{
  CURL *c = NULL;
  CURLM *m = NULL;
  int res = 0;
  int running;

  start_test_timing();

  global_init(CURL_GLOBAL_ALL);

  easy_init(c);

  easy_setopt(c, CURLOPT_PROXY, libtest_arg2); /* set in first.c */
  easy_setopt(c, CURLOPT_URL, URL);
  easy_setopt(c, CURLOPT_USERPWD, "test:ing");
  easy_setopt(c, CURLOPT_PROXYUSERPWD, "test:ing");
  easy_setopt(c, CURLOPT_HTTPPROXYTUNNEL, 1L);
  easy_setopt(c, CURLOPT_HEADER, 1L);
  easy_setopt(c, CURLOPT_VERBOSE, 1L);

  multi_init(m);

  multi_add_handle(m, c);

  for(;;) {
    struct timeval interval;
    fd_set rd, wr, exc;
    int maxfd = -99;

    interval.tv_sec = 1;
    interval.tv_usec = 0;

    multi_perform(m, &running);

    abort_on_test_timeout();

    if(!running)
      break; /* done */

    FD_ZERO(&rd);
    FD_ZERO(&wr);
    FD_ZERO(&exc);

    multi_fdset(m, &rd, &wr, &exc, &maxfd);

    /* At this point, maxfd is guaranteed to be greater or equal than -1. */

    select_test(maxfd + 1, &rd, &wr, &exc, &interval);

    abort_on_test_timeout();
  }

test_cleanup:

  /* proper cleanup sequence - type PA */

  curl_multi_remove_handle(m, c);
  curl_multi_cleanup(m);
  curl_easy_cleanup(c);
  curl_global_cleanup();

  return res;
}
Пример #19
0
void doit(void)
{
	char buf[128];
	int exit_val = 0;
	int ret;
	unsigned j;
	const char *lib, *bin;
	gnutls_x509_crt_t issuer = NULL;
	gnutls_x509_trust_list_t tl;
	gnutls_x509_crt_t certs[MAX_CHAIN];
	gnutls_x509_crt_t end, ca;
	unsigned verify_status = 0;
	gnutls_datum_t tmp;

	/* The overloading of time() seems to work in linux (ELF?)
	 * systems only. Disable it on windows.
	 */
#ifdef _WIN32
	exit(77);
#endif
	bin = softhsm_bin();

	lib = softhsm_lib();

	ret = global_init();
	if (ret != 0) {
		fail("%d: %s\n", ret, gnutls_strerror(ret));
		exit(1);
	}

	gnutls_pkcs11_set_pin_function(pin_func, NULL);
	gnutls_global_set_time_function(mytime);
	gnutls_global_set_log_function(tls_log_func);
	if (debug)
		gnutls_global_set_log_level(4711);

	set_softhsm_conf(CONFIG);
	snprintf(buf, sizeof(buf), "%s --init-token --slot 0 --label test --so-pin "PIN" --pin "PIN, bin);
	system(buf);

	ret = gnutls_pkcs11_add_provider(lib, "trusted");
	if (ret < 0) {
		fprintf(stderr, "gnutls_x509_crt_init: %s\n",
			gnutls_strerror(ret));
		exit(1);
	}

	for (j = 0; ca_list[j]; j++) {
		if (debug > 2)
			printf("\tAdding certificate %d...",
			       (int) j);

		ret = gnutls_x509_crt_init(&certs[j]);
		if (ret < 0) {
			fprintf(stderr,
				"gnutls_x509_crt_init[%d,%d]: %s\n",
				(int) 3, (int) j,
				gnutls_strerror(ret));
			exit(1);
		}

		tmp.data = (unsigned char *) ca_list[j];
		tmp.size = strlen(ca_list[j]);

		ret =
		    gnutls_x509_crt_import(certs[j], &tmp,
					   GNUTLS_X509_FMT_PEM);
		if (debug > 2)
			printf("done\n");
		if (ret < 0) {
			fprintf(stderr,
				"gnutls_x509_crt_import[%d]: %s\n",
				(int) j,
				gnutls_strerror(ret));
			exit(1);
		}

		gnutls_x509_crt_print(certs[j],
				      GNUTLS_CRT_PRINT_ONELINE,
				      &tmp);
		if (debug)
			printf("\tCertificate %d: %.*s\n", (int) j,
			       tmp.size, tmp.data);
		gnutls_free(tmp.data);
	}

	if (debug > 2)
		printf("\tAdding end certificate...");

	ret = gnutls_x509_crt_init(&end);
	if (ret < 0) {
		fprintf(stderr, "gnutls_x509_crt_init: %s\n",
			gnutls_strerror(ret));
		exit(1);
	}

	tmp.data = (unsigned char *) v1_root_check[0];
	tmp.size = strlen(v1_root_check[0]);

	ret =
	    gnutls_x509_crt_import(end, &tmp, GNUTLS_X509_FMT_PEM);
	if (ret < 0) {
		fprintf(stderr, "gnutls_x509_crt_import: %s\n",
			gnutls_strerror(ret));
		exit(1);
	}

	gnutls_x509_crt_print(end, GNUTLS_CRT_PRINT_ONELINE, &tmp);
	if (debug)
		printf("\tEnd Certificate: %.*s\n", tmp.size,
		       tmp.data);
	gnutls_free(tmp.data);

	ret = gnutls_x509_crt_init(&ca);
	if (ret < 0) {
		fprintf(stderr, "gnutls_x509_crt_init: %s\n",
			gnutls_strerror(ret));
		exit(1);
	}

	tmp.data = (unsigned char *) v1_root_check[1];
	tmp.size = strlen(v1_root_check[1]);

	ret =
	    gnutls_x509_crt_import(ca, &tmp, GNUTLS_X509_FMT_PEM);
	if (ret < 0) {
		fprintf(stderr, "gnutls_x509_crt_import: %s\n",
			gnutls_strerror(ret));
		exit(1);
	}

	gnutls_x509_crt_print(end, GNUTLS_CRT_PRINT_ONELINE, &tmp);
	if (debug)
		printf("\tCA Certificate: %.*s\n", tmp.size,
		       tmp.data);
	gnutls_free(tmp.data);

	if (debug > 2)
		printf("done\n");


	if (debug)
		printf("\tChecking presence and verification...");

	/* initialize softhsm token */
	ret = gnutls_pkcs11_token_init(SOFTHSM_URL, PIN, "test");
	if (ret < 0) {
		fail("gnutls_pkcs11_token_init\n");
		exit(1);
	}

	/* write CA certificate to softhsm */
	for (j = 0; ca_list[j]; j++) {
		char name[64];
		snprintf(name, sizeof(name), "test-ca%d", j);
		ret = gnutls_pkcs11_copy_x509_crt(SOFTHSM_URL, certs[j], name, GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED|GNUTLS_PKCS11_OBJ_FLAG_LOGIN_SO);
		if (ret < 0) {
			fail("gnutls_pkcs11_copy_x509_crt: %s\n", gnutls_strerror(ret));
			exit(1);
		}
	}

	gnutls_x509_trust_list_init(&tl, 0);

	ret = gnutls_x509_trust_list_add_trust_file(tl, SOFTHSM_URL, NULL, 0, 0, 0);
	if (ret < 0) {
		fail("gnutls_x509_trust_list_add_trust_file\n");
		exit(1);
	}

	ret = gnutls_x509_trust_list_add_cas(tl, &ca, 1, 0);
	if (ret < 0) {
		fail("gnutls_x509_trust_list_add_cas\n");
		exit(1);
	}

	/* extract the issuer of the certificate */
	ret = gnutls_x509_trust_list_get_issuer(tl, end, &issuer, GNUTLS_TL_GET_COPY);
	if (ret < 0) {
		fail("gnutls_x509_trust_list_get_issuer should have succeeded\n");
		exit(1);
	}
	gnutls_x509_crt_deinit(issuer);

	ret = gnutls_pkcs11_crt_is_known(SOFTHSM_URL, ca, GNUTLS_PKCS11_OBJ_FLAG_COMPARE_KEY|GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_TRUSTED);
	if (ret != 0) {
		fail("gnutls_pkcs11_crt_is_known should have failed!\n");
		exit(1);
	}

	ret = gnutls_x509_trust_list_verify_crt2(tl, &end, 1,
						NULL, 0,
						GNUTLS_VERIFY_DISABLE_TIME_CHECKS, &verify_status, NULL);
	if (ret < 0) {
		fail("gnutls_x509_trust_list_verify_crt2 should have succeeded\n");
		exit(1);
	}

	if (verify_status != 0) {
		fail("verification should have succeeded: %.2x\n", verify_status);
		exit(1);
	}

	if (debug)
		printf("\tCleanup...");

	gnutls_x509_trust_list_deinit(tl, 0);
	gnutls_x509_crt_deinit(ca);
	gnutls_x509_crt_deinit(end);
	for (j = 0; ca_list[j]; j++) {
		gnutls_x509_crt_deinit(certs[j]);
	}
	if (debug)
		printf("done\n\n\n");

	gnutls_global_deinit();

	if (debug)
		printf("Exit status...%d\n", exit_val);
	remove(CONFIG);

	exit(exit_val);
}
Пример #20
0
static void client(int fd, unsigned do_fork)
{
	int ret;
	gnutls_certificate_credentials_t x509_cred;
	gnutls_session_t session;
	/* Need to enable anonymous KX specifically. */

	global_init();

	if (debug) {
		side = "client";
		gnutls_global_set_log_function(tls_log_func);
		gnutls_global_set_log_level(4711);
	}

	gnutls_certificate_allocate_credentials(&x509_cred);

	/* Initialize TLS session
	 */
	gnutls_init(&session, GNUTLS_CLIENT | GNUTLS_DATAGRAM);
	gnutls_dtls_set_mtu(session, 1500);
	gnutls_dtls_set_timeouts(session, 6 * 1000, 60 * 1000);
	//gnutls_transport_set_push_function(session, push);

	/* Use default priorities */
	gnutls_priority_set_direct(session,
				   "NONE:+VERS-DTLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ECDHE-ECDSA:+CURVE-ALL",
				   NULL);

	/* put the anonymous credentials to the current session
	 */
	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, x509_cred);

	gnutls_transport_set_int(session, fd);

	/* Perform the TLS handshake
	 */
	do {
		ret = gnutls_handshake(session);
	}
	while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

	if (ret < 0) {
		fail("client: Handshake failed\n");
		gnutls_perror(ret);
		exit(1);
	} else {
		if (debug)
			success("client: Handshake was completed\n");
	}

	if (do_fork)
		do_fork_stuff(session);
	else
		do_reflect_stuff(session);

	close(fd);

	gnutls_deinit(session);

	gnutls_certificate_free_credentials(x509_cred);

	gnutls_global_deinit();
	exit(0);
}
Пример #21
0
static void server(int fd, unsigned do_fork)
{
	int ret;
	gnutls_certificate_credentials_t x509_cred;
	gnutls_session_t session;

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

#if 0
	if (debug) {
		side = "server";
		gnutls_global_set_log_function(tls_log_func);
		gnutls_global_set_log_level(4711);
	}
#endif

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

	gnutls_init(&session, GNUTLS_SERVER | GNUTLS_DATAGRAM);
	gnutls_dtls_set_timeouts(session, 5 * 1000, 60 * 1000);
	gnutls_dtls_set_mtu(session, 400);

	/* avoid calling all the priority functions, since the defaults
	 * are adequate.
	 */
	gnutls_priority_set_direct(session,
				   "NONE:+VERS-DTLS1.2:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ECDHE-ECDSA:+CURVE-ALL",
				   NULL);

	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, x509_cred);

	gnutls_transport_set_int(session, fd);

	do {
		ret = gnutls_handshake(session);
	} while (ret < 0 && gnutls_error_is_fatal(ret) == 0);
	if (ret < 0) {
		close(fd);
		gnutls_deinit(session);
		fail("server: Handshake has failed (%s)\n\n",
		     gnutls_strerror(ret));
		terminate();
	}
	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)));

	if (do_fork)
		do_fork_stuff(session);
	else
		do_reflect_stuff(session);


	close(fd);
	gnutls_deinit(session);

	gnutls_certificate_free_credentials(x509_cred);

	gnutls_global_deinit();

	if (debug)
		success("server: finished\n");
}
Пример #22
0
void doit(void)
{
	/* Server stuff. */
	gnutls_anon_server_credentials_t s_anoncred;
	const gnutls_datum_t p3 = { (void *) pkcs3, strlen(pkcs3) };
	static gnutls_dh_params_t dh_params;
	gnutls_session_t server;
	int sret, cret;
	/* Client stuff. */
	gnutls_anon_client_credentials_t c_anoncred;
	gnutls_session_t client;
	/* Need to enable anonymous KX specifically. */
	char buffer[MAX_BUF + 1];
	ssize_t ns;
	int ret, transferred = 0, msglen;

	/* General init. */
	global_init();
	gnutls_global_set_log_function(tls_log_func);
	if (debug)
		gnutls_global_set_log_level(99);

	/* Init server */
	gnutls_anon_allocate_server_credentials(&s_anoncred);
	gnutls_dh_params_init(&dh_params);
	gnutls_dh_params_import_pkcs3(dh_params, &p3, GNUTLS_X509_FMT_PEM);
	gnutls_anon_set_server_dh_params(s_anoncred, dh_params);
	gnutls_init(&server,
		    GNUTLS_SERVER | GNUTLS_DATAGRAM | GNUTLS_NONBLOCK);
	ret =
	    gnutls_priority_set_direct(server,
				       "NONE:+VERS-DTLS1.0:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-DH",
				       NULL);
	if (ret < 0)
		exit(1);
	gnutls_credentials_set(server, GNUTLS_CRD_ANON, s_anoncred);
	gnutls_transport_set_push_function(server, server_push);
	gnutls_transport_set_pull_function(server, server_pull);
	gnutls_transport_set_pull_timeout_function(server,
						   server_pull_timeout_func);
	gnutls_transport_set_ptr(server, server);

	/* Init client */
	gnutls_anon_allocate_client_credentials(&c_anoncred);
	gnutls_init(&client,
		    GNUTLS_CLIENT | GNUTLS_DATAGRAM | GNUTLS_NONBLOCK);
	cret =
	    gnutls_priority_set_direct(client,
				       "NONE:+VERS-DTLS1.0:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-DH",
				       NULL);
	if (cret < 0)
		exit(1);
	gnutls_credentials_set(client, GNUTLS_CRD_ANON, c_anoncred);
	gnutls_transport_set_push_function(client, client_push);
	gnutls_transport_set_pull_function(client, client_pull);
	gnutls_transport_set_pull_timeout_function(client,
						   client_pull_timeout_func);
	gnutls_transport_set_ptr(client, client);

	handshake = 1;
	HANDSHAKE(client, server);

	handshake = 0;
	if (debug)
		success("Handshake established\n");

	do {
		ret = gnutls_record_send(client, MSG, strlen(MSG));
	}
	while (ret == GNUTLS_E_AGAIN);
	//success ("client: sent %d\n", ns);

	msglen = strlen(MSG);
	TRANSFER(client, server, MSG, msglen, buffer, MAX_BUF);

	if (debug)
		fputs("\n", stdout);

	gnutls_bye(client, GNUTLS_SHUT_WR);
	gnutls_bye(server, GNUTLS_SHUT_WR);

	gnutls_deinit(client);
	gnutls_deinit(server);

	gnutls_anon_free_client_credentials(c_anoncred);
	gnutls_anon_free_server_credentials(s_anoncred);

	gnutls_dh_params_deinit(dh_params);

	gnutls_global_deinit();
}
Пример #23
0
void doit(void)
{
	int err, i;
	int sockets[2];
	const char *srcdir;
	pid_t child;
	char pub_key_path[512], priv_key_path[512];

	global_init();

	srcdir = getenv("srcdir") ? getenv("srcdir") : ".";

	for (i = 0; i < 5; i++) {
		if (i <= 1)
			key_id = NULL;	/* try using the master key */
		else if (i == 2)
			key_id = "auto";	/* test auto */
		else if (i >= 3)
			key_id = "f30fd423c143e7ba";

		if (debug) {
			gnutls_global_set_log_level(5);
			gnutls_global_set_log_function(log_message);
		}

		err = socketpair(AF_UNIX, SOCK_STREAM, 0, sockets);
		if (err != 0)
			fail("socketpair %s\n", strerror(errno));

		if (sizeof(pub_key_path) <
		    strlen(srcdir) + strlen(pub_key_file) + 2)
			abort();

		strcpy(pub_key_path, srcdir);
		strcat(pub_key_path, "/");
		strcat(pub_key_path, pub_key_file);

		if (sizeof(priv_key_path) <
		    strlen(srcdir) + strlen(priv_key_file) + 2)
			abort();

		strcpy(priv_key_path, srcdir);
		strcat(priv_key_path, "/");
		strcat(priv_key_path, priv_key_file);

		child = fork();
		if (child == -1)
			fail("fork %s\n", strerror(errno));

		if (child == 0) {
			/* Child process (client).  */
			gnutls_session_t session;
			gnutls_certificate_credentials_t cred;
			ssize_t sent;

			if (debug)
				printf("client process %i\n", getpid());

			err = gnutls_init(&session, GNUTLS_CLIENT);
			if (err != 0)
				fail("client session %d\n", err);

			if (i == 0)	/* we use the primary key which is RSA. Test the RSA ciphersuite */
				gnutls_priority_set_direct(session,
							   "NONE:+VERS-TLS1.0:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+RSA:+CTYPE-OPENPGP",
							   NULL);
			else
				gnutls_priority_set_direct(session,
							   "NONE:+VERS-TLS1.0:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+DHE-DSS:+DHE-RSA:+CTYPE-OPENPGP",
							   NULL);
			gnutls_transport_set_int(session, sockets[0]);

			err =
			    gnutls_certificate_allocate_credentials(&cred);
			if (err != 0)
				fail("client credentials %d\n", err);

			err =
			    gnutls_certificate_set_openpgp_key_file2(cred,
								     pub_key_path,
								     priv_key_path,
								     key_id,
								     GNUTLS_OPENPGP_FMT_BASE64);
			if (err != 0)
				fail("client openpgp keys %s\n",
				     gnutls_strerror(err));

			check_loaded_key(cred);

			err =
			    gnutls_credentials_set(session,
						   GNUTLS_CRD_CERTIFICATE,
						   cred);
			if (err != 0)
				fail("client credential_set %d\n", err);

			gnutls_dh_set_prime_bits(session, 1024);

			if (i == 4)
				gnutls_openpgp_send_cert(session,
							 GNUTLS_OPENPGP_CERT_FINGERPRINT);

			err = gnutls_handshake(session);
			if (err != 0)
				fail("client handshake %s (%d) \n",
				     gnutls_strerror(err), err);
			else if (debug)
				printf("client handshake successful\n");

			sent =
			    gnutls_record_send(session, message,
						sizeof(message));
			if (sent != sizeof(message))
				fail("client sent %li vs. %li\n",
				     (long) sent, (long) sizeof(message));

			err = gnutls_bye(session, GNUTLS_SHUT_RDWR);
			if (err != 0)
				fail("client bye %d\n", err);

			if (debug)
				printf("client done\n");

			gnutls_deinit(session);
			gnutls_certificate_free_credentials(cred);
			gnutls_free(stored_cli_cert.data);
			gnutls_global_deinit();
			return;
		} else {
			/* Parent process (server).  */
			gnutls_session_t session;
			gnutls_dh_params_t dh_params;
			gnutls_certificate_credentials_t cred;
			char greetings[sizeof(message) * 2];
			ssize_t received;
			pid_t done;
			int status;
			const gnutls_datum_t p3 =
			    { (void *) pkcs3, strlen(pkcs3) };

			if (debug)
				printf("server process %i (child %i)\n",
					getpid(), child);

			err = gnutls_init(&session, GNUTLS_SERVER);
			if (err != 0)
				fail("server session %d\n", err);

			gnutls_priority_set_direct(session,
						   "NONE:+VERS-TLS1.0:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+DHE-DSS:+DHE-RSA:+RSA:+CTYPE-OPENPGP",
						   NULL);
			gnutls_transport_set_int(session, sockets[1]);

			err =
			    gnutls_certificate_allocate_credentials(&cred);
			if (err != 0)
				fail("server credentials %d\n", err);

			err =
			    gnutls_certificate_set_openpgp_key_file2(cred,
								     pub_key_path,
								     priv_key_path,
								     key_id,
								     GNUTLS_OPENPGP_FMT_BASE64);
			if (err != 0)
				fail("server openpgp keys %s\n",
				     gnutls_strerror(err));

			check_loaded_key(cred);

			err = gnutls_dh_params_init(&dh_params);
			if (err)
				fail("server DH params init %d\n", err);

			err =
			    gnutls_dh_params_import_pkcs3(dh_params, &p3,
							  GNUTLS_X509_FMT_PEM);
			if (err)
				fail("server DH params generate %d\n",
				     err);

			gnutls_certificate_set_dh_params(cred, dh_params);

			err =
			    gnutls_credentials_set(session,
						   GNUTLS_CRD_CERTIFICATE,
						   cred);
			if (err != 0)
				fail("server credential_set %d\n", err);

			gnutls_certificate_server_set_request(session,
							      GNUTLS_CERT_REQUIRE);

			if (i == 4)
				gnutls_openpgp_set_recv_key_function
				    (session, key_recv_func);

			err = gnutls_handshake(session);
			if (err != 0)
				fail("server handshake %s (%d) \n",
				     gnutls_strerror(err), err);

			if (stored_cli_cert.data == NULL) {
				const gnutls_datum_t *d;
				unsigned int d_size;
				d = gnutls_certificate_get_peers(session,
								 &d_size);
				if (d != NULL) {
					stored_cli_cert.data =
					    gnutls_malloc(d[0].size);
					memcpy(stored_cli_cert.data,
						d[0].data, d[0].size);
					stored_cli_cert.size = d[0].size;
				}
			}

			received =
			    gnutls_record_recv(session, greetings,
						sizeof(greetings));
			if (received != sizeof(message)
			    || memcmp(greetings, message, sizeof(message)))
				fail("server received %li vs. %li\n",
				     (long) received,
				     (long) sizeof(message));

			err = gnutls_bye(session, GNUTLS_SHUT_RDWR);
			if (err != 0)
				fail("server bye %s (%d) \n",
				     gnutls_strerror(err), err);

			if (debug)
				printf("server done\n");

			gnutls_deinit(session);
			gnutls_certificate_free_credentials(cred);
			gnutls_dh_params_deinit(dh_params);

			done = wait(&status);
			if (done < 0)
				fail("wait %s\n", strerror(errno));

			if (done != child)
				fail("who's that?! %d\n", done);

			check_wait_status(status);
		}
	}

	gnutls_free(stored_cli_cert.data);
	gnutls_global_deinit();
}
Пример #24
0
void doit(void)
{
	int exit_code = EXIT_SUCCESS;
	int ret;
	/* Server stuff. */
	gnutls_certificate_credentials_t serverx509cred;
	gnutls_session_t server;
	int sret = GNUTLS_E_AGAIN;
	/* Client stuff. */
	gnutls_certificate_credentials_t clientx509cred;
	gnutls_session_t client;
	int cret = GNUTLS_E_AGAIN;
	gnutls_datum_t data;
	char buf[128];

	/* General init. */
	global_init();
	gnutls_global_set_log_function(tls_log_func);
	if (debug)
		gnutls_global_set_log_level(6);

	gnutls_global_set_time_function(mytime);

	/* Init server */
	gnutls_certificate_allocate_credentials(&serverx509cred);
	gnutls_certificate_set_x509_key_mem(serverx509cred,
					    &server_cert, &server_key,
					    GNUTLS_X509_FMT_PEM);

	gnutls_init(&server, GNUTLS_SERVER);
	gnutls_credentials_set(server, GNUTLS_CRD_CERTIFICATE,
				serverx509cred);
	gnutls_set_default_priority(server);
	gnutls_transport_set_push_function(server, server_push);
	gnutls_transport_set_pull_function(server, server_pull);
	gnutls_transport_set_ptr(server, server);

	/* Init client */
	ret = gnutls_certificate_allocate_credentials(&clientx509cred);
	if (ret < 0)
		exit(1);

	ret = gnutls_certificate_set_x509_trust_mem(clientx509cred, &ca_cert, GNUTLS_X509_FMT_PEM);
	if (ret < 0)
		exit(1);

	ret = gnutls_init(&client, GNUTLS_CLIENT|GNUTLS_ENABLE_FALSE_START);
	if (ret < 0)
		exit(1);

	ret = gnutls_credentials_set(client, GNUTLS_CRD_CERTIFICATE,
				clientx509cred);
	if (ret < 0)
		exit(1);

	gnutls_set_default_priority(client);
	gnutls_transport_set_push_function(client, client_push);
	gnutls_transport_set_pull_function(client, client_pull);
	gnutls_transport_set_ptr(client, client);

	memset(buf, 0, sizeof(buf));
	ret = gnutls_session_set_data(client, buf, sizeof(buf));
	if (ret != GNUTLS_E_DB_ERROR) {
		fail("unexpected error: %s\n", gnutls_strerror(ret));
	}

	HANDSHAKE(client, server);

	/* try obtaining the resumption data. This should fail because
	 * the handshake is not yet complete (due to false start) */
	ret = gnutls_session_get_data2(client, &data);
	if (ret != GNUTLS_E_UNAVAILABLE_DURING_HANDSHAKE) {
		fail("unexpected error: %s\n", gnutls_strerror(ret));
	}

	ret = gnutls_record_recv(client, buf, sizeof(buf));
	if (ret < 0 && ret != GNUTLS_E_AGAIN) {
		fail("unexpected error: %s\n", gnutls_strerror(ret));
	}

	ret = gnutls_session_get_data2(client, &data);
	if (ret != 0) {
		fail("unexpected error: %s\n", gnutls_strerror(ret));
	}
	gnutls_free(data.data);

	gnutls_bye(client, GNUTLS_SHUT_RDWR);
	gnutls_bye(server, GNUTLS_SHUT_RDWR);

	gnutls_deinit(client);
	gnutls_deinit(server);

	gnutls_certificate_free_credentials(serverx509cred);
	gnutls_certificate_free_credentials(clientx509cred);

	gnutls_global_deinit();

	if (debug > 0) {
		if (exit_code == 0)
			puts("Self-test successful");
		else
			puts("Self-test failed");
	}
}
Пример #25
0
static
int check_dsa(void)
{
	gnutls_privkey_t key;
	gnutls_pubkey_t pub;
	gnutls_datum_t p, q, g, y, x;
	int ret;

	global_init();

	success("Checking DSA key operations\n");

	ret = gnutls_privkey_init(&key);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_pubkey_init(&pub);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_privkey_import_x509_raw(key, &dsa_key, GNUTLS_X509_FMT_PEM, 0, 0);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_pubkey_import_privkey(pub, key, 0, 0);
	if (ret < 0)
		fail("error\n");

	ret = gnutls_pubkey_export_dsa_raw2(pub, &p, &q, &g, &y, 0);
	if (ret < 0)
		fail("error\n");

	CMP("p", &p, dsa_p);
	CMP("q", &q, dsa_q);
	CMP("g", &g, dsa_g);
	CMP("y", &y, dsa_y);
	gnutls_free(p.data);
	gnutls_free(q.data);
	gnutls_free(g.data);
	gnutls_free(y.data);

	ret = gnutls_pubkey_export_dsa_raw2(pub, &p, &q, &g, &y, GNUTLS_EXPORT_FLAG_NO_LZ);
	if (ret < 0)
		fail("error\n");

	CMP_NO_LZ("p", &p, dsa_p);
	CMP_NO_LZ("q", &q, dsa_q);
	CMP_NO_LZ("g", &g, dsa_g);
	CMP_NO_LZ("y", &y, dsa_y);
	gnutls_free(p.data);
	gnutls_free(q.data);
	gnutls_free(g.data);
	gnutls_free(y.data);

	ret = gnutls_privkey_export_dsa_raw(key, &p, &q, &g, &y, &x);
	if (ret < 0)
		fail("error\n");
	CMP("p", &p, dsa_p);
	CMP("q", &q, dsa_q);
	CMP("g", &g, dsa_g);
	CMP("y", &y, dsa_y);
	CMP("x", &x, dsa_x);
	gnutls_free(p.data);
	gnutls_free(q.data);
	gnutls_free(g.data);
	gnutls_free(y.data);
	gnutls_free(x.data);

	ret = _gnutls_privkey_export2_pkcs8(key, GNUTLS_X509_FMT_DER, NULL, 0, &x);
	if (ret < 0 || x.size == 0)
		fail("error in pkcs8 export\n");
	gnutls_free(x.data);

	gnutls_privkey_deinit(key);
	gnutls_pubkey_deinit(pub);

	return 0;
}
Пример #26
0
static void server(int fd)
{
	int ret;
	char buffer[MAX_BUF + 1];
	gnutls_session_t session;
	gnutls_certificate_credentials_t x509_cred;
	gnutls_datum_t skey;

	/* this must be called once in the program
	 */
	global_init();
	memset(buffer, 0, sizeof(buffer));

	if (debug) {
		gnutls_global_set_log_function(server_log_func);
		gnutls_global_set_log_level(4711);
	}

	assert(gnutls_certificate_allocate_credentials(&x509_cred)>=0);
	assert(gnutls_certificate_set_x509_key_mem(x509_cred, &server_cert,
					    &server_key,
					    GNUTLS_X509_FMT_PEM)>=0);

	assert(gnutls_init(&session, GNUTLS_SERVER)>=0);

	assert(gnutls_session_ticket_key_generate(&skey)>=0);
	assert(gnutls_session_ticket_enable_server(session, &skey) >= 0);

	gnutls_handshake_set_hook_function(session, GNUTLS_HANDSHAKE_NEW_SESSION_TICKET,
					   GNUTLS_HOOK_POST,
					   handshake_callback);

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

	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, x509_cred);

	gnutls_transport_set_int(session, fd);

	do {
		ret = gnutls_handshake(session);
	} while (ret < 0 && gnutls_error_is_fatal(ret) == 0);
	if (ret < 0) {
		/* failure is expected here */
		goto end;
	}

	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)));

	if (sent != 0) {
		fail("new session ticket was sent\n");
		exit(1);
	}		

	/* do not wait for the peer to close the connection.
	 */
	gnutls_bye(session, GNUTLS_SHUT_WR);

 end:
	close(fd);
	gnutls_deinit(session);
	gnutls_free(skey.data);

	gnutls_certificate_free_credentials(x509_cred);

	gnutls_global_deinit();

	if (debug)
		success("server: finished\n");
}
Пример #27
0
int WINAPI _tWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
	// Init any globals not in "struct g" that need it:
	g_hInstance = hInstance;
	InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x).

	if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround.
		*g_WorkingDir = '\0';
	// Unlike the below, the above must not be Malloc'd because the contents can later change to something
	// as large as MAX_PATH by means of the SetWorkingDir command.
	g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command.

	// Set defaults, to be overridden by command line args we receive:
	bool restart_mode = false;

#ifndef AUTOHOTKEYSC
	//#ifdef _DEBUG				// HotKeyIt, debugger will launch AutoHotkey.ahk as normal AutoHotkey.exe does
	//	TCHAR *script_filespec = _T("Test\\Test.ahk");
	//#else
		TCHAR *script_filespec = NULL; // Set default as "unspecified/omitted".
	//#endif
#endif

	// The problem of some command line parameters such as /r being "reserved" is a design flaw (one that
	// can't be fixed without breaking existing scripts).  Fortunately, I think it affects only compiled
	// scripts because running a script via AutoHotkey.exe should avoid treating anything after the
	// filename as switches. This flaw probably occurred because when this part of the program was designed,
	// there was no plan to have compiled scripts.
	// 
	// Examine command line args.  Rules:
	// Any special flags (e.g. /force and /restart) must appear prior to the script filespec.
	// The script filespec (if present) must be the first non-backslash arg.
	// All args that appear after the filespec are considered to be parameters for the script
	// and will be added as variables %1% %2% etc.
	// The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters
	// unless the filename is explicitly given (shouldn't be an issue for 99.9% of people).
	TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%).
	Var *var;
	bool switch_processing_is_complete = false;
	int script_param_num = 1;

	for (int i = 1; i < __argc; ++i) // Start at 1 because 0 contains the program name.
	{
		param = __targv[i]; // For performance and convenience.
		if (switch_processing_is_complete) // All args are now considered to be input parameters for the script.
		{
			if (   !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num)))   )
				return CRITICAL_ERROR;  // Realistically should never happen.
			var->Assign(param);
			++script_param_num;
		}
		// Insist that switches be an exact match for the allowed values to cut down on ambiguity.
		// For example, if the user runs "CompiledScript.exe /find", we want /find to be considered
		// an input parameter for the script rather than a switch:
		else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart")))
			restart_mode = true;
		else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force")))
			g_ForceLaunch = true;
		else if (!_tcsicmp(param, _T("/ErrorStdOut")))
			g_script.mErrorStdOut = true;
#ifndef AUTOHOTKEYSC // i.e. the following switch is recognized only by AutoHotkey.exe (especially since recognizing new switches in compiled scripts can break them, unlike AutoHotkey.exe).
		else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script.
		{
			++i; // Consume the next parameter too, because it's associated with this one.
			if (i >= __argc) // Missing the expected filename parameter.
				return CRITICAL_ERROR;
			// For performance and simplicity, open/create the file unconditionally and keep it open until exit.
			g_script.mIncludeLibraryFunctionsThenExit = new TextFile;
			if (!g_script.mIncludeLibraryFunctionsThenExit->Open(__targv[i], TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file.
				return CRITICAL_ERROR;
		}
		else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn
		{
			// Default codepage for the script file, NOT the default for commands used by it.
			g_DefaultScriptCodepage = ATOU(param + 3);
		}
#endif
#ifdef CONFIG_DEBUGGER
		// Allow a debug session to be initiated by command-line.
		else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '='))
		{
			if (param[6] == '=')
			{
				param += 7;

				LPTSTR c = _tcsrchr(param, ':');

				if (c)
				{
					StringTCharToChar(param, g_DebuggerHost, (int)(c-param));
					StringTCharToChar(c + 1, g_DebuggerPort);
				}
				else
				{
					StringTCharToChar(param, g_DebuggerHost);
					g_DebuggerPort = "9000";
				}
			}
			else
			{
				g_DebuggerHost = "127.0.0.1";
				g_DebuggerPort = "9000";
			}
			// The actual debug session is initiated after the script is successfully parsed.
		}
#endif
		else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design).
		{
			switch_processing_is_complete = true;  // No more switches allowed after this point.
#ifdef AUTOHOTKEYSC
			--i; // Make the loop process this item again so that it will be treated as a script param.
#else
			script_filespec = param;  // The first unrecognized switch must be the script filespec, by design.
#endif
		}
	}

#ifndef AUTOHOTKEYSC
	if (script_filespec)// Script filename was explicitly specified, so check if it has the special conversion flag.
	{
		size_t filespec_length = _tcslen(script_filespec);
		if (filespec_length >= CONVERSION_FLAG_LENGTH)
		{
			LPTSTR cp = script_filespec + filespec_length - CONVERSION_FLAG_LENGTH;
			// Now cp points to the first dot in the CONVERSION_FLAG of script_filespec (if it has one).
			if (!_tcsicmp(cp, CONVERSION_FLAG))
				return Line::ConvertEscapeChar(script_filespec);
		}
	}
#endif

	// Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero:
	if (   !(var = g_script.FindOrAddVar(_T("0")))   )
		return CRITICAL_ERROR;  // Realistically should never happen.
	var->Assign(script_param_num - 1);

	global_init(*g);  // Set defaults prior to the below, since below might override them for AutoIt2 scripts.

// Set up the basics of the script:
#ifdef AUTOHOTKEYSC
	if (g_script.Init(*g, _T(""), restart_mode,0,false) != OK) 
#else
	if (g_script.Init(*g, script_filespec, restart_mode,0,false) != OK)  // Set up the basics of the script, using the above.
#endif
		return CRITICAL_ERROR;

	// Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below,
	// never returns, perhaps because it contains an infinite loop (intentional or not):
	CopyMemory(&g_default, g, sizeof(global_struct));

	// Could use CreateMutex() but that seems pointless because we have to discover the
	// hWnd of the existing process so that we can close or restart it, so we would have
	// to do this check anyway, which serves both purposes.  Alt method is this:
	// Even if a 2nd instance is run with the /force switch and then a 3rd instance
	// is run without it, that 3rd instance should still be blocked because the
	// second created a 2nd handle to the mutex that won't be closed until the 2nd
	// instance terminates, so it should work ok:
	//CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness.
	//if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS)
#ifdef STANDALONE
	UINT load_result;
	if (script_filespec != NULL)
		load_result = g_script.LoadFromFile(script_filespec);
	else
	{
		TCHAR INTERNAL_SCRIPT[] = {
			#include "Script.ahk"
		};
		load_result = g_script.LoadFromText(INTERNAL_SCRIPT);
	}
#else
#ifdef AUTOHOTKEYSC
	UINT load_result = g_script.LoadFromFile();
#else
	UINT load_result = g_script.LoadFromFile(script_filespec == NULL);
#endif
#endif
	if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call).
		return CRITICAL_ERROR;  // Should return this value because PostQuitMessage() also uses it.
	if (!load_result) // LoadFromFile() relies upon us to do this check.  No script was loaded or we're in /iLib mode, so nothing more to do.
		return 0;

	// Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of
	// SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts
	// and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16:
	if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE && IS_PERSISTENT)
		g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT;

	HWND w_existing = NULL;
	UserMessages reason_to_close_prior = (UserMessages)0;
	if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch)
	{
		// Note: the title below must be constructed the same was as is done by our
		// CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle:
		if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle))
		{
			if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE)
				return 0;
			if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE)
				if (MsgBox(_T("An older instance of this script is already running.  Replace it with this")
					_T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.")
					, MB_YESNO, g_script.mFileName) == IDNO)
					return 0;
			// Otherwise:
			reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE;
		}
	}
	if (!reason_to_close_prior && restart_mode)
		if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle))
			reason_to_close_prior = AHK_EXIT_BY_RELOAD;
	if (reason_to_close_prior)
	{
		// Now that the script has been validated and is ready to run, close the prior instance.
		// We wait until now to do this so that the prior instance's "restart" hotkey will still
		// be available to use again after the user has fixed the script.  UPDATE: We now inform
		// the prior instance of why it is being asked to close so that it can make that reason
		// available to the OnExit subroutine via a built-in variable:
		ASK_INSTANCE_TO_CLOSE(w_existing, reason_to_close_prior);
		//PostMessage(w_existing, WM_CLOSE, 0, 0);

		// Wait for it to close before we continue, so that it will deinstall any
		// hooks and unregister any hotkeys it has:
		int interval_count;
		for (interval_count = 0; ; ++interval_count)
		{
			Sleep(20);  // No need to use MsgSleep() in this case.
			if (!IsWindow(w_existing))
				break;  // done waiting.
			if (interval_count == 100)
			{
				// This can happen if the previous instance has an OnExit subroutine that takes a long
				// time to finish, or if it's waiting for a network drive to timeout or some other
				// operation in which it's thread is occupied.
				if (MsgBox(_T("Could not close the previous instance of this script.  Keep waiting?"), 4) == IDNO)
					return CRITICAL_ERROR;
				interval_count = 0;
			}
		}
		// Give it a small amount of additional time to completely terminate, even though
		// its main window has already been destroyed:
		Sleep(100);
	}

	// Call this only after closing any existing instance of the program,
	// because otherwise the change to the "focus stealing" setting would never be undone:
	SetForegroundLockTimeout();

	// Create all our windows and the tray icon.  This is done after all other chances
	// to return early due to an error have passed, above.
	if (g_script.CreateWindows() != OK)
		return CRITICAL_ERROR;

	// At this point, it is nearly certain that the script will be executed.

	// v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately
	// rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little
	// impact on performance given the OS's built-in caching.  I looked at the source code for setvbuf()
	// and it seems like it should execute very quickly.  Code size seems to be about 75 bytes.
	setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout.

	if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem))))
		ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed.
	//else leave it NULL as it was initialized in globaldata.

	// MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required."
	// Therefore, in case it's a high overhead call, it's not done on XP or later:
	if (!g_os.IsWinXPorLater())
	{
		// Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal
		// controls, InitCommonControlsEx() must be called.  But since Ex() requires comctl32.dll
		// 4.70+, must get the function's address dynamically in case the program is running on
		// Windows 95/NT without the updated DLL (otherwise the program would not launch at all).
		typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX);
		MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType)
			GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler.
		if (MyInitCommonControlsEx)
		{
			INITCOMMONCONTROLSEX icce;
			icce.dwSize = sizeof(INITCOMMONCONTROLSEX);
			icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls().
			MyInitCommonControlsEx(&icce);
		}
		else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4.
			InitCommonControls();
	}

#ifdef CONFIG_DEBUGGER
	// Initiate debug session now if applicable.
	if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK)
	{
		g_Debugger.ProcessCommands();
	}
#endif

	// Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the
	// top part (the auto-execute part) of the script so that they will be in effect even if the
	// top part is something that's very involved and requires user interaction:
	Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop)
	g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp.

	Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable.
	if (clipboard_var)
		// This is done here rather than upon variable creation speed up runtime/dynamic variable creation.
		// Since the clipboard can be changed by activity outside the program, don't read-cache its contents.
		// Since other applications and the user should see any changes the program makes to the clipboard,
		// don't write-cache it either.
		clipboard_var->DisableCache();

	// Run the auto-execute part at the top of the script (this call might never return):
	if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort.
		return CRITICAL_ERROR;
	// REMEMBER: The call above will never return if one of the following happens:
	// 1) The AutoExec section never finishes (e.g. infinite loop).
	// 2) The AutoExec function uses uses the Exit or ExitApp command to terminate the script.
	// 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit).

	// Call it in this special mode to kick off the main event loop.
	// Be sure to pass something >0 for the first param or it will
	// return (and we never want this to return):
	MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES);
	return 0; // Never executed; avoids compiler warning.
}
Пример #28
0
static void client(int fd)
{
	int ret;
	gnutls_certificate_credentials_t x509_cred;
	gnutls_session_t session;
	/* Need to enable anonymous KX specifically. */

	gnutls_global_set_time_function(mytime);
	global_init();

	if (debug) {
		gnutls_global_set_log_function(client_log_func);
		gnutls_global_set_log_level(7);
	}

	gnutls_certificate_allocate_credentials(&x509_cred);

	/* Initialize TLS session
	 */
	gnutls_init(&session, GNUTLS_CLIENT|GNUTLS_NO_TICKETS);

	/* Use default priorities */
	gnutls_priority_set_direct(session, "NORMAL:-KX-ALL:+ECDHE-RSA", NULL);

	/* put the anonymous credentials to the current session
	 */
	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, x509_cred);

	gnutls_transport_set_int(session, fd);

	/* Perform the TLS handshake
	 */
	do {
		ret = gnutls_handshake(session);
	}
	while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

	if (ret == GNUTLS_E_UNSUPPORTED_SIGNATURE_ALGORITHM) {
		/* success */
		goto end;
	}

	if (ret < 0) {
		fail("client: Handshake failed: %s\n", gnutls_strerror(ret));
		terminate();
	} else {
		if (debug)
			success("client: Handshake was completed\n");
	}

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

	gnutls_bye(session, GNUTLS_SHUT_WR);

      end:

	close(fd);

	gnutls_deinit(session);

	gnutls_certificate_free_credentials(x509_cred);

	gnutls_global_deinit();
}
Пример #29
0
static void client(int fd, int proto, int cipher, int mac)
{
	int ret;
	char buffer[MAX_BUF + 1];
	gnutls_certificate_credentials_t xcred;
	gnutls_session_t session;

	global_init();

	if (debug) {
		gnutls_global_set_log_function(client_log_func);
		gnutls_global_set_log_level(4711);
	}

	gnutls_certificate_allocate_credentials(&xcred);

	/* Initialize TLS session
	 */
	gnutls_init(&session, GNUTLS_CLIENT | GNUTLS_DATAGRAM);
	gnutls_dtls_set_mtu(session, 1500);
	gnutls_handshake_set_timeout(session, 20 * 1000);

	/* Use default priorities */
	gnutls_priority_set_direct(session,
				   "NONE:+VERS-DTLS0.9:+COMP-NULL:+AES-128-GCM:+AEAD:+AES-128-CBC:+SHA1:+RSA:%COMPAT",
				   NULL);

	ret = gnutls_session_set_premaster(session, GNUTLS_CLIENT,
		proto, GNUTLS_KX_RSA,
		cipher, mac,
		GNUTLS_COMP_NULL, &master, &sess_id);
	if (ret < 0) {
		fail("client: gnutls_session_set_premaster failed: %s\n", gnutls_strerror(ret));
		exit(1);
	}

	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred);

	gnutls_transport_set_int(session, fd);
	gnutls_transport_set_push_function(session, push);

	/* Perform the TLS handshake
	 */
	do {
		ret = gnutls_handshake(session);
	}
	while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

	if (ret < 0) {
		fail("client: Handshake failed\n");
		gnutls_perror(ret);
		exit(1);
	} else {
		if (debug)
			success("client: Handshake was completed\n");
	}

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

	do {
		ret = gnutls_record_recv(session, buffer, sizeof(buffer)-1);
	} while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);

	if (ret == 0) {
		if (debug)
			success
			    ("client: Peer has closed the TLS connection\n");
		goto end;
	} else if (ret < 0) {
		fail("client: Error: %s\n", gnutls_strerror(ret));
		exit(1);
	}

	gnutls_bye(session, GNUTLS_SHUT_WR);

      end:

	close(fd);

	gnutls_deinit(session);

	gnutls_certificate_free_credentials(xcred);

	gnutls_global_deinit();
}
Пример #30
-1
static void
client (int fd, const char* prio, unsigned int text_size, struct test_st *test)
{
  int ret;
  char buffer[MAX_BUF + 1];
  char text[text_size];
  gnutls_certificate_credentials_t x509_cred;
  gnutls_session_t session;
  struct timespec start, stop;
  static unsigned long taken = 0;
  static unsigned long measurement;
  const char* err;

  global_init ();
  
  setpriority(PRIO_PROCESS, getpid(), -15);
  
  memset(text, 0, text_size);

#ifdef DEBUG
  gnutls_global_set_log_function (client_log_func);
  gnutls_global_set_log_level (6);
#endif

  gnutls_certificate_allocate_credentials (&x509_cred);

#ifdef REHANDSHAKE
restart:
#endif

  /* Initialize TLS session
   */
  gnutls_init (&session, GNUTLS_CLIENT);
  gnutls_session_set_ptr(session, test);
  cli_session = session;

  /* Use default priorities */
  if ((ret=gnutls_priority_set_direct (session, prio, &err)) < 0) {
    fprintf(stderr, "Error in priority string %s: %s\n", gnutls_strerror(ret), err);
    exit(1);
  }

  /* put the anonymous credentials to the current session
   */
  gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, x509_cred);
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) fd);

  /* Perform the TLS handshake
   */
  do 
    {
      ret = gnutls_handshake (session);
    }
  while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

  if (ret < 0)
    {
      fprintf (stderr, "client: Handshake failed\n");
      gnutls_perror (ret);
      exit(1);
    }
   
  ret = gnutls_protocol_get_version(session);
  if (ret < GNUTLS_TLS1_1)
    {
      fprintf (stderr, "client: Handshake didn't negotiate TLS 1.1 (or later)\n");
      exit(1);
    }

  gnutls_transport_set_push_function (session, push_crippled);

#ifndef REHANDSHAKE
restart:
#endif
  do {
    ret = gnutls_record_send (session, text, sizeof(text));
  } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);
  /* measure peer's processing time */
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);

#define TLS_RECV
#ifdef TLS_RECV
  do {
    ret = gnutls_record_recv(session, buffer, sizeof(buffer));
  } while(ret < 0 && (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED));
#else
  do {
    ret = recv(fd, buffer, sizeof(buffer), 0);
  } while(ret == -1 && errno == EAGAIN);
#endif

  if (taken < MAX_MEASUREMENTS(test->npoints) && ret > 0)
    {
      clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &stop);
      taken++;
      measurement = timespec_sub_ns(&stop, &start);
      prev_point_ptr->measurements[prev_point_ptr->midx] = measurement;

/*fprintf(stderr, "(%u,%u): %lu\n", (unsigned) prev_point_ptr->byte1,
 (unsigned) prev_point_ptr->byte2, measurements[taken]);*/
      memcpy(&measurement, buffer, sizeof(measurement));
      prev_point_ptr->smeasurements[prev_point_ptr->midx] = measurement;
      prev_point_ptr->midx++;

      /* read server's measurement */
      
#ifdef REHANDSHAKE
      gnutls_deinit(session);
#endif      
      goto restart;
    }
#ifndef TLS_RECV
  else if (ret < 0)
    {
      fprintf(stderr, "Error in recv()\n");
      exit(1);
    }
#endif

  gnutls_transport_set_push_function (session, push);
    
  gnutls_bye (session, GNUTLS_SHUT_WR);
  
  {
    double avg2, med, savg, smed;
    unsigned i;
    FILE* fp = NULL;
    
    if (test->file)
      fp = fopen(test->file, "w");
    
    if (fp) /* point, avg, median */
     fprintf(fp, "Delta,TimeAvg,TimeMedian,ServerAvg,ServerMedian\n");

    for (i=0;i<test->npoints;i++)
      {
        qsort( test->points[i].measurements, test->points[i].midx, 
               sizeof(test->points[i].measurements[0]), compar);

        qsort( test->points[i].smeasurements, test->points[i].midx, 
               sizeof(test->points[i].smeasurements[0]), compar);
     
        avg2 = calc_avg( test->points[i].measurements, test->points[i].midx);
        /*var = calc_var( test->points[i].measurements, test->points[i].midx, avg2);*/
        med = calc_median( test->points[i].measurements, test->points[i].midx);

        savg = calc_avg( test->points[i].smeasurements, test->points[i].midx);
        /*var = calc_var( test->points[i].measurements, test->points[i].midx, avg2);*/
        smed = calc_median( test->points[i].smeasurements, test->points[i].midx);
        /*min = calc_min( test->points[i].measurements, test->points[i].midx);*/
        
        if (fp) /* point, avg, median */
          fprintf(fp, "%u,%.2lf,%.2lf,%.2lf,%.2lf\n", (unsigned)test->points[i].byte1, 
                  avg2,med,savg, smed);
        
        /*printf("(%u) Avg: %.3f nanosec, Median: %.3f, Variance: %.3f\n", (unsigned)test->points[i].byte1, 
               avg2, med, var);*/
      }

    if (fp)
      fclose(fp);
  }

  if (test->desc)
    fprintf(stderr, "Description: %s\n", test->desc);

  close (fd);

  gnutls_deinit (session);

  gnutls_certificate_free_credentials (x509_cred);

  gnutls_global_deinit ();
}