void
test_main (void) 
{
  int fd_a, fd_b;
  size_t ofs_a = 0, ofs_b = 0;

  random_init (0);
  random_bytes (buf_a, sizeof buf_a);
  random_bytes (buf_b, sizeof buf_b);

  CHECK (create ("a", 0), "create \"a\"");
  CHECK (create ("b", 0), "create \"b\"");

  CHECK ((fd_a = open ("a")) > 1, "open \"a\"");
  CHECK ((fd_b = open ("b")) > 1, "open \"b\"");

  msg ("write \"a\" and \"b\" alternately");
  while (ofs_a < FILE_SIZE || ofs_b < FILE_SIZE) 
    {
      write_some_bytes ("a", fd_a, buf_a, &ofs_a);
      write_some_bytes ("b", fd_b, buf_b, &ofs_b);
    }

  msg ("close \"a\"");
  close (fd_a);

  msg ("close \"b\"");
  close (fd_b);

  check_file ("a", buf_a, FILE_SIZE);
  check_file ("b", buf_b, FILE_SIZE);
}
Example #2
0
void init_key() {
  unsigned char binkey[64];
  random_bytes((unsigned char *)&secret_key_len, sizeof(secret_key_len));
  secret_key_len &= 0x7fffffff;
  secret_key_len = (16 + secret_key_len % 16);
  
  random_bytes(binkey, secret_key_len);
  // secret_key is null terminated
  hexencode(binkey, secret_key_len, secret_key);
  //  printf("key_len: %d\n", secret_key_len);
  //printf("%s\n", secret_key);
}
Example #3
0
int arc_encode(char *clear, int clear_len, unsigned char **crypt, char *password, int pad_to)
{
	struct arc_state *st;
	unsigned char *key;
	char *padded = NULL;
	int key_len, i, padded_len;

	key_len = strlen(password) + ARC_IV_LEN;
	if (clear_len <= 0) {
		clear_len = strlen(clear);
	}

	/* Pad the string to the closest multiple of pad_to. This makes it
	   impossible to see the exact length of the password. */
	if (pad_to > 0 && (clear_len % pad_to) > 0) {
		padded_len = clear_len + pad_to - (clear_len % pad_to);
		padded = g_malloc(padded_len);
		memcpy(padded, clear, clear_len);

		/* First a \0 and then random data, so we don't have to do
		   anything special when decrypting. */
		padded[clear_len] = 0;
		random_bytes((unsigned char *) padded + clear_len + 1, padded_len - clear_len - 1);

		clear = padded;
		clear_len = padded_len;
	}

	/* Prepare buffers and the key + IV */
	*crypt = g_malloc(clear_len + ARC_IV_LEN);
	key = g_malloc(key_len);
	strcpy((char *) key, password);

	/* Add the salt. Save it for later (when decrypting) and, of course,
	   add it to the encryption key. */
	random_bytes(crypt[0], ARC_IV_LEN);
	memcpy(key + key_len - ARC_IV_LEN, crypt[0], ARC_IV_LEN);

	/* Generate the initial S[] from the IVed key. */
	st = arc_keymaker(key, key_len, ARC_CYCLES);
	g_free(key);

	for (i = 0; i < clear_len; i++) {
		crypt[0][i + ARC_IV_LEN] = clear[i] ^ arc_getbyte(st);
	}

	g_free(st);
	g_free(padded);

	return clear_len + ARC_IV_LEN;
}
Example #4
0
/**
 * Test implementation.
 */
void G_COLD
tea_test(void)
{
	tea_key_t key;
	tea_block_t value;
	tea_block_t encrypted;
	tea_block_t decrypted;
	int i;
	char in[80];
	char out[80];
	char recovered[80];

	STATIC_ASSERT(sizeof(key.v) == TEA_KEY_SIZE);
	STATIC_ASSERT(sizeof(value.v) == TEA_BLOCK_SIZE);

	for (i = 0; i < 10; i++) {
		int j;
		bool randomized = FALSE;

		for (j = 0; j < 10; j++) {
			random_bytes(key.v, TEA_KEY_SIZE);
			random_bytes(value.v, TEA_BLOCK_SIZE);

			t_encrypt(&encrypted, &key, &value);
			if (0 != memcmp(value.v, encrypted.v, TEA_BLOCK_SIZE)) {
				randomized = TRUE;
				break;
			}
		}

		if (!randomized)
			g_error("no luck with random numbers in tea_test()");

		t_decrypt(&decrypted, &key, &encrypted);
		if (0 != memcmp(value.v, decrypted.v, TEA_BLOCK_SIZE)) {
			g_error("TEA implementation tests FAILED");
			return;
		}
	}

	STATIC_ASSERT(sizeof in == sizeof out);
	STATIC_ASSERT(sizeof in == sizeof recovered);

	random_bytes(key.v, TEA_KEY_SIZE);
	random_bytes(in, sizeof in);
	tea_encrypt(&key, out, in, sizeof in);
	tea_decrypt(&key, recovered, out, sizeof out);

	if (0 != memcmp(in, recovered, sizeof in))
		g_error("TEA implementation tests FAILED");
}
Example #5
0
int main(int argc, char *argv[]) {
  int i, wait1, wait2, seed, start;
  unsigned int value;

  signal(SIGINT, SIGINT_handler);

  if(argc < 2) {
    random_bytes((unsigned char *)&wait1, sizeof(wait1));
    wait1 &= 0x7fffffff;
    wait1 = wait1 % 960 + 40;
    
    random_bytes((unsigned char *)&wait2, sizeof(wait2));
    wait2 &= 0x7fffffff;
    wait2 = wait2 % 960 + 40;
    
    printf("about to spend %d seconds running bad crypto code, OK?\n", wait1 + wait2);
    
    if(sleep(wait1)) {
      printf("sleep was interrupted\n");
    }
    
    seed = time(NULL);  
    FILE *fp = fopen("seed", "w");
    fprintf(fp, "%d", seed);
    fclose(fp);
    
    MT_initialize_generator(seed);
    
    sleep(wait2);  
    
    printf("secret: %u\n", MT_extract_number());
  } else {
    sscanf(argv[1], "%u", &value);
    if(argc > 2)
      sscanf(argv[2], "%d", &start);
    else
      start = time(NULL);

    printf("brute force search for seed generating %u, starting at %d\n", value, start);

    do {
      MT_initialize_generator(start--);
    } while(MT_extract_number() != value);
    start++;
    printf("generator seeded with: %d\n", start);
  }

  return 0;
}
Example #6
0
void
seq_test (const char *file_name, void *buf, size_t size, size_t initial_size,
          size_t (*block_size_func) (void),
          void (*check_func) (int fd, long ofs))
{
  size_t ofs;
  int fd;

  random_bytes (buf, size);
  CHECK (create (file_name, initial_size), "create \"%s\"", file_name);
  CHECK ((fd = open (file_name)) > 1, "open \"%s\"", file_name);

  ofs = 0;
  msg ("writing \"%s\"", file_name);
  while (ofs < size)
    {
      size_t block_size = block_size_func ();
      if (block_size > size - ofs)
        block_size = size - ofs;

      if (write (fd, buf + ofs, block_size) != (int) block_size)
        fail ("write %zu bytes at offset %zu in \"%s\" failed",
              block_size, ofs, file_name);

      ofs += block_size;
      if (check_func != NULL)
        check_func (fd, ofs);
    }
  msg ("close \"%s\"", file_name);
  close (fd);
  check_file (file_name, buf, size);
}
Example #7
0
static void test_acquire_data_fd_one(unsigned flags) {
        char wbuffer[196*1024 - 7];
        char rbuffer[sizeof(wbuffer)];
        int fd;

        fd = acquire_data_fd("foo", 3, flags);
        assert_se(fd >= 0);

        zero(rbuffer);
        assert_se(read(fd, rbuffer, sizeof(rbuffer)) == 3);
        assert_se(streq(rbuffer, "foo"));

        fd = safe_close(fd);

        fd = acquire_data_fd("", 0, flags);
        assert_se(fd >= 0);

        zero(rbuffer);
        assert_se(read(fd, rbuffer, sizeof(rbuffer)) == 0);
        assert_se(streq(rbuffer, ""));

        fd = safe_close(fd);

        random_bytes(wbuffer, sizeof(wbuffer));

        fd = acquire_data_fd(wbuffer, sizeof(wbuffer), flags);
        assert_se(fd >= 0);

        zero(rbuffer);
        assert_se(read(fd, rbuffer, sizeof(rbuffer)) == sizeof(rbuffer));
        assert_se(memcmp(rbuffer, wbuffer, sizeof(rbuffer)) == 0);

        fd = safe_close(fd);
}
int
main (int argc, const char *argv[]) 
{
  int child_idx;
  int fd;
  size_t i;

  quiet = true;
  
  CHECK (argc == 2, "argc must be 2, actually %d", argc);
  child_idx = atoi (argv[1]);

  random_init (0);
  random_bytes (buf, sizeof buf);

  CHECK ((fd = open (file_name)) > 1, "open \"%s\"", file_name);
  for (i = 0; i < sizeof buf; i++) 
    {
      char c;
      CHECK (read (fd, &c, 1) > 0, "read \"%s\"", file_name);
      compare_bytes (&c, buf + i, 1, i, file_name);
    }
  close (fd);

  return child_idx;
}
Example #9
0
int
main (int argc, const char *argv[])
{
  int child_idx;
  int fd;
  size_t ofs;

  quiet = true;

  CHECK (argc == 2, "argc must be 2, actually %d", argc);
  child_idx = atoi (argv[1]);

  random_init (0);
  random_bytes (buf1, sizeof buf1);

  CHECK ( (fd = open (file_name)) > 1, "open \"%s\"", file_name);
  ofs = 0;
  while (ofs < sizeof buf2)
    {
      int bytes_read = read (fd, buf2 + ofs, sizeof buf2 - ofs);
      CHECK (bytes_read >= -1 && bytes_read <= (int) (sizeof buf2 - ofs),
             "%zu-byte read on \"%s\" returned invalid value of %d",
             sizeof buf2 - ofs, file_name, bytes_read);
      if (bytes_read > 0)
        {
          compare_bytes (buf2 + ofs, buf1 + ofs, bytes_read, ofs, file_name);
          ofs += bytes_read;
        }
    }
  close (fd);

  return child_idx;
}
END_TEST

START_TEST(random_bytes_returns_random_bytes) {
  random_t random;
  random_create(random);

  uint8_t a[16] = {};
  uint8_t b[16] = {};

  random_bytes(random, a, 16);
  random_bytes(random, b, 16);

  fail_unless(memcmp(a, b, 16) != 0);

  random_free(random);
}
Example #11
0
static
void write_offer(struct master_config* config, struct endpoint* endpoint, struct udpaddress* remote) {
    char* key;
    char token[1500];
    char obuf[1500];
    ssize_t tlength, olength, r;
    struct proto proto;
    struct session* session;
    struct cipher_context* rkey = config->key0;

    key = alloca(config->cipher_keysize);
    random_bytes(key, config->cipher_keysize);

    session = session_find_by_address(config, &endpoint->local, remote);
    if (session) {
        if (session->rkey) {
            rkey = session->rkey;
        }
    }

    tlength = encrypt_challenge(config, remote, &endpoint->local, session ? session->key1 : 0, key, token);

    memset(&proto, 0, sizeof(proto));
    proto.type = PROTO_OFFER;
    proto.id.value = token;
    proto.id.length = tlength;
    proto.key.value = key;
    proto.key.length = config->cipher_keysize;
    olength = proto_encode(&proto, obuf, sizeof(obuf));

    encrypt_and_write(config, endpoint->socket, remote, rkey, obuf, olength);
}
Example #12
0
/* Returns a pseudo-random unsigned long.
   Use random_ulong() % n to obtain a random number in the range
   0...n (exclusive). */
unsigned long
random_ulong (void) 
{
  unsigned long ul;
  random_bytes (&ul, sizeof ul);
  return ul;
}
Example #13
0
bool test_encode_base64 (Test *test)
{
        char *base64;
        char bytes[1024 * 16];
        size_t i;

        TITLE ();
        CATCH (encode_base64 (NULL, 0));
        CATCH (error_at (0).error != ErrorInvalidArgument);
        CATCH (error_at (0).code != 1);
        CATCH (encode_base64 ("", 0));
        CATCH (error_at (0).error != ErrorInvalidArgument);
        CATCH (error_at (0).code != 2);
        memory_commit_limit (0);
        CATCH (encode_base64 ("abc", 3));
        CATCH (error_at (0).error != ErrorFunctionCall);
        memory_commit_limit (ULLONG_MAX);

        for (i = 0; i < 1000; i++) {
                CATCH (!(base64 = encode_base64 ("any carnal pleasure.", 20)));
                CATCH (!string_equals (base64, "YW55IGNhcm5hbCBwbGVhc3VyZS4="));
                string_destroy (base64);
        }

        CATCH (!random_open ());
        for (i = 0; i < 1000; i++) {
                CATCH (!random_bytes ((unsigned char *)&bytes, 1024 * 16));
                CATCH (!(base64 = encode_base64 (bytes, 1024 * 16)));
                CATCH (string_length (base64) < 21848);
                string_destroy (base64);
        }
        random_close ();
        PASS ();
}
Example #14
0
static void random_key(secp256k1_context *ctx,
		       struct seckey *seckey, secp256k1_pubkey *pkey)
{
	do {
		random_bytes(seckey->u.u8, sizeof(seckey->u));
	} while (!secp256k1_ec_pubkey_create(ctx, pkey, seckey->u.u8));
}
Example #15
0
/*
 * Return a new random number.
 */
u32_t magic() {
  u32_t new_rand;

  random_bytes((unsigned char *)&new_rand, sizeof(new_rand));

  return new_rand;
}
Example #16
0
/**
 * Generate new token for given version string.
 */
static char *
tok_generate(time_t now, const char *version)
{
	char token[TOKEN_BASE64_SIZE + 1];
	char digest[TOKEN_VERSION_SIZE];
	char lvldigest[LEVEL_SIZE];
	char lvlbase64[LEVEL_BASE64_SIZE + 1];
	const struct tokkey *tk;
	uint32 crc32;
	uint idx;
	const char *key;
	SHA1Context ctx;
    struct sha1 sha1;
	int lvlsize;
	int i;

	/*
	 * Compute token.
	 */

	key = random_key(now, &idx, &tk);
	now = clock_loc2gmt(now);				/* As close to GMT as possible */

	poke_be32(&digest[0], now);
	random_bytes(&digest[4], 3);
	digest[6] &= 0xe0U;			/* Upper 3 bits only */
	digest[6] |= idx & 0xffU;	/* Has 5 bits for the index */

	SHA1Reset(&ctx);
	SHA1Input(&ctx, key, strlen(key));
	SHA1Input(&ctx, digest, 7);
	SHA1Input(&ctx, version, strlen(version));
	SHA1Result(&ctx, &sha1);
	memcpy(&digest[7], sha1.data, SHA1_RAW_SIZE);

	/*
	 * Compute level.
	 */

	lvlsize = G_N_ELEMENTS(token_keys) - (tk - token_keys);
	crc32 = crc32_update(0, digest, TOKEN_VERSION_SIZE);

	for (i = 0; i < lvlsize; i++) {
		poke_be16(&lvldigest[i*2], tok_crc(crc32, tk));
		tk++;
	}

	/*
	 * Encode into base64.
	 */

	base64_encode_into(digest, TOKEN_VERSION_SIZE, token, TOKEN_BASE64_SIZE);
	token[TOKEN_BASE64_SIZE] = '\0';

	ZERO(&lvlbase64);
	base64_encode_into(lvldigest, 2 * lvlsize, lvlbase64, LEVEL_BASE64_SIZE);

	return g_strconcat(token, "; ", lvlbase64, (void *) 0);
}
Example #17
0
static void chap_md5_generate_challenge(unsigned char *cp) {
    int clen;

    clen = (int)(drand48() * (MD5_MAX_CHALLENGE - MD5_MIN_CHALLENGE))
           + MD5_MIN_CHALLENGE;
    *cp++ = clen;
    random_bytes(cp, clen);
}
Example #18
0
static void chapms2_generate_challenge(unsigned char *challenge) {
	*challenge++ = 16;
#ifdef DEBUGMPPEKEY
	if (mschap_challenge && strlen(mschap_challenge) == 16)
		memcpy(challenge, mschap_challenge, 16);
	else
#endif
		random_bytes(challenge, 16);
}
Example #19
0
static int crypt_main( int argc, char *argv[] )
{
	int pass_len;
	unsigned char *pass_cr, *pass_cl;
	
	if( argc < 4 || ( strcmp( argv[2], "hash" ) != 0 &&
	                  strcmp( argv[2], "unhash" ) != 0 && argc < 5 ) )
	{
		printf( "Supported:\n"
		        "  %s -x enc <key> <cleartext password>\n"
		        "  %s -x dec <key> <encrypted password>\n"
		        "  %s -x hash <cleartext password>\n"
		        "  %s -x unhash <hashed password>\n"
		        "  %s -x chkhash <hashed password> <cleartext password>\n",
		        argv[0], argv[0], argv[0], argv[0], argv[0] );
	}
	else if( strcmp( argv[2], "enc" ) == 0 )
	{
		pass_len = arc_encode( argv[4], strlen( argv[4] ), (unsigned char**) &pass_cr, argv[3], 12 );
		printf( "%s\n", base64_encode( pass_cr, pass_len ) );
	}
	else if( strcmp( argv[2], "dec" ) == 0 )
	{
		pass_len = base64_decode( argv[4], (unsigned char**) &pass_cr );
		arc_decode( pass_cr, pass_len, (char**) &pass_cl, argv[3] );
		printf( "%s\n", pass_cl );
	}
	else if( strcmp( argv[2], "hash" ) == 0 )
	{
		md5_byte_t pass_md5[21];
		md5_state_t md5_state;
		
		random_bytes( pass_md5 + 16, 5 );
		md5_init( &md5_state );
		md5_append( &md5_state, (md5_byte_t*) argv[3], strlen( argv[3] ) );
		md5_append( &md5_state, pass_md5 + 16, 5 ); /* Add the salt. */
		md5_finish( &md5_state, pass_md5 );
		
		printf( "%s\n", base64_encode( pass_md5, 21 ) );
	}
	else if( strcmp( argv[2], "unhash" ) == 0 )
	{
		printf( "Hash %s submitted to a massive Beowulf cluster of\n"
		        "overclocked 486s. Expect your answer next year somewhere around this time. :-)\n", argv[3] );
	}
	else if( strcmp( argv[2], "chkhash" ) == 0 )
	{
		char *hash = strncmp( argv[3], "md5:", 4 ) == 0 ? argv[3] + 4 : argv[3];
		int st = md5_verify_password( argv[4], hash );
		
		printf( "Hash %s given password.\n", st == 0 ? "matches" : "does not match" );
		
		return st;
	}
	
	return 0;
}
Example #20
0
void ecc_start(void)
{
    secp256k1_ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);
    assert(secp256k1_ctx != NULL);

    uint8_t seed[32];
    random_bytes(seed, 32, 0);
    int ret = secp256k1_context_randomize(secp256k1_ctx, seed);
    assert(ret);
}
gchar *
fb_util_rand_uuid(void)
{
    guint8 buf[50];
    sha1_state_t sha;

    sha1_init(&sha);
    random_bytes(buf, sizeof buf);
    sha1_append(&sha, buf, sizeof buf);
    return sha1_random_uuid(&sha);
}
Example #22
0
	bool Random_Impl::random_bool()
	{
		if (!random_bool_bits_free)
		{
			random_bytes(&_random_bool, 1);
			random_bool_bits_free = 8;
		}
		random_bool_bits_free--;

		return ((_random_bool >> random_bool_bits_free) & 1);
	}
Example #23
0
JournalRateLimit *journal_rate_limit_new(void) {
        JournalRateLimit *r;

        r = new0(JournalRateLimit, 1);
        if (!r)
                return NULL;

        random_bytes(r->hash_key, sizeof(r->hash_key));

        return r;
}
Example #24
0
uint16_t
random_uint16(void)
{
    if (RAND_MAX >= UINT16_MAX) {
        random_init();
        return rand();
    } else {
        uint16_t x;
        random_bytes(&x, sizeof x);
        return x;
    }
}
Example #25
0
/**************************************************************************
 * Function: generateAccountHash
 * Description: returns the unique hash for the account.
 * ************************************************************************/ 
md_hash * generateAccountHash (Account * acct) {
	static md_hash ret;
	unsigned char * hashable;
	int data_length = 0, string_length = 0;
	
	MemSet(ret, sizeof(md_hash), 0);
	
	/* username, password, acct mod date, 
	 * pw mod date, and 256 bits of randomness */
	data_length = 
		StrLen(acct->username)+
		StrLen(acct->system)+
		StrLen(acct->password)+
		StrLen(acct->service)+
		StrLen(acct->comment)+
		sizeof(acct->account_mod_date)+
		sizeof(acct->password_mod_date)+
		(sizeof(Int16)*16)+1;
		
		
	if((hashable=MemPtrNew(data_length))) {
		MemSet(hashable, data_length, 0);
		StrCopy(hashable, acct->username);	
		string_length+=StrLen(acct->username);
		StrCat(hashable, acct->system);	
		string_length+=StrLen(acct->system);
		StrCat(hashable, acct->password);
		string_length+=StrLen(acct->password);	
		StrCat(hashable, acct->service);
		string_length+=StrLen(acct->service);	
		StrCat(hashable, acct->comment);
		string_length+=StrLen(acct->comment);	
		
		MemMove(hashable+string_length, 
			&acct->account_mod_date, 
			sizeof(acct->account_mod_date));
		string_length+=sizeof(acct->account_mod_date);
		
		MemMove(hashable+string_length, 
			&acct->password_mod_date, 				
			sizeof(acct->password_mod_date));
		string_length+=sizeof(acct->password_mod_date);
		
		/* move some randomness onto the end 
		 * to make dictionary attacks impossible.   */
		random_bytes(hashable+string_length, 32);
		string_length+=32;
		
		md_block(hashable, string_length, ret);	
		MemPtrFree(hashable);
	}	
	return &ret;
}
Example #26
0
File: jabber.c Project: AlD/bitlbee
/* This generates an unfinished md5_state_t variable. Every time we generate
   an ID, we finish the state by adding a sequence number and take the hash. */
static void jabber_generate_id_hash( struct jabber_data *jd )
{
	md5_byte_t binbuf[4];
	char *s;
	
	md5_init( &jd->cached_id_prefix );
	md5_append( &jd->cached_id_prefix, (unsigned char *) jd->username, strlen( jd->username ) );
	md5_append( &jd->cached_id_prefix, (unsigned char *) jd->server, strlen( jd->server ) );
	s = set_getstr( &jd->ic->acc->set, "resource" );
	md5_append( &jd->cached_id_prefix, (unsigned char *) s, strlen( s ) );
	random_bytes( binbuf, 4 );
	md5_append( &jd->cached_id_prefix, binbuf, 4 );
}
/** Run unit tests for digest set code (implemented as a hashtable or as a
 * bloom filter) */
static void
test_container_digestset(void *unused)
{
  smartlist_t *included = smartlist_create();
  char d[SHA256_LENGTH];
  int i;
  int ok = 1;
  int false_positives = 0;
  digestset_t *set = NULL;

  for (i = 0; i < 1000; ++i) {
    random_bytes((uchar *)d, SHA256_LENGTH);
    smartlist_add(included, xmemdup(d, SHA256_LENGTH));
  }
  set = digestset_new(1000);
  SMARTLIST_FOREACH(included, const char *, cp,
                    if (digestset_isin(set, cp))
                      ok = 0);
  tt_assert(ok);
  SMARTLIST_FOREACH(included, const char *, cp,
                    digestset_add(set, cp));
  SMARTLIST_FOREACH(included, const char *, cp,
                    if (!digestset_isin(set, cp))
                      ok = 0);
  tt_assert(ok);
  for (i = 0; i < 1000; ++i) {
    random_bytes((uchar *)d, SHA256_LENGTH);
    if (digestset_isin(set, d))
      ++false_positives;
  }
  tt_assert(false_positives < 50); /* Should be far lower. */

 end:
  if (set)
    digestset_free(set);
  SMARTLIST_FOREACH(included, char *, cp, free(cp));
  smartlist_free(included);
}
Example #28
0
/* Initialize a flow with random fields that matter for nx_hash_fields. */
void
flow_random_hash_fields(struct flow *flow)
{
    uint16_t rnd = random_uint16();

    /* Initialize to all zeros. */
    memset(flow, 0, sizeof *flow);

    eth_addr_random(flow->dl_src);
    eth_addr_random(flow->dl_dst);

    flow->vlan_tci = (OVS_FORCE ovs_be16) (random_uint16() & VLAN_VID_MASK);

    /* Make most of the random flows IPv4, some IPv6, and rest random. */
    flow->dl_type = rnd < 0x8000 ? htons(ETH_TYPE_IP) :
        rnd < 0xc000 ? htons(ETH_TYPE_IPV6) : (OVS_FORCE ovs_be16)rnd;

    if (dl_type_is_ip_any(flow->dl_type)) {
        if (flow->dl_type == htons(ETH_TYPE_IP)) {
            flow->nw_src = (OVS_FORCE ovs_be32)random_uint32();
            flow->nw_dst = (OVS_FORCE ovs_be32)random_uint32();
        } else {
            random_bytes(&flow->ipv6_src, sizeof flow->ipv6_src);
            random_bytes(&flow->ipv6_dst, sizeof flow->ipv6_dst);
        }
        /* Make most of IP flows TCP, some UDP or SCTP, and rest random. */
        rnd = random_uint16();
        flow->nw_proto = rnd < 0x8000 ? IPPROTO_TCP :
            rnd < 0xc000 ? IPPROTO_UDP :
            rnd < 0xd000 ? IPPROTO_SCTP : (uint8_t)rnd;
        if (flow->nw_proto == IPPROTO_TCP ||
            flow->nw_proto == IPPROTO_UDP ||
            flow->nw_proto == IPPROTO_SCTP) {
            flow->tp_src = (OVS_FORCE ovs_be16)random_uint16();
            flow->tp_dst = (OVS_FORCE ovs_be16)random_uint16();
        }
    }
}
Example #29
0
static
ssize_t xencrypt(struct master_config* config, struct cipher_context* context, const char* in, size_t ilength, char* out) {
    char* tmp;
    ssize_t r,i;

    tmp = alloca(ilength + config->cipher_size);
    random_bytes(tmp, config->cipher_size);
    memcpy(tmp + config->cipher_size, in, ilength);

    r = cipher_encrypt(context, tmp, ilength + config->cipher_size, out);

    digest_sign(config->digest, tmp, ilength + config->cipher_size, out + r);
    return r + config->digest_size;
}
Example #30
0
int dns_transaction_new(DnsTransaction **ret, DnsScope *s, DnsResourceKey *key) {
        _cleanup_(dns_transaction_freep) DnsTransaction *t = NULL;
        int r;

        assert(ret);
        assert(s);
        assert(key);

        r = hashmap_ensure_allocated(&s->manager->dns_transactions, NULL);
        if (r < 0)
                return r;

        r = hashmap_ensure_allocated(&s->transactions, &dns_resource_key_hash_ops);
        if (r < 0)
                return r;

        t = new0(DnsTransaction, 1);
        if (!t)
                return -ENOMEM;

        t->dns_udp_fd = -1;
        t->key = dns_resource_key_ref(key);

        /* Find a fresh, unused transaction id */
        do
                random_bytes(&t->id, sizeof(t->id));
        while (t->id == 0 ||
               hashmap_get(s->manager->dns_transactions, UINT_TO_PTR(t->id)));

        r = hashmap_put(s->manager->dns_transactions, UINT_TO_PTR(t->id), t);
        if (r < 0) {
                t->id = 0;
                return r;
        }

        r = hashmap_put(s->transactions, t->key, t);
        if (r < 0) {
                hashmap_remove(s->manager->dns_transactions, UINT_TO_PTR(t->id));
                return r;
        }

        t->scope = s;

        if (ret)
                *ret = t;

        t = NULL;

        return 0;
}