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
static float
rand_float (void)
{
    uint32_t u = prng_rand();

    return *(float *)&u;
}
Ejemplo n.º 3
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.º 4
0
const char *
prng_fuzz(struct prng *prng,
          const char *string,
          const char *charset,
          unsigned int operations)
{
  static char buf[256];
  unsigned int charset_len;
  unsigned int i;
  unsigned int offset;
  unsigned int op;
  unsigned int character;

  assert(strlen(string) < sizeof(buf));

  strncpy(buf, string, sizeof(buf));
  charset_len = strlen(charset);

  for (i = 0; i < operations; i++)
    {
      offset = prng_rand(prng) % strlen(buf);
      op = prng_rand(prng) % 3;

      switch (op)
        {
        case 0:
          /* replace */
          character = prng_rand(prng) % charset_len;
          buf[offset] = charset[character];
          break;
        case 1:
          /* remove */
          memmove(buf + offset, buf + offset + 1, strlen(buf) - offset);
          break;
        case 2:
          /* insert */
          assert(strlen(buf) + 1 < sizeof(buf));

          memmove(buf + offset + 1, buf + offset, strlen(buf) + 1 - offset);
          character = prng_rand(prng) % charset_len;
          buf[offset] = charset[character];
          break;
        }
    }
  return buf;
}
Ejemplo n.º 5
0
int
main (int argc, const char *argv[])
{
    int i;
    int result = 0;

    if (argc == 2)
    {
	if (strcmp (argv[1], "--forever") == 0)
	{
	    uint32_t n;

	    prng_srand (time (0));

	    n = prng_rand();

	    for (;;)
		do_check (n++);
	}
        else
	{
	    do_check (strtol (argv[1], NULL, 0));
	}
    }
    else
    {
#ifdef USE_OPENMP
#       pragma omp parallel for default(none) reduction(|:result)
#endif
        for (i = 0; i < N_TESTS; ++i)
	{
	    if (!do_check (i))
		result |= 1;
	}
    }
    
    return result;
}
Ejemplo n.º 6
0
static int get_key_data(void)
{
  int best_weight = from_be_u16(polyhash[index_first].weight);
  index_weight_count = best_weight;
  uint64_t key = polyhash[index_first].key;

  index_count = 1;
  index_best = index_first;

  for (ssize_t i = index_first + 1; i < keycount; i++) {
    if (polyhash[i].key != key)
      break;

    index_count++;
    index_weight_count += from_be_u16(polyhash[i].weight);
    if (from_be_u16(polyhash[i].weight) > best_weight) {
      best_weight = from_be_u16(polyhash[i].weight);
      index_best = i;
    }
  }

  int rand_pos = prng_rand(&sr) % index_weight_count;
  int weight_count = 0;
  index_rand = index_best;

  for (ssize_t i = index_first; i < index_first + index_count; i++) {
    if (   rand_pos >= weight_count
        && rand_pos < weight_count + from_be_u16(polyhash[i].weight))
    {
      index_rand = i;
      break;
    }
    weight_count += from_be_u16(polyhash[i].weight);
  }

  return index_count;
}
Ejemplo n.º 7
0
int main(int argc, char **argv)
{
  int i, j;
  struct thread t;
  struct timeval **alarms;

  master = thread_master_create();

  log_buf_len = SCHEDULE_TIMERS * (TIMESTR_LEN + 1) + 1;
  log_buf_pos = 0;
  log_buf = XMALLOC(MTYPE_TMP, log_buf_len);

  expected_buf_len = SCHEDULE_TIMERS * (TIMESTR_LEN + 1) + 1;
  expected_buf_pos = 0;
  expected_buf = XMALLOC(MTYPE_TMP, expected_buf_len);

  prng = prng_new(0);

  timers = XMALLOC(MTYPE_TMP, SCHEDULE_TIMERS * sizeof(*timers));

  for (i = 0; i < SCHEDULE_TIMERS; i++)
    {
      long interval_msec;
      int ret;
      char *arg;

      /* Schedule timers to expire in 0..5 seconds */
      interval_msec = prng_rand(prng) % 5000;
      arg = XMALLOC(MTYPE_TMP, TIMESTR_LEN + 1);
      timers[i] = thread_add_timer_msec(master, timer_func, arg, interval_msec);
      ret = snprintf(arg, TIMESTR_LEN + 1, "%ld.%06ld",
                     timers[i]->u.sands.tv_sec, timers[i]->u.sands.tv_usec);
      assert(ret > 0);
      assert((size_t)ret < TIMESTR_LEN + 1);
      timers_pending++;
    }

  for (i = 0; i < REMOVE_TIMERS; i++)
    {
      int index;

      index = prng_rand(prng) % SCHEDULE_TIMERS;
      if (!timers[index])
        continue;

      XFREE(MTYPE_TMP, timers[index]->arg);
      thread_cancel(timers[index]);
      timers[index] = NULL;
      timers_pending--;
    }

  /* We create an array of pointers to the alarm times and sort
   * that array. That sorted array is used to generate a string
   * representing the expected "output" of the timers when they
   * are run. */
  j = 0;
  alarms = XMALLOC(MTYPE_TMP, timers_pending * sizeof(*alarms));
  for (i = 0; i < SCHEDULE_TIMERS; i++)
    {
      if (!timers[i])
        continue;
      alarms[j++] = &timers[i]->u.sands;
    }
  qsort(alarms, j, sizeof(*alarms), cmp_timeval);
  for (i = 0; i < j; i++)
    {
      int ret;

      ret = snprintf(expected_buf + expected_buf_pos,
                     expected_buf_len - expected_buf_pos,
                     "%ld.%06ld\n", alarms[i]->tv_sec, alarms[i]->tv_usec);
      assert(ret > 0);
      expected_buf_pos += ret;
      assert(expected_buf_pos < expected_buf_len);
    }
  XFREE(MTYPE_TMP, alarms);

  while (thread_fetch(master, &t))
    thread_call(&t);

  return 0;
}
Ejemplo n.º 8
0
int main(int argc, char **argv)
{
  struct prng *prng;
  int i;
  struct thread **timers;
  struct timeval tv_start, tv_lap, tv_stop;
  unsigned long t_schedule, t_remove;

  master = thread_master_create();
  prng = prng_new(0);
  timers = calloc(SCHEDULE_TIMERS, sizeof(*timers));

  /* create thread structures so they won't be allocated during the
   * time measurement */
  for (i = 0; i < SCHEDULE_TIMERS; i++)
    timers[i] = thread_add_timer_msec(master, dummy_func, NULL, 0);
  for (i = 0; i < SCHEDULE_TIMERS; i++)
    thread_cancel(timers[i]);

  quagga_gettime(QUAGGA_CLK_MONOTONIC, &tv_start);

  for (i = 0; i < SCHEDULE_TIMERS; i++)
    {
      long interval_msec;

      interval_msec = prng_rand(prng) % (100 * SCHEDULE_TIMERS);
      timers[i] = thread_add_timer_msec(master, dummy_func,
                                        NULL, interval_msec);
    }

  quagga_gettime(QUAGGA_CLK_MONOTONIC, &tv_lap);

  for (i = 0; i < REMOVE_TIMERS; i++)
    {
      int index;

      index = prng_rand(prng) % SCHEDULE_TIMERS;
      if (timers[index])
        thread_cancel(timers[index]);
      timers[index] = NULL;
    }

  quagga_gettime(QUAGGA_CLK_MONOTONIC, &tv_stop);

  t_schedule = 1000 * (tv_lap.tv_sec - tv_start.tv_sec);
  t_schedule += (tv_lap.tv_usec - tv_start.tv_usec) / 1000;

  t_remove = 1000 * (tv_stop.tv_sec - tv_lap.tv_sec);
  t_remove += (tv_stop.tv_usec - tv_lap.tv_usec) / 1000;

  printf("Scheduling %d random timers took %ld.%03ld seconds.\n",
         SCHEDULE_TIMERS, t_schedule/1000, t_schedule%1000);
  printf("Removing %d random timers took %ld.%03ld seconds.\n",
         REMOVE_TIMERS, t_remove/1000, t_remove%1000);
  fflush(stdout);

  free(timers);
  thread_master_free(master);
  prng_free(prng);
  return 0;
}
Ejemplo n.º 9
0
int main(int argc, char **argv)
{
  char *outfile;
  struct bench_args_t *data;
  int fd;
  node_index_t *adjmat;
  node_index_t *permute;
  node_index_t r,rp,c,cp,s,temp;
  edge_index_t e;
  int scale;
  long int rint;
  struct prng_rand_t state;
  int useless=0;

  if( argc>1 )
    outfile = argv[1];
  else
    outfile = "input.data";

  // Allocate data structure and temporary adjacency matrix
  data = (struct bench_args_t *)malloc(sizeof(struct bench_args_t));
  adjmat = (node_index_t *)calloc(N_NODES*N_NODES, sizeof(node_index_t));

  // Generate dense matrix
  prng_srand(1, &state);

  // The naive way is to create a normal SKG matrix and then shuffle it to
  // eliminate degree locality. But that takes a while (and lots of memops).
  // An alternate way is to generate a permute schedule a priori, then map
  // the generated edges directly to the shuffled matrix.
  // (For this shuffle, see Knuth v2-3.4.2 alg P.
  //  Ours is sufficiently identical.)
  permute = (node_index_t *)malloc(N_NODES*sizeof(node_index_t));
  for( s=0; s<N_NODES; s++ ) {
    permute[s] = s; // Default is no-swap
  }
  for( s=0; s<N_NODES; s++ ) {
    rint = prng_rand(&state)%N_NODES;
    // Swap row s with row rint
    temp = permute[s];
    permute[s] = permute[rint];
    permute[rint] = temp;
  }

  printf("Generating edges (SKG parameters: %0.2f,%0.2f,%0.2f,%0.2f)...\n",
    ((double)(A))/PRNG_RAND_MAX,
    ((double)(B))/PRNG_RAND_MAX,
    ((double)(C))/PRNG_RAND_MAX,
    ((double)(D))/PRNG_RAND_MAX );
  e = 0;
  // generate N_EDGES/2 undirected edges (N_EDGES directed), but give up after
  // a set number of tries without gainfully producing one. This prevents bad
  // parameter settings (e.g.- n_edges>n_nodes^2) from spinning forever.
  while( e<N_EDGES/2 && useless<USELESS_THRESHOLD ) {
    r = 0;
    c = 0;
    // Pick a random edge according to SKG parameters
    for( scale=SCALE; scale>0; scale-- ) { // each level of the quadtree
      rint = prng_rand(&state); // implicit modulo PRNG_RAND_MAX
      if( rint>=(A+B) ) // C or D (bottom half)
        r += 1<<(scale-1);
      if( (rint>=A && rint<A+B) || (rint>=A+B+C) ) // B or D (right half)
        c += 1<<(scale-1);
    }       
    if( r!=c ) { // ignore self-edges, they're irrelevant
      rp = permute[r];
      cp = permute[c];
      if( adjmat[rp*N_NODES+cp]==0 ) {
        // We make undirected edges
        adjmat[rp*N_NODES+cp]=1;
        adjmat[cp*N_NODES+rp]=1;
        ++e;
        useless = 0;
      }     
    }     
    useless++;
  }
  if( useless>=USELESS_THRESHOLD ) {
    printf("WARNING: stopped generating edges due to fruitless search for unconnected nodes.\n");
    return -1;
  }

  // printf("Creating CSR form...\n");
  // Scan rows for edge list lengths, and fill edges while we're at it
  e = 0;
  for( r=0; r<N_NODES; r++ ) { // count first
    data->nodes[r].edge_begin = 0;
    data->nodes[r].edge_end = 0;
    for( c=0; c<N_NODES; c++ ) {
      if( adjmat[r*N_NODES+c] ) {
        ++data->nodes[r].edge_end;
        data->edges[e].dst = c;
        //data->edges[e].weight = random()%(MAX_WEIGHT-MIN_WEIGHT)+MIN_WEIGHT;
        ++e;
      }
    }
    //if( data->nodes[r].edge_begin==data->nodes[r].edge_end ) {
    //  printf("Isolated node %lu\n", r);
    //}
  }

  for( r=1; r<N_NODES; r++ ) { // now scan
    data->nodes[r].edge_begin = data->nodes[r-1].edge_end;
    data->nodes[r].edge_end += data->nodes[r-1].edge_end;
  }

  // Pick starting node
  do {
    rint = random()%N_NODES;
  } while( (data->nodes[rint].edge_end-data->nodes[rint].edge_begin)<2 );
  data->starting_node = rint;

  // Fill data structure
  memset(data->queue, 0, N_NODES*sizeof(node_index_t));
  memset(data->level, MAX_LEVEL, N_NODES*sizeof(level_t));
  memset(data->level_counts, 0, MAX_LEVEL*sizeof(edge_index_t));

  // Open and write
  fd = open(outfile, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
  assert( fd>0 && "Couldn't open input data file" );
  data_to_input(fd, data);

  return 0;
}