Ejemplo n.º 1
1
int main(int argc, char *argv[])
{   FILE *inf, *outf;
    unsigned char buf[1024], tmp_buf1[16], tmp_buf2[16], salt[16], *fname, *cp;
    fcrypt_ctx  zcx[1];
    int len, flen, err = 0;
    unsigned char mode;

    if(argc != 3)   /* the command line is bad  */
    {
        err = ERROR_USAGE; goto error_0;
    }


    len = (int)strlen(argv[1]);

    if(len < 8)     /* password is too short    */
    {
        err = ERROR_PASSWORD_LENGTH; goto error_0;
    }

    /* set the key length based on password length assuming that there  */
    /* are about 4 bits of entropy per password character (the key      */
    /* length and other mode dependent parameter values are set using   */
    /* macros defined in fileenc.h)                                     */
    mode = (len < 32 ? 1 : len < 48 ? 2 : 3);

    /* save input file name to a temporary memory area with extra space */
    /* for the extension ".enc" to be added                             */
    fname = (unsigned char*)malloc(strlen(argv[2]) + 5);
    if(fname == NULL)
    {
        err = ERROR_OUT_OF_MEMORY; goto error_0;
    }

    /* open the input file  */
    strcpy(fname, argv[2]);
    if((inf = fopen(fname, "rb")) == NULL)
    {
        err = ERROR_INPUT_FILE; goto error_1;
    }

    /* if the file name extension is ".enc" assume this is an encrypted */
    /* file                                                             */
    if((cp = strrchr(fname, '.')) && strcmp(cp, ".enc") == 0)
    {
        *cp = 0;
        mode |= 4;  /* signal decryption */
    }
    else                        /* add ".enc" to file name to mark the  */
        strcat(fname, ".enc");  /* the file as an encrypted one         */

    /* open output file for binary output */
    if((outf = fopen(fname, "wb")) == NULL)
    {
        err = ERROR_OUTPUT_FILE; goto error_2;
    }

    if(!(mode & 4))         /* encryption operation     */
    {
        prng_ctx rng[1];    /* the context for the random number pool   */
        prng_init(entropy_fun, rng);                /* initialise RNG   */
        prng_rand(salt, SALT_LENGTH(mode), rng);    /* and the salt     */

        /* write salt value         */
        fwrite(salt, sizeof(unsigned char), SALT_LENGTH(mode), outf);

        /* initialise encryption and authentication */
#ifdef PASSWORD_VERIFIER
        fcrypt_init(mode, argv[1], (unsigned int)strlen(argv[1]), salt, tmp_buf1, zcx);
        /* write password verifier (if used)        */
        fwrite(tmp_buf1, sizeof(unsigned char), PWD_VER_LENGTH, outf);
#else
        fcrypt_init(mode, argv[1], (unsigned int)strlen(argv[1]), salt, zcx);
#endif
        /* encrypt and authenticate the file        */
        len = (int)fread(buf, sizeof(unsigned char), 1024, inf);
        while(len)
        {
            fcrypt_encrypt(buf, len, zcx);
            fwrite(buf, sizeof(unsigned char), len, outf);
            len = (int)fread(buf, sizeof(unsigned char), len, inf);
        }

        /* write the MAC    */
        fcrypt_end(tmp_buf1, zcx);
        fwrite(tmp_buf1, sizeof(unsigned char), MAC_LENGTH(mode), outf);

        /* and close random pool    */
        prng_end(rng);
    }
    else                    /* decryption operation     */
    {
        /* we need to know the file length to avoid reading the MAC */
        fseek(inf, 0, SEEK_END);
        flen = ftell(inf);
        fseek(inf, 0, SEEK_SET);
        mode &= 3;

        /* recover the password salt     */
        fread(salt, sizeof(unsigned char), SALT_LENGTH(mode), inf); flen -= SALT_LENGTH(mode);
#ifdef  PASSWORD_VERIFIER
        /* initialise encryption and authentication */
        fcrypt_init(mode, argv[1], (unsigned int)strlen(argv[1]), salt, tmp_buf2, zcx);
        /* recover the password verifier (if used)  */
        fread(tmp_buf1, sizeof(unsigned char), PWD_VER_LENGTH, inf); flen -= PWD_VER_LENGTH;
        /* check password verifier  */
        if(memcmp(tmp_buf1, tmp_buf2, PWD_VER_LENGTH))
        {
            err = ERROR_BAD_PASSWORD; fclose(outf); goto error_2;
        }
#else
        /* initialise encryption and authentication */
        fcrypt_init(mode, argv[1], (unsigned int)strlen(argv[1]), salt, zcx);
#endif

        flen -= MAC_LENGTH(mode);   /* avoid reading the MAC    */
        /* decrypt the file     */
        len = (int)fread(buf, sizeof(unsigned char),
                    (size_t)(flen < 1024 ? flen : 1024), inf);
        while(len)
        {   flen -= len;
            fcrypt_decrypt(buf, len, zcx);
            fwrite(buf, sizeof(unsigned char), len, outf);
            len = (int)fread(buf, sizeof(unsigned char),
                        (size_t)(flen < 1024 ? flen : 1024), inf);
        }

        /* calculate the MAC value          */
        fcrypt_end(tmp_buf2, zcx);

        /* now read the stored MAC value    */
        fread(tmp_buf1, sizeof(unsigned char), MAC_LENGTH(mode), inf);

        /* compare the stored and calculated MAC values */
        if(memcmp(tmp_buf1, tmp_buf2, MAC_LENGTH(mode)))
        {   /* authentication failed        */

            err = ERROR_BAD_AUTHENTICATION;
            fclose(outf);
            /* delete the (bad) output file */
            remove(fname);
            goto error_2;
        }
    }

    fclose(outf);
error_2:
    fclose(inf);
error_1:
    free(fname);
error_0:
    if(err)
        printf(err_string[err - 1], fname);
    return -err;
}
Ejemplo n.º 2
0
byte *ecc_encode(vlPoint session, vlPoint publicKey, vlPoint msg)
{
    lunit   *expt = NULL;
    lunit   *logt = NULL;

    assert(session != NULL && publicKey != NULL);
    prng            p;
    int             i;
    byte            *result;
    ByteArrayStream bas;
    byteStreamInit(&bas, (VL_SIZE) << 1);
    prng_init(&p);
    gfInit(&expt, &logt);
    cpEncodeSecret(publicKey, msg, session, expt, logt);

    for (i = 0; i < VL_SIZE; i++) {
        bas.writeShort(&bas, msg[i]);
    }

    gfQuit(expt, logt);
    result = bas.toArray(&bas);
    bas.dispose(&bas);
    prng_init(&p);
    vlClear(publicKey);
    vlClear(session);
    return result;
}
Ejemplo n.º 3
0
byte *getRc4Key(const char *seed, vlPoint rc4Encode, vlPoint publicKey, vlPoint msg)
{
    lunit   *expt = NULL;
    lunit   *logt = NULL;

    assert(rc4Encode != NULL);
    prng            p;
    int             i;
    byte            *result;
    ByteArrayStream bas;
    byteStreamInit(&bas, (VL_SIZE) << 1);

    prng_init(&p);
    prng_set_secret_str(&p, seed);  // seed 生成Rc4秘钥
    prng_set_time(&p);
    prng_to_vlong(&p, rc4Encode);   // 生成 写入
    gfInit(&expt, &logt);
    cpEncodeSecret(publicKey, msg, rc4Encode, expt, logt);
    gfQuit(expt, logt);

    for (i = 0; i < VL_SIZE; i++) {
        bas.writeShort(&bas, rc4Encode[i]);
    }

    result = bas.toArray(&bas);
    bas.dispose(&bas);
    prng_init(&p);
    vlClear(rc4Encode);
    return result;
}
Ejemplo n.º 4
0
byte *ecc_decode(vlPoint toDecode, const char *passwd, vlPoint msg)
{
    lunit   *expt = NULL;
    lunit   *logt = NULL;

    assert(toDecode != NULL);
    prng            p;
    int             i;
    vlPoint         secret;
    byte            *result;
    ByteArrayStream bas;
    byteStreamInit(&bas, (VL_SIZE) << 1);
    prng_init(&p);
    prng_set_secret_str(&p, passwd);
    prng_to_vlong(&p, secret);
    gfInit(&expt, &logt);
    assert(logt != NULL && expt != NULL);
    cpDecodeSecret(secret, toDecode, msg, expt, logt);

    for (i = 0; i < VL_SIZE; i++) {
        bas.writeShort(&bas, msg[i]);
    }

    gfQuit(expt, logt);
    result = bas.toArray(&bas);
    bas.dispose(&bas);
    prng_init(&p);
    vlClear(secret);
    return result;
}
Ejemplo n.º 5
0
byte *getPubKey(const char *password, vlPoint publicKey)
{
    lunit           *expt = NULL;
    lunit           *logt = NULL;
    vlPoint         secret;
    prng            p;
    int             i;
    byte            *result;
    ByteArrayStream bas;

    byteStreamInit(&bas, (VL_SIZE) << 1);
    prng_init(&p);
    prng_set_secret_str(&p, password);  // 生成SHA-1的Password串
    prng_to_vlong(&p, secret);          // 将160bit的SHA-1转换成vlPoint
    gfInit(&expt, &logt);
    assert(logt != NULL && expt != NULL);
    cpMakePublicKey(publicKey, secret, expt, logt);

    for (i = 0; i < VL_SIZE; i++) {
        bas.writeShort(&bas, publicKey[i]); // 输入之后一定是BIG_ENDIAN
    }

    result = bas.toArray(&bas);
    bas.dispose(&bas);
    gfQuit(expt, logt);
    prng_init(&p);
    vlClear(secret);
    return result;
}
Ejemplo n.º 6
0
END_TEST

static void test_manifest_tell_seek(enum protocol protocol, int phase)
{
	struct slist *slist;
	struct manio *manio;
	struct sbuf *sb=NULL;
	man_off_t *offset=NULL;
	int entries=1000;
	prng_init(0);
	base64_init();
	hexmap_init();
	recursive_delete(path);

	slist=build_manifest(path, protocol, entries, phase);
	fail_unless(slist!=NULL);

	sb=slist->head;
	fail_unless((manio=do_manio_open(path, "rb", protocol, phase))!=NULL);
	read_manifest(&sb, manio, 0, entries/2, protocol, phase);
	fail_unless((offset=manio_tell(manio))!=NULL);
	fail_unless(sb!=NULL);
	fail_unless(!manio_close(&manio));

	fail_unless((manio=do_manio_open(path, "rb", protocol, phase))!=NULL);
	fail_unless(!manio_seek(manio, offset));
	read_manifest(&sb, manio, entries/2, entries, protocol, phase);
	fail_unless(sb==NULL);
	fail_unless(!manio_close(&manio));
	fail_unless(!manio);

	slist_free(&slist);
	man_off_t_free(&offset);
	tear_down();
}
Ejemplo n.º 7
0
void pb_init(const char *bookfile)
{
  if (!bookfile || strlen(bookfile) == 0 || strcmp(bookfile, "<empty>") == 0) {
    enabled = false;
    return;
  }

  pb_free();

  FD fd = open_file(bookfile);
  if (fd != FD_ERR) {
    keycount = file_size(fd) / 16;
    polyhash = map_file(fd, &mapping);
  }
  close_file(fd);

  if (!polyhash) {
    printf("info string Could not open %s\n", bookfile);
    enabled = false;
    return;
  }

  prng_init(&sr, time(NULL));
  for (int i = 0; i < 10; i++)
    prng_rand(&sr);

  printf("info string Book loaded: %s\n", bookfile);

  enabled = true;
}
Ejemplo n.º 8
0
/** @brief Process a login packet.
 *
 * A login packet consists of a 32-byte uninterpreted value.
 * [SHA256_OUTPUT_LEN-byte uninterpreted array]
 *
 * On success, the reponse packet is
 * [CR_PUBKEY][(uint16) CHAT_PUBKEY_LEN][byte array of length CHAT_PUBKEY_LEN]
 *
 * @param ctx Non-null. The chat context.
 * @param pkt Non-null. The incoming login packet. On success, this
 *            pointer re-used to format the outgoing reply message.
 * @return 0 on success.
 */
int chat_process_login(chat_context_t *ctx, ffs_packet_t *pkt) {
    int err = 0;

    /* Generate the ECC key and compute its hash */
    {
        chat_ecc_genkey(pkt->data, ctx->key_prv, ctx->key_pub);
        sha256_hash(ctx->key_pub, ECC_POINT_LEN, ctx->key_pub_hash);
    }

    /* Initialize the prng */
    {
        uint8_t seed[SHA256_OUTPUT_LEN];
        sha256_hash(pkt->data, SHA256_OUTPUT_LEN, seed);
        uint8_t r[SHA256_OUTPUT_LEN];
        for (int i = 0; i < SHA256_OUTPUT_LEN; i++)
            msel_svc(MSEL_SVC_TRNG, &r[i]);
        sha256_hash(r, SHA256_OUTPUT_LEN, r);
        for (int i = 0; i < SHA256_OUTPUT_LEN; i++)
            seed[i] ^= r[i];
        sha256_hash(seed, SHA256_OUTPUT_LEN, seed);
        prng_init(&ctx->prng, AES_128, seed, ((uint64_t*)seed)[2], ((uint64_t*)seed)[3]);
    }

    /* Format the response */
    {
        uint32_t length = 0;
        msel_memset(pkt->data, 0, FFS_DATA_SIZE);
        /* [CR_PUBKEY] */
        err = ChatResponse_serialize(pkt->data, FFS_DATA_SIZE, &length, CR_PUBKEY);
        if (err) goto cleanup;
        /* [(uint16) CHAT_PUBKEY_LEN] */
        err = uint16_serialize(pkt->data, FFS_DATA_SIZE, &length, CHAT_PUBKEY_LEN);
        if (err) goto cleanup;
        /* [CHAT_PUBKEY_LEN-byte ecc point] */
        err = uint8_serialize(pkt->data, FFS_DATA_SIZE, &length, ctx->key_pub[0]);
        if (err) goto cleanup;
        msel_memcpy(&pkt->data[length], &ctx->key_pub[ECC_POINT_LEN - (CHAT_PUBKEY_LEN - 1)], (CHAT_PUBKEY_LEN - 1));
        length += CHAT_PUBKEY_LEN - 1;
    }

    /* Update our status */
    ctx->state = CS_AWAITING_COMMANDS;

    /* Send the response */
    while (msel_svc(MSEL_SVC_SESSION_SEND, pkt) != MSEL_OK)
        msel_svc(MSEL_SVC_YIELD, NULL);

cleanup:
    return err;
}
Ejemplo n.º 9
0
static void run_test(int expected_ret,
	int manio_entries,
	int async_read_write_callback(struct async *as),
	void setup_asfds_callback(struct asfd *asfd, struct asfd *chfd,
		struct slist *slist))
{
	struct asfd *asfd;
	struct asfd *chfd;
	struct async *as;
	struct sdirs *sdirs;
	struct conf **confs;
	struct slist *slist=NULL;
	prng_init(0);
	base64_init();
	hexmap_init();
	setup(&as, &sdirs, &confs);
	asfd=asfd_mock_setup(&areads, &awrites);
	chfd=asfd_mock_setup(&creads, &cwrites);
	fail_unless((asfd->desc=strdup_w("a", __func__))!=NULL);
	fail_unless((chfd->desc=strdup_w("c", __func__))!=NULL);
	as->asfd_add(as, asfd);
	as->asfd_add(as, chfd);
	as->read_write=async_read_write_callback;

	if(manio_entries)
		slist=build_manifest(sdirs->phase1data,
			PROTO_2, manio_entries, 1 /*phase*/);
	setup_asfds_callback(asfd, chfd, slist);

	fail_unless(do_backup_phase2_server_protocol2(
		as,
		chfd,
		sdirs,
		0, // resume
		confs
	)==expected_ret);

	if(!expected_ret)
	{
		// FIX THIS: Should check for the presence and correctness of
		// changed and unchanged manios.
	}
	asfd_free(&asfd);
	asfd_free(&chfd);
	asfd_mock_teardown(&areads, &awrites);
	asfd_mock_teardown(&creads, &cwrites);
	slist_free(&slist);
	tear_down(&as, &sdirs, &confs);
}
Ejemplo n.º 10
0
int
__bro_openssl_rand_bytes(u_char *buf, int num)
{
  if (! buf || num <= 0)
    return FALSE;

  /* Make sure PRNG is initialized; has effect only once. */
  prng_init();

  if (RAND_bytes(buf, num) > 0)
    return TRUE;
  
  RAND_pseudo_bytes(buf, num);
  return TRUE;
}
Ejemplo n.º 11
0
int ssl_init(void)
{
    if (!prng_init()) {
	Debug((DEBUG_NOTICE, "PRNG seeded"));
    }
    if ((bootopt & BOOT_TTY) && (bootopt & BOOT_DEBUG))
	    (void)fprintf(stderr, "ssl_init(): SSL_load_error_strings()\n" );
    SSL_load_error_strings();
    if ((bootopt & BOOT_TTY) && (bootopt & BOOT_DEBUG))
	    (void)fprintf(stderr, "ssl_init(): OpenSSL_add_ssl_algorythms()\n");
    OpenSSL_add_ssl_algorithms();
    if ((bootopt & BOOT_TTY) && (bootopt & BOOT_DEBUG))
	    (void)fprintf(stderr, "ssl_init(): SSL_CTX_new()\n");
    ctx = SSL_CTX_new(SSLv23_server_method());
    if (!ctx) {
	Debug((DEBUG_ERROR, "CTX_new: %s", ERR_error_string(ERR_get_error(), NULL)));
	return 0;
    }
    if ((bootopt & BOOT_TTY) && (bootopt & BOOT_DEBUG))
	    (void)fprintf(stderr, "ssl_init(): SSL_CTX_use_certificate_file()\n");
    if (SSL_CTX_use_certificate_file(ctx,
		IRCD_CRT, SSL_FILETYPE_PEM) <= 0) {
	(void)disable_ssl(1);
	return 0;
    }
    if ((bootopt & BOOT_TTY) && (bootopt & BOOT_DEBUG))
	    (void)fprintf(stderr, "ssl_init(): SSL_CTX_use_PrivateKey_file()\n");
    if (SSL_CTX_use_PrivateKey_file(ctx,
		IRCD_KEY, SSL_FILETYPE_PEM) <= 0) {
	(void)disable_ssl(1);
	return 0;
    }
    if ((bootopt & BOOT_TTY) && (bootopt & BOOT_DEBUG))
	    (void)fprintf(stderr, "ssl_init(): SSL_CTX_check_private_key()\n");    
    if (!SSL_CTX_check_private_key(ctx)) {
	(void)disable_ssl(1);
	return 0;
    }
    return 1;
}
Ejemplo n.º 12
0
int ssl_configure(GLOBAL_OPTIONS *global) { /* configure global SSL settings */
#ifdef USE_FIPS
    if(FIPS_mode()!=global->option.fips) {
        RAND_set_rand_method(NULL); /* reset RAND methods */
        if(!FIPS_mode_set(global->option.fips)) {
            ERR_load_crypto_strings();
            sslerror("FIPS_mode_set");
            return 1;
        }
    }
    s_log(LOG_NOTICE, "FIPS mode %s",
        global->option.fips ? "enabled" : "disabled");
#endif /* USE_FIPS */
#ifndef OPENSSL_NO_COMP
    if(compression_init(global))
        return 1;
#endif /* OPENSSL_NO_COMP */
    if(prng_init(global))
        return 1;
    s_log(LOG_DEBUG, "PRNG seeded successfully");
    return 0; /* SUCCESS */
}
Ejemplo n.º 13
0
void chat_ecc_genkey(uint8_t *seed, uint8_t *prv, uint8_t *pub) {
    /* Generate the private key */
    uint8_t tmp[SHA256_OUTPUT_LEN];
    kdf_getkey(chat_master, sizeof(chat_master), chat_secret_data, SHA256_OUTPUT_LEN, seed, tmp);
    prng_ctx_t prng;
    prng_init(&prng, AES_128, tmp, ((uint64_t*)tmp)[2], ((uint64_t*)tmp)[3]);
    msel_memset(tmp, 0, SHA256_OUTPUT_LEN);

    for (int i = 0; i < ECC_SCALAR_LEN; i += AES_BLOCK_SIZE)
        prng_output(&prng, &prv[i]);
    for (int i = 0; i < ECC_SCALAR_LEN - CHAT_PRVKEY_LEN; i++)
        prv[i] = 0;

    /* Generate the public key*/
    msel_memcpy(pub, curve_base_point, ECC_POINT_LEN);
    ecc_ctx_t ecc_ctx;
    ecc_ctx.scalar = prv;
    ecc_ctx.point = pub;
    // msel_svc(MSEL_SVC_ECC, &ecc_ctx);
    for (int i = 0; i < ECC_POINT_LEN; i++)
        ecc_ctx.point[i] ^= ecc_ctx.scalar[i];

    msel_memset(&prng, 0, sizeof(prng));
}
Ejemplo n.º 14
0
/*
 * Called from the main OpenVPN process to enable the port
 * share proxy.
 */
struct port_share *
port_share_open (const char *host,
		 const int port,
		 const int max_initial_buf,
		 const char *journal_dir)
{
  pid_t pid;
  socket_descriptor_t fd[2];
  in_addr_t hostaddr;
  struct port_share *ps;

  ALLOC_OBJ_CLEAR (ps, struct port_share);
  ps->foreground_fd = -1;
  ps->background_pid = -1;

  /*
   * Get host's IP address
   */
  hostaddr = getaddr (GETADDR_RESOLVE|GETADDR_HOST_ORDER|GETADDR_FATAL, host, 0, NULL, NULL);

  /*
   * Make a socket for foreground and background processes
   * to communicate.
   */
  if (socketpair (PF_UNIX, SOCK_DGRAM, 0, fd) == -1)
    {
      msg (M_WARN, "PORT SHARE: socketpair call failed");
      goto error;
    }

  /*
   * Fork off background proxy process.
   */
  pid = fork ();

  if (pid)
    {
      int status;

      /*
       * Foreground Process
       */

      ps->background_pid = pid;

      /* close our copy of child's socket */
      openvpn_close_socket (fd[1]);

      /* don't let future subprocesses inherit child socket */
      set_cloexec (fd[0]);

      /* wait for background child process to initialize */
      status = recv_control (fd[0]);
      if (status == RESPONSE_INIT_SUCCEEDED)
	{
	  /* note that this will cause possible EAGAIN when writing to
	     control socket if proxy process is backlogged */
	  set_nonblock (fd[0]);

	  ps->foreground_fd = fd[0];
	  return ps;
	}
      else
	{
	  msg (M_ERR, "PORT SHARE: unexpected init recv_control status=%d", status);
	}
    }
  else
    {
      /*
       * Background Process
       */

      /* Ignore most signals (the parent will receive them) */
      set_signals ();

      /* Let msg know that we forked */
      msg_forked ();

#ifdef ENABLE_MANAGEMENT
      /* Don't interact with management interface */
      management = NULL;
#endif

      /* close all parent fds except our socket back to parent */
      close_fds_except (fd[1]);

      /* no blocking on control channel back to parent */
      set_nonblock (fd[1]);

      /* initialize prng */
      prng_init (NULL, 0);

      /* execute the event loop */
      port_share_proxy (hostaddr, port, fd[1], max_initial_buf, journal_dir);

      openvpn_close_socket (fd[1]);

      exit (0);
      return 0; /* NOTREACHED */
    }

 error:
  port_share_close (ps);
  return NULL;
}
Ejemplo n.º 15
0
int
__bro_openssl_init(void)
{
  static int deja_vu = FALSE;
  int use_ssl = FALSE;
  const char *our_cert, *our_key, *our_pass, *ca_cert;
  
  D_ENTER;

  if (deja_vu)
    D_RETURN_(TRUE);

  deja_vu = TRUE;

  /* I hope these should go before SSL_library_init() -- not even the
   * O'Reilly book is clear on that. :( --cpk
   */
  if (global_ctx)
    {
      if (global_ctx->id_func)
	CRYPTO_set_id_callback(global_ctx->id_func);
      if (global_ctx->lock_func)
	CRYPTO_set_locking_callback(global_ctx->lock_func);
      if (global_ctx->dl_create_func)
	CRYPTO_set_dynlock_create_callback(global_ctx->dl_create_func);
      if (global_ctx->dl_lock_func)
	CRYPTO_set_dynlock_lock_callback(global_ctx->dl_lock_func);
      if (global_ctx->dl_free_func)
	CRYPTO_set_dynlock_destroy_callback(global_ctx->dl_free_func);
    }
  
  SSL_library_init();
  prng_init();
  
#ifdef BRO_DEBUG
  D(("Loading OpenSSL error strings for debugging\n"));
  SSL_load_error_strings();
#endif

  if (__bro_conf_get_int("/broccoli/use_ssl", &use_ssl) && ! use_ssl)
    {
      D(("SSL disabled in configuration, not using SSL.\n"));
      D_RETURN_(TRUE);
    }

  our_cert = __bro_conf_get_str("/broccoli/host_cert");
  our_key = __bro_conf_get_str("/broccoli/host_key");
  if (our_key == NULL)
    {
    /* No private key configured; get it from the certificate file */
    our_key = our_cert;
    }

  if (our_cert == NULL)
    {
      if (use_ssl)
	{
	  D(("SSL requested but host certificate not given -- aborting.\n"));
	  D_RETURN_(FALSE);
	}
      else
	{
	  D(("use_ssl not used and host certificate not given -- not using SSL.\n"));
	  D_RETURN_(TRUE);
	}
    }

  if (our_key == NULL)
    {
      if (use_ssl)
	{
	  D(("SSL requested but host key not given -- aborting.\n"));
	  D_RETURN_(FALSE);
	}
      else
	{
	  D(("use_ssl not used and host key not given -- not using SSL.\n"));
	  D_RETURN_(TRUE);
	}
    }


  /* At this point we either haven't seen use_ssl but a host_cert, or
   * we have seen use_ssl and it is set to true. Either way, we attempt
   * to set up an SSL connection now and abort if this fails in any way.
   */

  if (! (ctx = SSL_CTX_new(SSLv3_method())))
    D_RETURN_(FALSE);
  
  /* We expect things to be stored in PEM format, which means that we
   * can store multiple entities in one file. In this case, our own
   * certificate is expected to be stored along with the private key
   * in the file pointed to by preference setting /broccoli/certificate.
   *
   * See page 121 in O'Reilly's OpenSSL book for details.
   */
  if (SSL_CTX_use_certificate_chain_file(ctx, our_cert) != 1)
    {
      D(("Error loading certificate from '%s'.\n", our_cert));
      goto error_return;
    }
  
  if ( (our_pass = __bro_conf_get_str("/broccoli/host_pass")))
    {
      D(("Host passphrase given in config file, not prompting for input.\n"));
      SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
      SSL_CTX_set_default_passwd_cb_userdata(ctx, (void *) our_pass);
    }
  
  if (SSL_CTX_use_PrivateKey_file(ctx, our_key, SSL_FILETYPE_PEM) != 1)
    {
      D(("SSL used but error loading private key from '%s' -- aborting.\n", our_key));
      goto error_return;
    }
  
  /* We should not need the passphrase, if existant, ever again.
   * Therefore we erase it from memory now.
   */
  if (our_pass)
    {
      our_pass = NULL;
      __bro_conf_forget_item("/broccoli/host_pass");
    }

  /* For validation purposes, our trusted CA's certificate will
   * be needed as well:
   */
  if (! (ca_cert = __bro_conf_get_str("/broccoli/ca_cert")))
    {
      D(("SSL used but CA certificate not given -- aborting."));
      goto error_return;
    }
  
  if (! SSL_CTX_load_verify_locations(ctx, ca_cert, 0))
    {
      D(("SSL used but CA certificate could not be loaded -- aborting\n"));
      goto error_return;
    }
  
  /* Check the consistency of the certificate vs. the private key */
  if (SSL_CTX_check_private_key(ctx) != 1)
    {
      D(("SSL used but private key does not match the certificate -- aborting\n"));
      goto error_return;
    }
  
  /* Only use real ciphers.
   */
  if (! SSL_CTX_set_cipher_list(ctx, "HIGH"))
    {
      D(("SSL used but can't set cipher list -- aborting\n"));
      goto error_return;
    }
  
  /* We require certificates from all communication peers, regardless of
   * whether we're the "server" or "client" (these concepts are blurred in our
   * case anyway). In order to be able to give better error feedback, we
   * add our own verification filter callback, "verify_cb".
   */
  SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
		     verify_cb);
  
  D(("SSL setup successful.\n"));
  D_RETURN_(TRUE);
  
 error_return:
  SSL_CTX_free(ctx);
  ctx = NULL;
  D_RETURN_(FALSE);
}
Ejemplo n.º 16
0
int run_haggle()
{
	srand(time(NULL));
#ifdef ENABLE_DEBUG_MANAGER
	DebugManager *db = NULL;
#endif
	ApplicationManager *am = NULL;
	DataManager *dm = NULL;
// SW: START: SendPriorityManager
	SendPriorityManager *spm = NULL;
// SW: END: SendPriorityManager
	NodeManager *nm = NULL;
	ProtocolManager *pm = NULL;
	ForwardingManager *fm = NULL;
	SecurityManager *sm = NULL;
	ConnectivityManager *cm = NULL;
	LossEstimateManager *lm = NULL;
	NetworkCodingManager* networkCodingManager = NULL;
	FragmentationManager* fragmentationManager = NULL;
	//JM
	ReplicationManager *replicationManager = NULL;
	BenchmarkManager *bm = NULL;
	ResourceManager *rm = NULL;
// SW: START: interest manager
    InterestManager *im = NULL;
// SW: END: interest manager

	ProtocolSocket *p = NULL;
#ifdef OS_WINDOWS_MOBILE

	// For testing we force the deletion of the data store
	//recreateDataStore = true;
#endif
	int retval = EXIT_FAILURE;

#if defined(OS_ANDROID)
	//mallopt(-1, -1); // MOS - avoid trimming
#elif defined(OS_LINUX)
        mallopt(M_TRIM_THRESHOLD, -1); // MOS - avoid trimming
#endif

	xmlInitParser(); // MOS - this need to be called here for thread-safe libxml use

#ifdef DEBUG
    Trace::trace.enableFileTrace();
#endif

	HAGGLE_LOG("\n\n****************** HAGGLE STARTUP *********************\n\n");

	if (!create_path(HAGGLE_DEFAULT_STORAGE_PATH)) {
                HAGGLE_ERR("Could not create Haggle storage path : %s\n", HAGGLE_DEFAULT_STORAGE_PATH);
                return -1;
        }
	
        retval = write_pid_file(getpid());

        if (retval != HAGGLE_PROCESS_NO_ERROR) {
                switch (retval) {
                        case HAGGLE_PROCESS_BAD_PID:
                                HAGGLE_ERR("Cannot read PID file %s.\n", PID_FILE.c_str());
                                break;
                        case HAGGLE_PROCESS_CANNOT_WRITE_PID:
                                HAGGLE_ERR("Cannot write PID file %s\n", PID_FILE.c_str());
                                break;
                        case HAGGLE_PROCESS_ALREADY_RUNNING: 
                                HAGGLE_ERR("PID file %s indicates that Haggle is already running.\n", PID_FILE.c_str());
                                break;
                        default:
                                HAGGLE_ERR("Unknown PID file error\n");

                }
                shouldCleanupPidFile = false;
                return -1;
        }
#if defined(OS_UNIX) && !defined(OS_ANDROID)
	setrawtty();
#endif
      
        /* Seed the random number generator */
	prng_init();

// SW: START CONFIG PATH (instead of hardcoded ~/.Haggle/config.xml),
    if (useMemoryDB) {
        kernel = new HaggleKernel(configFile, new MemoryDataStore(recreateDataStore));
    }
    else {
        kernel = new HaggleKernel(configFile, new SQLDataStore(recreateDataStore));
    }
// SW: END CONFIG PATH.

	if (!kernel || !kernel->init()) {
		fprintf(stderr, "Kernel initialization error!\n");
		return -1;
	}
	
	// Build a Haggle configuration
	am = new ApplicationManager(kernel);

	if (!am || !am->init()) {
		HAGGLE_ERR("Could not initialize application manager\n");
		goto finish;
	}

	dm = new DataManager(kernel, setCreateTimeOnBloomfilterUpdate);

	if (!dm || !dm->init()) {
		HAGGLE_ERR("Could not initialize data manager\n");
		goto finish;
	}

// SW: START: SendPriorityManager
    spm = new SendPriorityManager(kernel);
    if (!spm || !spm->init()) {
        HAGGLE_ERR("Could not initialize send priority manager\n");
        goto finish;
    }
// SW: END: SendPriorityManager

	nm = new NodeManager(kernel);

	if (!nm || !nm->init()) {
		HAGGLE_ERR("Could not initialize node manager\n");
		goto finish;
	}

	pm = new ProtocolManager(kernel);

	if (!pm || !pm->init()) {
		HAGGLE_ERR("Could not initialize protocol manager\n");
		goto finish;
	}

	fm = new ForwardingManager(kernel);

	if (!fm || !fm->init()) {
		HAGGLE_ERR("Could not initialize forwarding manager\n");
		goto finish;
	}

	sm = new SecurityManager(kernel, securityLevel);

	if (!sm || !sm->init()) {
		HAGGLE_ERR("Could not initialize security manager\n");
		goto finish;
	}
	fragmentationManager = new FragmentationManager(kernel);
	if(!fragmentationManager || !fragmentationManager->init()) {
	    HAGGLE_ERR("Could not initialize fragmentationManager\n");
	    goto finish;
	}

	networkCodingManager = new NetworkCodingManager(kernel);
	if(!networkCodingManager || !networkCodingManager->init()) {
	    HAGGLE_ERR("Could not initialize networkCodingManager \n");
	    goto finish;
	}

	//JM
	replicationManager = new ReplicationManager(kernel);
        if (!replicationManager || !replicationManager->init()) {
		HAGGLE_ERR("Could not initialize replication manager\n");
		goto finish;
    }
    
	lm = new LossEstimateManager(kernel);
	if(!lm || !lm->init()){
	    HAGGLE_ERR("Could not initialize LossEstimateManager \n");
	    goto finish;		
	}

#ifdef USE_UNIX_APPLICATION_SOCKET
	p = new ProtocolLOCAL(kernel->getStoragePath() + "/" + HAGGLE_LOCAL_SOCKET, pm);

	if (!p || !p->init()) {
		HAGGLE_ERR("Could not initialize LOCAL protocol\n");
		goto finish;
	}
	p->setFlag(PROT_FLAG_APPLICATION);
	p->registerWithManager();

#endif
	p = new ProtocolUDP("127.0.0.1", HAGGLE_SERVICE_DEFAULT_PORT, pm);
	/* Add ConnectivityManager last since it will start to
	* discover interfaces and generate events. At that
	* point the other managers should already be
	* running. */

	if (!p || !p->init()) {
		HAGGLE_ERR("Could not initialize UDP Application protocol\n");
		goto finish;
	}
	p->setFlag(PROT_FLAG_APPLICATION);
	p->registerWithManager();

// SW: start interest manager
    im = new InterestManager(kernel);

    if (!im || !im->init()) {
        HAGGLE_ERR("Could not initialize interest manager\n");
        goto finish;
    }
// SW: end interest manager

	/* MOS - disable resource mananager due 
	   high cpu utilization bug on Android

	rm = new ResourceManager(kernel);

	if (!rm || !rm->init()) {
		HAGGLE_ERR("Could not initialize resource manager\n");
		goto finish;
	}

	*/

	if (!isBenchmarking) {
		cm = new ConnectivityManager(kernel);

		if (!cm || !cm->init()) {
			HAGGLE_ERR("Could not initialize connectivity manager\n");
			goto finish;
		}

	} else {
		bm = new BenchmarkManager(kernel, Benchmark_DataObjects_Attr, Benchmark_Nodes_Attr, Benchmark_Attr_Num, Benchmark_DataObjects_Num, Benchmark_Test_Num);

		if (!bm || !bm->init()) {
			HAGGLE_ERR("Could not initialize benchmark manager\n");
			goto finish;
		}
	}
#if defined(ENABLE_DEBUG_MANAGER)
	// It seems as if there can be only one accept() per
	// thread... we need to make the DebugManager register
	// protocol or something with the ProtocolTCPServer
	// somehow
	db = new DebugManager(kernel, runAsInteractive);

	if (!db || !db->init()) {
		HAGGLE_ERR("Could not initialize debug manager\n");
		/* Treat as non critical error. */
	}
#endif

	HAGGLE_DBG("Starting Haggle...\n");

#ifdef OS_WINDOWS_MOBILE
	if (platform_type(current_platform()) == platform_windows_mobile_professional)
		tray_notification_add(g_hInstance, kernel);
#endif

	kernel->run();

	if(kernel->hasFatalError()) retval = EXIT_FAILURE;
	else retval = EXIT_SUCCESS;

	HAGGLE_DBG("Haggle finished...\n");

finish:
	if (bm)
		delete bm;
	if (lm)
		delete lm;

	if (fragmentationManager) {
	    delete fragmentationManager;
	    fragmentationManager = NULL;
	}
	if (networkCodingManager)
	    delete networkCodingManager;
	//JM
	if (replicationManager)
	  	delete replicationManager;
	if (cm)
		delete cm;
	if (sm)
		delete sm;
	if (fm)
		delete fm;
	if (pm)	
		delete pm;
	if (nm)
		delete nm;
	if (dm)
		delete dm;
// SW: START: SendPriorityManager
    if (spm)
        delete spm;
// SW: END: SendPriorityManager
	if (am)
		delete am;
// SW: start interest manager
    if (im)
        delete im;
// SW: end interest manager
#if defined(ENABLE_DEBUG_MANAGER)
	if (db)
		delete db;
#endif
	if (rm)
		delete rm;

#ifdef OS_WINDOWS_MOBILE
	tray_notification_remove();
#endif
	delete kernel;
	kernel = NULL;

	xmlCleanupParser(); // MOS

	return retval;
}
Ejemplo n.º 17
0
static void run_test(int expected_ret,
	enum protocol protocol,
	int manio_entries,
	int blocks_per_file,
	void setup_asfds_callback(struct asfd *asfd, struct slist *slist))
{
        struct async *as;
        struct asfd *asfd;
        struct sdirs *sdirs;
        struct conf **confs;
        struct slist *slist=NULL;
	char *dir_for_notify=NULL;
        prng_init(0);
        base64_init();
        hexmap_init();
        setup(protocol, &as, &sdirs, &confs);
	set_string(confs[OPT_BACKUP], "1");
	set_protocol(confs, protocol);
        asfd=asfd_mock_setup(&reads, &writes);
	as->asfd_add(as, asfd);
	as->read_write=async_rw_simple;
	as->read_quick=async_rw_simple;
	asfd->as=as;

	build_storage_dirs(sdirs, sd1, ARR_LEN(sd1));
	if(manio_entries)
	{
		struct sbuf *s;
		if(protocol==PROTO_2)
			slist=build_manifest_with_data_files(sdirs->cmanifest,
				sdirs->data, manio_entries, blocks_per_file);
		else
		{
			slist=build_manifest(sdirs->cmanifest,
				protocol, manio_entries, 0 /*phase*/);
			for(s=slist->head; s; s=s->next)
			{
				char path[256];
				if(!sbuf_is_filedata(s))
					continue;
				snprintf(path, sizeof(path), "%s/%s%s",
					sdirs->currentdata,
					TREE_DIR, s->path.buf);
				build_file(path, "data");
			}
		}
	}
	setup_asfds_callback(asfd, slist);

	fail_unless(do_restore_server(
		asfd,
		sdirs,
		ACTION_RESTORE,
		0, // srestore
		&dir_for_notify,
		confs
	)==expected_ret);

	if(!expected_ret)
	{
		// FIX THIS: Should check for the presence and correctness of
		// changed and unchanged manios.
	}
	slist_free(&slist);
	free_w(&dir_for_notify);
	tear_down(&as, &asfd, &sdirs, &confs);
}
Ejemplo n.º 18
0
/* void */
int
ipsec_klips_init(void)
{
	int error = 0;
	unsigned char seed[256];
#ifdef CONFIG_KLIPS_ENC_3DES
	extern int des_check_key;

	/* turn off checking of keys */
	des_check_key=0;
#endif /* CONFIG_KLIPS_ENC_3DES */

	KLIPS_PRINT(1, "klips_info:ipsec_init: "
		    "KLIPS startup, Openswan KLIPS IPsec stack version: %s\n",
		    ipsec_version_code());

	error |= ipsec_proc_init();

#ifdef SPINLOCK
	ipsec_sadb.sadb_lock = SPIN_LOCK_UNLOCKED;
#else /* SPINLOCK */
	ipsec_sadb.sadb_lock = 0;
#endif /* SPINLOCK */

#ifndef SPINLOCK
	tdb_lock.lock = 0;
	eroute_lock.lock = 0;
#endif /* !SPINLOCK */

	error |= ipsec_sadb_init();
	error |= ipsec_radijinit();

	error |= pfkey_init();

	error |= register_netdevice_notifier(&ipsec_dev_notifier);

#ifdef CONFIG_KLIPS_ESP
	openswan_inet_add_protocol(&esp_protocol, IPPROTO_ESP);
#endif /* CONFIG_KLIPS_ESP */

#ifdef CONFIG_KLIPS_AH
	openswan_inet_add_protocol(&ah_protocol, IPPROTO_AH);
#endif /* CONFIG_KLIPS_AH */

/* we never actually link IPCOMP to the stack */
#ifdef IPCOMP_USED_ALONE
#ifdef CONFIG_KLIPS_IPCOMP
 	openswan_inet_add_protocol(&comp_protocol, IPPROTO_COMP);
#endif /* CONFIG_KLIPS_IPCOMP */
#endif

	error |= ipsec_tunnel_init_devices();

#if defined(NET_26) && defined(CONFIG_IPSEC_NAT_TRAVERSAL)
	/* register our ESP-UDP handler */
	if(udp4_register_esp_rcvencap(klips26_rcv_encap
				      , &klips_old_encap)!=0) {
	   printk(KERN_ERR "KLIPS: can not register klips_rcv_encap function\n");
	}
#endif	


#ifdef CONFIG_SYSCTL
        error |= ipsec_sysctl_register();
#endif                                                                          

#ifdef CONFIG_KLIPS_ALG
	ipsec_alg_init();
#endif

#ifdef CONFIG_KLIPS_OCF
	ipsec_ocf_init();
#endif

	get_random_bytes((void *)seed, sizeof(seed));
	prng_init(&ipsec_prng, seed, sizeof(seed));

	atomic_set(&ipsec_irs_cnt, 0);
	atomic_set(&ipsec_ixs_cnt, 0);

	ipsec_irs_cache = kmem_cache_create("ipsec_irs",
			sizeof(struct ipsec_rcv_state), 0, SLAB_HWCACHE_ALIGN, NULL, NULL);
	if (!ipsec_irs_cache) {
		printk("Failed to get IRS cache\n");
		error |= 1;
	}
	ipsec_ixs_cache = kmem_cache_create("ipsec_ixs",
			sizeof(struct ipsec_xmit_state), 0, SLAB_HWCACHE_ALIGN, NULL, NULL);
	if (!ipsec_ixs_cache) {
		printk("Failed to get IXS cache\n");
		error |= 1;
	}
	return error;
}	
Ejemplo n.º 19
0
int main(char *argv[], int argc)
{
	int ret;
	int error;
	struct sockaddr_in saddr, daddr;
	struct sockaddr_in saddr2, daddr2;
	void *rcv02_talloc = NULL;

	struct ipsec_sa *sa, *sa1;
	char auth1[] = { 0x87, 0x65, 0x87, 0x65,
			 0x87, 0x65, 0x87, 0x65,
			 0x87, 0x65, 0x87, 0x65,
			 0x87, 0x65, 0x87, 0x65 };
	char enc[] = { 0x40, 0x43, 0x43, 0x45, 0x45, 0x46, 0x46, 0x49,
		       0x49, 0x4a, 0x4a, 0x4c, 0x4c, 0x4f, 0x4f, 0x51,
		       0x51, 0x52, 0x52, 0x54, 0x54, 0x57, 0x57, 0x58 };

	debug_xform = 1;
	init_kmalloc();
	debug_rcv = 0xffffffff;
	sysctl_ipsec_debug_verbose = 1;
	prng_init(&ipsec_prng, seed, sizeof(seed));
	ipsec_sadb_init();
	ipsec_alg_init();

	{
		sa1 = ipsec_sa_alloc(&error);
		assert(error == 0);

		ipsec_sa_intern(sa1);

		sa1->ips_said.spi = htonl(0x12345678);
		sa1->ips_said.proto = IPPROTO_IPIP;
		sa1->ips_said.dst.u.v4.sin_addr.s_addr = htonl(0xc001022D);

		sa1->ips_seq = 1;
		sa1->ips_pid = 10;

		sa1->ips_state = SADB_SASTATE_MATURE;
		daddr2.sin_addr.s_addr = htonl(0xc001022D);
		saddr2.sin_addr.s_addr = htonl(0xc0010217);
		sa1->ips_addr_s = (struct sockaddr *)&saddr2;
		sa1->ips_addr_d = (struct sockaddr *)&daddr2;
	}

	{
		sa = ipsec_sa_alloc(&error);
		assert(error == 0);

		ipsec_sa_intern(sa);

		sa->ips_said.spi = htonl(0x12345678);
		sa->ips_said.proto = IPPROTO_ESP;
		sa->ips_said.dst.u.v4.sin_addr.s_addr = htonl(0xc001022D);

		sa->ips_seq = 1;
		sa->ips_pid = 10;
		sa->ips_inext = sa1;

		{
			/* make a copy so that ipsec_sa_init() can zero it out */
			char *auth = talloc_size(rcv02_talloc, AHMD596_KLEN);

			memcpy(auth, auth1, AHMD596_KLEN);
			sa->ips_authalg = AH_MD5;
			sa->ips_key_bits_a = AHMD596_KLEN * 8;
			sa->ips_key_a = auth;
		}

		sa->ips_natt_type = ESPINUDP_WITH_NON_ESP;
		sa->ips_encalg = ESP_3DES;
		sa->ips_key_bits_e = 192;
		sa->ips_iv_bits = 128;
		sa->ips_key_e_size = 0;
		sa->ips_key_e = talloc_memdup(rcv02_talloc, enc,
					      sa->ips_key_bits_e);

		sa->ips_state = SADB_SASTATE_MATURE;
		daddr.sin_addr.s_addr = htonl(0xc001022D);
		saddr.sin_addr.s_addr = htonl(0xc0010217);
		sa->ips_addr_s = (struct sockaddr *)&saddr;
		sa->ips_addr_d = (struct sockaddr *)&daddr;

		ipsec_sa_init(sa);
		ipsec_sa_add(sa);
		//ipsec_sa_put(sa);
	}

	{
		int iphlen, len;
		struct iphdr *iph;
		struct sk_buff *skb = skbFromArray(packet1, packet1_len);
		skb_ethernet_ip_setup(skb);

		/* now simulate action of udp_encap_rcv */

		len = sizeof(struct udphdr);

		iph = skb->nh.iph;
		iphlen = iph->ihl << 2;
		iph->tot_len = htons(ntohs(iph->tot_len) - len);
		if (skb->len < iphlen + len) {
			/* packet is too small!?! */
			return 0;
		}

		/* pull the data buffer up to the ESP header and set the
		 * transport header to point to ESP.  Keep UDP on the stack
		 * for later.
		 */
		skb->h.raw = skb_pull(skb, len);

		/* modify the protocol (it's ESP!) */
		iph->protocol = IPPROTO_ESP;

		printf("SA natt: %d\n", sa->ips_natt_type);
		ret = klips26_rcv_encap(skb, UDP_ENCAP_ESPINUDP);
	}

	return 0;
}
Ejemplo n.º 20
0
int main(char *argv[], int argc)
{
  int ret;
  int error;
  struct sockaddr_in saddr,daddr;
  struct sockaddr_in saddr2,daddr2;
  void *rcv01_talloc = NULL;

  struct ipsec_sa *sa, *sa1;
  char auth1[]={0x87, 0x65, 0x87, 0x65,
	       0x87, 0x65, 0x87, 0x65,
	       0x87, 0x65, 0x87, 0x65,
	       0x87, 0x65, 0x87, 0x65};
  char enc[] ={0x40, 0x43, 0x43, 0x45, 0x45, 0x46, 0x46, 0x49,
	       0x49, 0x4a, 0x4a, 0x4c, 0x4c, 0x4f, 0x4f, 0x51,
	       0x51, 0x52, 0x52, 0x54, 0x54, 0x57, 0x57, 0x58};

  debug_xform = 1;
  init_kmalloc();
  debug_rcv=0xffffffff;
  sysctl_ipsec_debug_verbose = 1;
  prng_init(&ipsec_prng, seed, sizeof(seed));
  ipsec_sadb_init();
  ipsec_alg_init();

  {
    sa1 = ipsec_sa_alloc(&error);
    assert(error == 0);

    ipsec_sa_intern(sa1);

    sa1->ips_said.spi = htonl(0x12345678);
    sa1->ips_said.proto = IPPROTO_IPIP;
    sa1->ips_said.dst.u.v4.sin_addr.s_addr = htonl(0xc001022D);

    sa1->ips_seq = 1;
    sa1->ips_pid = 10;
    
    sa1->ips_state = SADB_SASTATE_MATURE;
    daddr2.sin_addr.s_addr = htonl(0xc001022D);
    saddr2.sin_addr.s_addr = htonl(0xc0010217);
    sa1->ips_addr_s = (struct sockaddr *)&saddr2;
    sa1->ips_addr_d = (struct sockaddr *)&daddr2;
  }
    
  {
    sa = ipsec_sa_alloc(&error);

    ipsec_sa_intern(sa);

    assert(error == 0);
    sa->ips_said.spi = htonl(0x12345678);
    sa->ips_said.proto = IPPROTO_ESP;
    sa->ips_said.dst.u.v4.sin_addr.s_addr = htonl(0xc001022D);

    sa->ips_seq = 1;
    sa->ips_pid = 10;
    sa->ips_inext = sa1;

    {
      /* make a copy so that ipsec_sa_init() can zero it out */
      char *auth = talloc_size(rcv01_talloc, AHMD596_KLEN);

      memcpy(auth, auth1, AHMD596_KLEN);
      sa->ips_authalg = AH_MD5;
      sa->ips_key_bits_a = AHMD596_KLEN * 8;
      sa->ips_key_a = auth;
    }

    sa->ips_encalg = ESP_3DES;
    sa->ips_key_bits_e = 192;
    sa->ips_iv_bits = 128;
    sa->ips_key_e_size = 0;
    sa->ips_key_e = talloc_memdup(rcv01_talloc, enc, sa->ips_key_bits_e);

    sa->ips_state = SADB_SASTATE_MATURE;
    daddr.sin_addr.s_addr = htonl(0xc001022D);
    saddr.sin_addr.s_addr = htonl(0xc0010217);
    sa->ips_addr_s = (struct sockaddr *)&saddr;
    sa->ips_addr_d = (struct sockaddr *)&daddr;

    ipsec_sa_add(sa);
    assert(ipsec_sa_init(sa) == 0);
    //ipsec_sa_put(sa);
  }
    
  {
    struct sk_buff *skb = skbFromArray(packet1, packet1_len);
    skb_ethernet_ip_setup(skb);

    ret = ipsec_rcv(skb);
    assert(netif_rx_count == 1);
  }
  
  ipsec_sadb_cleanup(0);  /* 0 = all protocols */

  exit(0);
}
Ejemplo n.º 21
0
/* void */
int
ipsec_init(void)
{
	int error = 0;
	unsigned char seed[256];
#ifdef CONFIG_IPSEC_ENC_3DES
	extern int des_check_key;

	/* turn off checking of keys */
	des_check_key=0;
#endif /* CONFIG_IPSEC_ENC_3DES */

	KLIPS_PRINT(1, "klips_info:ipsec_init: "
		    "KLIPS startup, Openswan KLIPS IPsec stack version: %s\n",
		    ipsec_version_code());

	error |= ipsec_proc_init();

#ifdef SPINLOCK
	ipsec_sadb.sadb_lock = SPIN_LOCK_UNLOCKED;
#else /* SPINLOCK */
	ipsec_sadb.sadb_lock = 0;
#endif /* SPINLOCK */

#ifndef SPINLOCK
	tdb_lock.lock = 0;
	eroute_lock.lock = 0;
#endif /* !SPINLOCK */

	error |= ipsec_sadb_init();
	error |= ipsec_radijinit();

	error |= pfkey_init();

	error |= register_netdevice_notifier(&ipsec_dev_notifier);

#ifdef CONFIG_IPSEC_ESP
	openswan_inet_add_protocol(&esp_protocol, IPPROTO_ESP);
#endif /* CONFIG_IPSEC_ESP */

#ifdef CONFIG_IPSEC_AH
	openswan_inet_add_protocol(&ah_protocol, IPPROTO_AH);
#endif /* CONFIG_IPSEC_AH */

/* we never actually link IPCOMP to the stack */
#ifdef IPCOMP_USED_ALONE
#ifdef CONFIG_IPSEC_IPCOMP
 	openswan_inet_add_protocol(&comp_protocol, IPPROTO_COMP);
#endif /* CONFIG_IPSEC_IPCOMP */
#endif

	error |= ipsec_tunnel_init_devices();


#ifdef CONFIG_SYSCTL
        error |= ipsec_sysctl_register();
#endif                                                                          

#ifdef CONFIG_IPSEC_ALG
	ipsec_alg_init();
#endif

	get_random_bytes((void *)seed, sizeof(seed));
	prng_init(&ipsec_prng, seed, sizeof(seed));

	return error;
}	
Ejemplo n.º 22
0
/* void */
int
ipsec_klips_init(void)
{
	int error = 0;
	unsigned char seed[256];
#ifdef CONFIG_KLIPS_ENC_3DES
	extern int des_check_key;

	/* turn off checking of keys */
	des_check_key=0;
#endif /* CONFIG_KLIPS_ENC_3DES */

	KLIPS_PRINT(1, "klips_info:ipsec_init: "
		    "KLIPS startup, Openswan KLIPS IPsec stack version: %s\n",
		    ipsec_version_code());

        error = ipsec_xmit_state_cache_init ();
        if (error)
                goto error_xmit_state_cache;

        error = ipsec_rcv_state_cache_init ();
        if (error)
                goto error_rcv_state_cache;

	error |= ipsec_proc_init();
        if (error)
                goto error_proc_init;

#ifdef SPINLOCK
	ipsec_sadb.sadb_lock = SPIN_LOCK_UNLOCKED;
#else /* SPINLOCK */
	ipsec_sadb.sadb_lock = 0;
#endif /* SPINLOCK */

#ifndef SPINLOCK
	tdb_lock.lock = 0;
	eroute_lock.lock = 0;
#endif /* !SPINLOCK */

	error |= ipsec_sadb_init();
        if (error)
                goto error_sadb_init;

	error |= ipsec_radijinit();
        if (error)
                goto error_radijinit;

	error |= pfkey_init();
        if (error)
                goto error_pfkey_init;

	error |= register_netdevice_notifier(&ipsec_dev_notifier);
        if (error)
                goto error_netdev_notifier;

#ifdef CONFIG_XFRM_ALTERNATE_STACK
        error = xfrm_register_alternate_rcv (ipsec_rcv);
        if (error)
                goto error_xfrm_register;

#else // CONFIG_XFRM_ALTERNATE_STACK

#ifdef CONFIG_KLIPS_ESP
	error |= openswan_inet_add_protocol(&esp_protocol, IPPROTO_ESP,"ESP");
	if (error)
		goto error_openswan_inet_add_protocol_esp;

#endif /* CONFIG_KLIPS_ESP */

#ifdef CONFIG_KLIPS_AH
	error |= openswan_inet_add_protocol(&ah_protocol, IPPROTO_AH,"AH");
	if (error)
		goto error_openswan_inet_add_protocol_ah;
#endif /* CONFIG_KLIPS_AH */

/* we never actually link IPCOMP to the stack */
#ifdef IPCOMP_USED_ALONE
#ifdef CONFIG_KLIPS_IPCOMP
 	error |= openswan_inet_add_protocol(&comp_protocol, IPPROTO_COMP,"IPCOMP");
	if (error)
		goto error_openswan_inet_add_protocol_comp;
#endif /* CONFIG_KLIPS_IPCOMP */
#endif

#endif // CONFIG_XFRM_ALTERNATE_STACK

	error |= ipsec_tunnel_init_devices();
        if (error)
                goto error_tunnel_init_devices;

	error |= ipsec_mast_init_devices();

#if defined(NET_26) && defined(CONFIG_IPSEC_NAT_TRAVERSAL)
	/* register our ESP-UDP handler */
	if(udp4_register_esp_rcvencap(klips26_rcv_encap
				      , &klips_old_encap)!=0) {
	   printk(KERN_ERR "KLIPS: can not register klips_rcv_encap function\n");
	}
#endif	

#ifdef CONFIG_SYSCTL
        error |= ipsec_sysctl_register();
        if (error)
                goto error_sysctl_register;
#endif                                                                          

#ifdef CONFIG_KLIPS_ALG
	ipsec_alg_init();
#endif

#ifdef CONFIG_KLIPS_OCF
	ipsec_ocf_init();
#endif

	get_random_bytes((void *)seed, sizeof(seed));
	prng_init(&ipsec_prng, seed, sizeof(seed));
	return error;

        // undo ipsec_sysctl_register
error_sysctl_register:
	ipsec_tunnel_cleanup_devices();
error_tunnel_init_devices:
#ifdef CONFIG_XFRM_ALTERNATE_STACK
        xfrm_deregister_alternate_rcv(ipsec_rcv);
error_xfrm_register:
#else // CONFIG_XFRM_ALTERNATE_STACK
#ifdef IPCOMP_USED_ALONE
#ifdef CONFIG_KLIPS_IPCOMP
error_openswan_inet_add_protocol_comp:
	openswan_inet_del_protocol(&comp_protocol, IPPROTO_COMP);
#endif /* CONFIG_KLIPS_IPCOMP */
#endif
#ifdef CONFIG_KLIPS_AH
error_openswan_inet_add_protocol_ah:
	openswan_inet_del_protocol(&ah_protocol, IPPROTO_AH);
#endif
error_openswan_inet_add_protocol_esp:
	openswan_inet_del_protocol(&esp_protocol, IPPROTO_ESP);
#endif
	unregister_netdevice_notifier(&ipsec_dev_notifier);
error_netdev_notifier:
	pfkey_cleanup();
error_pfkey_init:
	ipsec_radijcleanup();
error_radijinit:
	ipsec_sadb_cleanup(0);
	ipsec_sadb_free();
error_sadb_init:
error_proc_init:
        // ipsec_proc_init() does not cleanup after itself, so we have to do it here
        // TODO: ipsec_proc_init() should roll back what it chaned on failure
	ipsec_proc_cleanup();
        ipsec_rcv_state_cache_cleanup ();
error_rcv_state_cache:
        ipsec_xmit_state_cache_cleanup ();
error_xmit_state_cache:
        return error;
}	
Ejemplo n.º 23
0
int main(char *argv[], int argc)
{
  int error;
  struct sockaddr_in saddr,daddr;
  struct sockaddr_in saddr2,daddr2;

  void *main_talloc = NULL;
  struct ipsec_sa *sa, *sa1;
  char auth1[]={0x87, 0x65, 0x87, 0x65,
	       0x87, 0x65, 0x87, 0x65,
	       0x87, 0x65, 0x87, 0x65,
	       0x87, 0x65, 0x87, 0x65};
  char enc[] ={0x40, 0x43, 0x43, 0x45, 0x45, 0x46, 0x46, 0x49,
	       0x49, 0x4a, 0x4a, 0x4c, 0x4c, 0x4f, 0x4f, 0x51,
	       0x51, 0x52, 0x52, 0x54, 0x54, 0x57, 0x57, 0x58};

  debug_xform = 1;
  init_kmalloc();
  debug_tunnel=0xffffffff;
  debug_xmit=0xffffffff;
  sysctl_ipsec_debug_verbose = 1;
  prng_init(&ipsec_prng, seed, sizeof(seed));
  ipsec_sadb_init();
  ipsec_alg_init();

  {
    sa1 = ipsec_sa_alloc(&error);
    assert(error == 0);

    ipsec_sa_intern(sa1);

    sa1->ips_seq = 1;
    sa1->ips_pid = 10;
    
    sa1->ips_said.spi = htonl(0x12345678);
    sa1->ips_said.proto = IPPROTO_IPIP;
    sa1->ips_said.dst.u.v4.sin_addr.s_addr = htonl(0xc001022D);

    sa1->ips_state = SADB_SASTATE_MATURE;
    daddr2.sin_addr.s_addr = htonl(0xc001022D);
    saddr2.sin_addr.s_addr = htonl(0xc0010217);
    sa1->ips_addr_s = (struct sockaddr *)&saddr2;
    sa1->ips_addr_d = (struct sockaddr *)&daddr2;
  }
    
  {
    sa = ipsec_sa_alloc(&error);
    assert(error == 0);

    ipsec_sa_intern(sa);

    sa->ips_said.spi = htonl(0x12345678);
    sa->ips_said.proto = IPPROTO_ESP;
    sa->ips_said.dst.u.v4.sin_addr.s_addr = htonl(0xc001022D);
    sa->ips_said.dst.u.v4.sin_family      = AF_INET;

    sa->ips_seq = 1;
    sa->ips_pid = 10;
    sa->ips_inext = sa1;

    {
      /* make a copy so that ipsec_sa_init() can zero it out */
      char *auth = talloc_size(main_talloc, AHMD596_KLEN);

      memcpy(auth, auth1, AHMD596_KLEN);
      sa->ips_authalg = AH_MD5;
      sa->ips_key_bits_a = AHMD596_KLEN * 8;
      sa->ips_key_a = auth;
    }

    sa->ips_encalg = ESP_3DES;
    sa->ips_key_bits_e = 192;
    sa->ips_iv_bits = 128;
    sa->ips_key_e_size = 0;
    
    sa->ips_key_e = talloc_memdup(main_talloc, enc, sa->ips_key_bits_e);
    sa->ips_state = SADB_SASTATE_MATURE;
    daddr.sin_addr.s_addr = htonl(0xc001022D);
    saddr.sin_addr.s_addr = htonl(0xc0010217);
    sa->ips_addr_s = (struct sockaddr *)&saddr;
    sa->ips_addr_d = (struct sockaddr *)&daddr;

    ipsec_sa_add(sa);
    assert(ipsec_sa_init(sa) == 0);
    ipsec_sa_put(sa);
  }
    
  {
    struct ipsec_xmit_state ixs_mem;
    struct ipsec_xmit_state *ixs = &ixs_mem;
    enum ipsec_xmit_value stat;
    struct net_device_stats stats;
    int iphlen;

    struct sk_buff *skb = skbFromArray(packet2, packet2_len);

    skb->nh.raw = skb_pull(skb, skb->mac_len);
    iphlen = (skb->nh.iph->ihl<<2);

    /* do not use skb_pull, since data should stay at IP header */
    skb->h.raw = skb->nh.raw + iphlen;

    memset((caddr_t)ixs, 0, sizeof(*ixs));
    memset(&stats, 0, sizeof(stats));
    ixs->stats = &stats;
    ixs->oskb = NULL;
    ixs->saved_header = NULL;	/* saved copy of the hard header */
    ixs->route = NULL;
    memset((caddr_t)&(ixs->ips), 0, sizeof(ixs->ips));
    ixs->dev = NULL;
    ixs->skb = skb;
    ixs->physmtu = 1500;
    ixs->cur_mtu = 1500;
    ixs->outgoing_said.spi   = htonl(0x12345678);
    ixs->outgoing_said.proto = IPPROTO_ESP;
    ixs->outgoing_said.dst.u.v4.sin_family = AF_INET;
    ixs->outgoing_said.dst.u.v4.sin_addr.s_addr = htonl(0xc001022D);
    
    stat = ipsec_xmit_sanity_check_skb(ixs);
    assert(stat == IPSEC_XMIT_OK);

#if 0    
    stat = ipsec_tunnel_strip_hard_header(ixs);
    assert(stat == IPSEC_XMIT_OK);
    
    stat = ipsec_tunnel_SAlookup(ixs);
    assert(stat == IPSEC_XMIT_OK);
#endif
    
    stat = ipsec_xmit_encap_bundle(ixs);
    assert(stat == IPSEC_XMIT_OK);

#if 0
    stat = ipsec_tunnel_restore_hard_header(ixs);
#endif

    ipsec_print_ip(ixs->iph);
  }
  
  return 0;
}
Ejemplo n.º 24
0
int run_haggle()
{
#ifdef ENABLE_DEBUG_MANAGER
	DebugManager *db = NULL;
#endif
	ApplicationManager *am = NULL;
	DataManager *dm = NULL;
	NodeManager *nm = NULL;
	ProtocolManager *pm = NULL;
	ForwardingManager *fm = NULL;
	SecurityManager *sm = NULL;
	ConnectivityManager *cm = NULL;
#ifdef BENCHMARK
	BenchmarkManager *bm = NULL;
	//recreateDataStore = true;
#endif
	ResourceManager *rm = NULL;
	ProtocolSocket *p = NULL;
#ifdef OS_WINDOWS_MOBILE

	// For testing we force the deletion of the data store
	//recreateDataStore = true;
#endif
	int retval = EXIT_FAILURE;
	  
	if (!create_path(HAGGLE_DEFAULT_STORAGE_PATH)) {
                HAGGLE_ERR("Could not create Haggle storage path : %s\n", HAGGLE_DEFAULT_STORAGE_PATH);
                return -1;
        }
	
        retval = write_pid_file(getpid());

        if (retval != HAGGLE_PROCESS_NO_ERROR) {
                switch (retval) {
                        case HAGGLE_PROCESS_BAD_PID:
                                HAGGLE_ERR("Cannot read PID file %s.\n", PID_FILE.c_str());
                                break;
                        case HAGGLE_PROCESS_CANNOT_WRITE_PID:
                                HAGGLE_ERR("Cannot write PID file %s\n", PID_FILE.c_str());
                                break;
                        case HAGGLE_PROCESS_ALREADY_RUNNING: 
                                HAGGLE_ERR("PID file %s indicates that Haggle is already running.\n", PID_FILE.c_str());
                                break;
                        default:
                                HAGGLE_ERR("Unknown PID file error\n");

                }
                shouldCleanupPidFile = false;
                return -1;
        }
#if defined(OS_UNIX) && !defined(OS_ANDROID)
	setrawtty();
#endif
      
        /* Seed the random number generator */
	prng_init();

        kernel = new HaggleKernel(new SQLDataStore(recreateDataStore));

	if (!kernel || !kernel->init()) {
		fprintf(stderr, "Kernel initialization error!\n");
		return -1;
	}
	
	// Build a Haggle configuration
	am = new ApplicationManager(kernel);

	if (!am || !am->init()) {
		HAGGLE_ERR("Could not initialize application manager\n");
		goto finish;
	}

	dm = new DataManager(kernel, setCreateTimeOnBloomfilterUpdate);

	if (!dm || !dm->init()) {
		HAGGLE_ERR("Could not initialize data manager\n");
		goto finish;
	}

	nm = new NodeManager(kernel);

	if (!nm || !nm->init()) {
		HAGGLE_ERR("Could not initialize node manager\n");
		goto finish;
	}

	pm = new ProtocolManager(kernel);

	if (!pm || !pm->init()) {
		HAGGLE_ERR("Could not initialize protocol manager\n");
		goto finish;
	}

	fm = new ForwardingManager(kernel);

	if (!fm || !fm->init()) {
		HAGGLE_ERR("Could not initialize forwarding manager\n");
		goto finish;
	}

	sm = new SecurityManager(kernel, securityLevel);

	if (!sm || !sm->init()) {
		HAGGLE_ERR("Could not initialize security manager\n");
		goto finish;
	}

#ifdef USE_UNIX_APPLICATION_SOCKET
	p = new ProtocolLOCAL(kernel->getStoragePath() + "/" + HAGGLE_LOCAL_SOCKET, pm);
	
	if (!p || !p->init()) {
		HAGGLE_ERR("Could not initialize LOCAL protocol\n");
		goto finish;
	}
	p->setFlag(PROT_FLAG_APPLICATION);
	p->registerWithManager();

#endif
	p = new ProtocolUDP("127.0.0.1", HAGGLE_SERVICE_DEFAULT_PORT, pm);
	/* Add ConnectivityManager last since it will start to
	* discover interfaces and generate events. At that
	* point the other managers should already be
	* running. */

	if (!p || !p->init()) {
		HAGGLE_ERR("Could not initialize UDP Application protocol\n");
		goto finish;
	}
	p->setFlag(PROT_FLAG_APPLICATION);
	p->registerWithManager();

	rm = new ResourceManager(kernel);

	if (!rm || !rm->init()) {
		HAGGLE_ERR("Could not initialize resource manager\n");
		goto finish;
	}
#ifdef BENCHMARK
	if (!isBenchmarking) {
#endif
		cm = new ConnectivityManager(kernel);

		if (!cm || !cm->init()) {
			HAGGLE_ERR("Could not initialize connectivity manager\n");
			goto finish;
		}

#ifdef BENCHMARK
	} else {
		bm = new BenchmarkManager(kernel, Benchmark_DataObjects_Attr, Benchmark_Nodes_Attr, Benchmark_Attr_Num, Benchmark_DataObjects_Num, Benchmark_Test_Num);

		if (!bm || !bm->init()) {
			HAGGLE_ERR("Could not initialize benchmark manager\n");
			goto finish;
		}
	}
#endif
#if defined(ENABLE_DEBUG_MANAGER)
	// It seems as if there can be only one accept() per
	// thread... we need to make the DebugManager register
	// protocol or something with the ProtocolTCPServer
	// somehow
	db = new DebugManager(kernel, runAsInteractive);

	if (!db || !db->init()) {
		HAGGLE_ERR("Could not initialize debug manager\n");
		/* Treat as non critical error. */
	}
#endif

	HAGGLE_DBG("Starting Haggle...\n");

#ifdef OS_WINDOWS_MOBILE
	if (platform_type(current_platform()) == platform_windows_mobile_professional)
		tray_notification_add(g_hInstance, kernel);
#endif

	kernel->run();
	retval = EXIT_SUCCESS;

	HAGGLE_DBG("Haggle finished...\n");

finish:
#ifdef BENCHMARK
	if (bm)
		delete bm;
#endif
	if (cm)
		delete cm;
	if (sm)
		delete sm;
	if (fm)
		delete fm;
	if (pm)	
		delete pm;
	if (nm)
		delete nm;
	if (dm)
		delete dm;
	if (am)
		delete am;
#if defined(ENABLE_DEBUG_MANAGER)
	if (db)
		delete db;
#endif
	if (rm)
		delete rm;

#ifdef OS_WINDOWS_MOBILE
	tray_notification_remove();
#endif
	delete kernel;
	kernel = NULL;

	return retval;
}