Example #1
0
static void person_process(int id) {
	init_random();
	char buf[4096];
    struct lift_msg * reply;
	struct lift_msg m;
    m.person_id = id;
    int len;
    //printf("Created person with id %d\n", m.person_id);
	while(1) {
        // TODO:
		//    Generate a to and from floor
		//    Send a LIFT_TRAVEL message to the lift process
        //    Wait for a LIFT_TRAVEL_DONE message
		//    Wait a little while
	  //printf("Morning! This is number %d speaking.\n", id);
        m.from_floor = get_random_value(id, N_FLOORS - 1);
        do {
            m.to_floor = get_random_value(id, N_FLOORS - 1);
        } while(m.from_floor == m.to_floor);
        //printf("Person %d wants to go to floor %d\n", m.person_id,  m.to_floor);
        m.type = LIFT_TRAVEL;
        message_send((char *) &m, sizeof(m), QUEUE_LIFT, 0);

        do { 
            len = message_receive(buf, 4096, QUEUE_FIRSTPERSON + id); // Wait for a message
            if(len < sizeof(struct lift_msg)) {
                fprintf(stderr, "Message too short\n");
                continue;
            }
            reply = ((struct lift_msg*) buf);
         } while(reply->type != LIFT_TRAVEL_DONE);
        //printf("Going to sleep. Number %d\n", id);
        usleep(1000000);
    }
}
Example #2
0
static void *passenger_thread(void *idptr)
{
  //printf("Person skapad\n");
  // Code that reads the passenger ID from the idptr pointer
	// (due to the way pthread_create works we need to first cast
	// the void pointer to an int pointer).
	int *tmp = (int *) idptr;
	int id = *tmp;
	sem_post(&mutex);


	struct timeval starttime;
	struct timeval endtime;
	long long int timediff;
	gettimeofday(&starttime, NULL);
	
	int to, from;
	int i;
	for(i = 0; i < N_ITERATIONS; i++){
	  // * Select random floors
	  to = get_random_value(id, N_FLOORS-1);
	  while((from = get_random_value(id, N_FLOORS-1)) == to);
	  // * Travel between these floors
	  lift_travel(Lift, id, from, to);
	  // * Wait a little while
	  //sleep(1);
	}
	
	gettimeofday(&endtime, NULL);
	timediff = (endtime.tv_sec*1000000ULL + endtime.tv_usec) - (starttime.tv_sec*1000000ULL + starttime.tv_usec);
	printf("%d: %lld\n",id,timediff);
	
	return NULL;
}
Example #3
0
static void *passenger_thread(void *idptr)
{
	// Code that reads the passenger ID from the idptr pointer
	// (due to the way pthread_create works we need to first cast
	// the void pointer to an int pointer).


	int *tmp = (int *) idptr;
	int id = *tmp;
	sem_post(&(Lift->sem));

	if(id < N_VIP){
		struct sched_param sp;
		sp.sched_priority = 9;
		if(pthread_setschedparam(pthread_self(), SCHED_FIFO, &sp)){
			fprintf(stderr,"WARNING: Failed to set thread"
				"to real-time priority\n");
		}
	}

	int iterations = 0;
	struct timeval starttime;
    	struct timeval endtime;
    	long long int timediff = 0;
	long long int total_time = 0;
	

	while(1){
		gettimeofday(&starttime, NULL);


		// * Select random floors
		// * Travel between these floors
		// * Wait a little while
		int from_floor = get_random_value(id, N_FLOORS-1);
		int to_floor = get_random_value(id, N_FLOORS-1);
		while(from_floor == to_floor){
			to_floor = get_random_value(id, N_FLOORS-1);
		}

		lift_travel(Lift, id, from_floor, to_floor);


		gettimeofday(&endtime, NULL);
    		timediff = (endtime.tv_sec*1000000ULL + endtime.tv_usec) -
               		(starttime.tv_sec*1000000ULL + starttime.tv_usec);
		total_time = total_time + timediff;
		if(iterations == MAX_ITERATIONS){
			printf("ID %d done! Took %lld us.\n", id, total_time);
			pthread_mutex_lock(&Lift->mutex);
			done[id] = 1;
			outdata[id] = total_time;
			pthread_mutex_unlock(&Lift->mutex);
			sem_post(&(Lift->sem_done));
		}
		iterations++;

	}
	return NULL;
}
Example #4
0
/*
 * Encrypt a plaintext message using the mt19937 generator as keystream
 */
size_t encrypt( uint8_t *ctext[], const  uint8_t ptext[], const size_t len)
{
	size_t i;
	uint8_t *keystream;

	if (!random_prefix_len)
		random_prefix_len = 1 + (get_random_value() % 15);

	// Init MT19937 prng to a new seed
	password_token_reset();		
		
	keystream = malloc(len*sizeof(uint8_t));
	if (NULL == keystream)	
		return 0x00;

	*ctext = malloc((random_prefix_len + len)*sizeof(uint8_t));
	if (NULL == *ctext)
	{
		free(keystream);
		return 0x00;
	}	

	for (i = 0; i < random_prefix_len; i++)
		(*ctext)[i] = (uint8_t) get_random_value();

	mt19937_init( &cipher_mt, cipher_mt.seed);
	for (i = 0; i < len; i++)
		keystream[i] = mt19937_get_value(&cipher_mt);

	xor_encode(&((*ctext)[random_prefix_len]), ptext, len, keystream, len);

	free(keystream);

	return random_prefix_len + len;
}
Example #5
0
/*
 *  Reset the prng seed to the current timestamp (aka token reset).
 */
void password_token_reset()
{
	sleep(1 + (get_random_value() % 15));

	mt19937_init(&cipher_mt, time(NULL));
	token_init = 0x01;
	
	sleep(1 +(get_random_value() % 15));
}
Example #6
0
int Board::create_random_tile()
{
    int size = 0;
    
    // get the free position from the matrix
    create_free_position_array(m_free_pos_array, size);
    
    // get the random position of the element
    int random_pos = rand() % size;

    // decode the indexes of the chosen position
    int i = 0;
    int j = 0;
    sscanf(m_free_pos_array[random_pos], "%d %d", &i, &j);

    // generate the new random value
    int random_value = get_random_value();
    m_board[i][j].set_value(random_value);

    // reset the array of free positions
    for (int i = 0; i < size; i++)
    {
        strcpy(m_free_pos_array[i], "");
    }

    return 0;
}
ae_error_t CertificateProvisioningProtocol::msg1_create_seq3_0(const TLVsMsg& seq3_1_tlv_epid_gid, const provision_request_header_t& serializedHeader,
                               const upse::Buffer& ek1, TLVsMsg& seq3_0_tlv_block_cipher_text, upse::Buffer& mac)
{
    //* 3.0 Block Cipher Text TLV (TLV Type, Type, Version, Size, [IV, EncryptedPayload is 3.1])
    ae_error_t status = AE_FAILURE;
    tlv_status_t tlv_status;

    do
    {
        status = get_random_value(IV_SIZE, M1IV);
        if (AE_FAILED(status))
            break;

        upse::Buffer aad;
        status = aad.Alloc(sizeof(serializedHeader));
        if (AE_FAILED(status))
            break;

        upse::BufferWriter aadWriter(aad);
        status = aadWriter.writeRaw((const uint8_t*)&serializedHeader, sizeof(serializedHeader));
        if (AE_FAILED(status))
            break;

        upse::Buffer epidGid;
        status = epidGid.Alloc(seq3_1_tlv_epid_gid.get_tlv_msg(), seq3_1_tlv_epid_gid.get_tlv_msg_size());
        if (AE_FAILED(status))
            break;

        upse::Buffer encryptedPayload;
        status = aesGCMEncrypt(M1IV, ek1, epidGid, aad, encryptedPayload, mac);
        if (AE_FAILED(status))
            break;

        tlv_status = seq3_0_tlv_block_cipher_text.add_block_cipher_text(M1IV.getData(), encryptedPayload.getData(), encryptedPayload.getSize());
        status = tlv_error_2_pve_error(tlv_status);
        if (AE_FAILED(status))
            break;

        status = AE_SUCCESS;

    } while (0);

    return status;
}
int main()
{
	TEST_THREAD_DATA threads_data[NUMBER_OF_TEST_THREADS];
	THR_HANDLE thread_handle[NUMBER_OF_TEST_THREADS];
	unsigned i;
	int found_error = 0;

	srand( (unsigned)time( NULL ) );  

	memset( threads_data, 0, sizeof(threads_data) );
	for ( i = 0; i < NUMBER_OF_TEST_THREADS; i++ )
	{
		threads_data[i].index = i;
		threads_data[i].sleep_interval_millis = get_random_value( MAX_THREAD_SLEEP_MILLIS );
		thread_handle[i] = launch_thread( &threads_data[i] );
		if ( !thread_handle[i] )
		{
			fprintf( stderr, "failed to launch worker thread, error code is %d\n", LAST_ERROR() );
			return EXIT_FAILURE;
		}
	}

	for ( i = 0; i < NUMBER_OF_TEST_THREADS; i++ )
		if ( join_thread( thread_handle[i] ) != 0 )
		{
			fprintf( stderr, "failed to join thread %d, error code is %d\n", i, LAST_ERROR() );
			return EXIT_FAILURE;
		}

	for ( i = 0; i < NUMBER_OF_TEST_THREADS; i++ )
	{
		if( threads_data[i].error_occured )
		{
			fprintf( stderr, "error occured at thread %d: %s\n", i, threads_data[i].error_message );
			found_error = 1;
		}
	}
	if ( found_error )
		return EXIT_FAILURE;

//	printf( "test ended successfully\n");
	return EXIT_SUCCESS;
}
ae_error_t CertificateProvisioningProtocol::msg1_create_seq2_1(TLVsMsg& seq2_1_tlv_block_cipher_info)
{
    //* 2.1 Block Cipher Info TLV (TLV Type, Type, Version, Size, [SK])
    ae_error_t status = AE_FAILURE;
    tlv_status_t tlv_status;

    do
    {
        status = get_random_value(SK_SIZE, M1SK);
        if (AE_FAILED(status))
            break;

        tlv_status = seq2_1_tlv_block_cipher_info.add_block_cipher_info(M1SK.getData());
        status = tlv_error_2_pve_error(tlv_status);
        if (AE_FAILED(status))
            break;

        status = AE_SUCCESS;
    } while (0);

    return status;
}
Example #10
0
void run_isaac_test (rand_ctx ctx) {
    ub4 i;
    ub4 j;
    ub4 k;

    static char text[] = "This is <i>not</i> the right mytext.";

    std::memcpy((char *) ctx.rand_rsl, (char *) text, sizeof(text));

    rand_init(&ctx, TRUE);

    for (i = 0, k = 0; i < 10; ++i) {
        for (j = 0; j < RANDSIZ; ++j) {
            std::cout << std::hex << std::setfill('0') << std::setw(8);
            std::cout << get_random_value(&ctx) << " ";

            if (++k == 8) {
                k = 0;
                std::cout << std::endl;
            }
        }
    }
}
Example #11
0
ae_error_t CertificateProvisioningProtocol::msg3_seq3_0_create_block_cipher_text_tlv(const TLVsMsg& quote, const TLVsMsg& epidSigTLV, const TLVsMsg& csrTLV, const TLVsMsg& nonceTLV, 
                                                      const provision_request_header_t& requestHeader, const upse::Buffer& ek2,
                                                      TLVsMsg& blockCipherTextTLV, upse::Buffer& mac)
{
    ae_error_t status = AE_FAILURE;
    tlv_status_t tlv_status;

    upse::Buffer plainText;
    upse::Buffer encryptedPayload;

    do
    {
        status = get_random_value(IV_SIZE, M3IV);
        if (AE_FAILED(status))
            break;

        status = plainText.Alloc(quote.get_tlv_msg_size() + epidSigTLV.get_tlv_msg_size() + csrTLV.get_tlv_msg_size());
        if (AE_FAILED(status))
            break;

        upse::BufferWriter plainTextWriter(plainText);
        status = plainTextWriter.writeRaw(quote.get_tlv_msg(), quote.get_tlv_msg_size());
        if (AE_FAILED(status))
            break;
        status = plainTextWriter.writeRaw(epidSigTLV.get_tlv_msg(), epidSigTLV.get_tlv_msg_size());
        if (AE_FAILED(status))
            break;
        status = plainTextWriter.writeRaw(csrTLV.get_tlv_msg(), csrTLV.get_tlv_msg_size());
        if (AE_FAILED(status))
            break;

        uint32_t payloadSize = BLOCK_CIPHER_TEXT_TLV_PAYLOAD_SIZE(plainText.getSize());
        uint32_t blockCipherTextHeaderSize = get_tlv_total_size(payloadSize) - payloadSize;

        // Calculate AAD (concatenation of Request header, Nonce, Block Cipher Text TLV header and IV from Block Cipher Text TLV)
        upse::Buffer aad;
        status = aad.Alloc(static_cast<uint32_t>(sizeof(requestHeader) + nonceTLV.get_tlv_msg_size() +  blockCipherTextHeaderSize + M3IV.getSize()));
        if (AE_FAILED(status))
            break;

        TLVsMsg tmpBlockCipherTextTLV;
        tlv_status = tmpBlockCipherTextTLV.add_block_cipher_text(M3IV.getData(), NULL, plainText.getSize());
		status = tlv_error_2_pve_error(tlv_status);
        if (AE_FAILED(status))
            break;

        upse::BufferWriter aadWriter(aad);
        status = aadWriter.writeRaw((const uint8_t*)&requestHeader, sizeof(requestHeader));
        if (AE_FAILED(status))
            break;
        status = aadWriter.writeRaw(nonceTLV.get_tlv_msg(), nonceTLV.get_tlv_msg_size());
        if (AE_FAILED(status))
            break;
        status = aadWriter.writeRaw(tmpBlockCipherTextTLV.get_tlv_msg(), blockCipherTextHeaderSize);
        if (AE_FAILED(status))
            break;
        status = aadWriter.writeRaw(M3IV.getData(), M3IV.getSize());
        if (AE_FAILED(status))
            break;

        status = aesGCMEncrypt(M3IV, ek2, plainText, aad, encryptedPayload, mac);
        if (AE_FAILED(status))
            break;

        tlv_status = blockCipherTextTLV.add_block_cipher_text(M3IV.getData(), encryptedPayload.getData(), encryptedPayload.getSize());
		status = tlv_error_2_pve_error(tlv_status);
        if (AE_FAILED(status))
            break;

        status = AE_SUCCESS;

    } while (0);

    return status;
}
Example #12
0
static void person_process(int id) {
    init_random();
    char buf[4096];
    struct long_time_msg * reply;
    struct lift_msg m;
    struct long_lift_msg long_m;
    m.person_id = id;
    long_m.person_id = id;
    int len;
    int i, j;
    FILE * fptr;
    char result_name[25];

    struct timeval starttime;
    struct timeval endtime;
    long long int timediff[MAX_ITERATIONS];
    //printf("Created person with id %d\n", m.person_id);
    for(i=0; i < MAX_ITERATIONS; i+= MAX_TRIP_LEN) {
        // Generate new trip list
        long_m.type = LIFT_TRAVEL;
        long_m.trip_len = MAX_ITERATIONS - i < MAX_TRIP_LEN ? MAX_ITERATIONS - i : MAX_TRIP_LEN;
        //        printf("%d, %d, %d \n", MAX_ITERATIONS, i, MAX_TRIP_LEN);
        //        printf("Generating trip list for person %d of length %d\n", id, long_m.trip_len);
        for (j=0; j < long_m.trip_len; j++) {
            long_m.from_floor[j] = get_random_value(id, N_FLOORS - 1);
            do {
                long_m.to_floor[j] = get_random_value(id, N_FLOORS - 1);
            } while(long_m.from_floor[j] == long_m.to_floor[j]);
            //  printf("(%lld, %lld), ", long_m.from_floor[j], long_m.to_floor[j]);
        }
        // Send trip list to lift proc
        //        printf("\nPerson %d sent a trip list of length: %d\n", id, long_m.trip_len);
        message_send((char *) &long_m, sizeof(long_m), QUEUE_LIFT, 0);

        //printf("Person %d wants to go to floor %d\n", m.person_id,  m.to_floor);
        //gettimeofday(&starttime, NULL);
        do {
            len = message_receive(buf, 4096, QUEUE_FIRSTPERSON + id); // Wait for a message
            if(len < sizeof(struct long_time_msg)) {
                fprintf(stderr, "Message too short\n");
                continue;
            }
            //printf("Person %d, recieved a message \n", id);
            reply = ((struct long_time_msg*) buf);
        } while(reply->type != LIFT_TRAVEL_DONE);

        //        printf("Person %d received a reply from lift\nTimediff %d: (", id, id);
        // save timediff's to own array
        for (j=0; j < long_m.trip_len; j++) {
            timediff[i + j] = reply->timediff[j];
            //            printf("%lld, ", timediff[i+j]);
        }
        //        printf("\n");
        //printf("Person %d finished an iteration in %lld \n", id, timediff[i]);
    }

    //printf("Person %d asking file guard for permission.", id);
    /* Ask file guard for permission to write and wait for my turn */
    m.type = FILE_ASK;
    message_send((char *) &m, sizeof(m), QUEUE_FILE, 0);

    do {
        len = message_receive(buf, 4096, QUEUE_FIRSTPERSON + id); // Wait for a reply from guard
        if(len < sizeof(struct lift_msg)) {
            fprintf(stderr, "Message too short\n");
            continue;
        }
        //printf("Person %d, recieved a message\n", id);
        reply = ((struct lift_msg*) buf);
    } while(reply->type != FILE_WRITE);

    //printf("Person %d is writing to file\n", id);
    sprintf(result_name, "opt_results_m_%d.csv", MAX_N_PERSONS);
    fptr = fopen(result_name, "a");


    for (i=0; i<MAX_ITERATIONS; i++) {
        //printf("I'll write my results now, ID = %d\n", id);
        if (i== MAX_ITERATIONS - 1) {
            fprintf(fptr, "%lld\n", timediff[i]);
        } else {

            fprintf(fptr, "%lld, ", timediff[i]);
        }
    }
    //printf("Person %d is done writing to file\n", id);
    fclose(fptr);

    m.type = FILE_DONE;
    message_send((char *) &m, sizeof(m), QUEUE_FILE, 0);


    //printf("Finished!\n");
    exit(0);
}
Example #13
0
void restart
(
  int dimension,          /* dimension of the full model */
  vfp nmodel,             /* pointer to noise model */
  vfp smodel,             /* pointer to signal model */
  int r,                  /* number of parameters in the noise model */
  int p,                  /* number of parameters in the signal model */
  int nabs,               /* use absolute constraints for noise parameters */
  float * min_nconstr,    /* minimum parameter constraints for noise model */
  float * max_nconstr,    /* maximum parameter constraints for noise model */
  float * min_sconstr,    /* minimum parameter constraints for signal model */
  float * max_sconstr,    /* maximum parameter constraints for signal model */
  float * par_rdcd,       /* estimated parameters for the reduced model */
  float ** simplex,       /* the simplex itself */
  float * response,       /* sse at each vertex of the simplex */
  float * step_size,      /* amount of allowed variation at each parameter */
  int ts_length,          /* length of time series array */
  float ** x_array,       /* independent variable matrix */
  float * ts_array        /* observed time series */
)

{
  const float STEP_FACTOR = 0.9;
  int i, j;
  int worst, next, best;
  float minval, maxval;


  /* find the current best vertex */
  eval_vertices (dimension, response, &worst, &next, &best);


  /* set the first vertex to the current best */
  for (i = 0; i < dimension;  i++)
    simplex[0][i] = simplex[best][i];


  /* decrease step size */
  for (i = 0;  i < dimension;  i++)
    step_size[i] *= STEP_FACTOR;


  /* set up remaining vertices of simplex using new step size */
  for (i = 1;  i < dimension+1;  i++)
    {
      /*----- choose noise model parameters -----*/
      for (j = 0;  j < r;  j++)
	{
	  minval = simplex[0][j] - step_size[j];
	  if (nabs)   /*--- absolute noise parameter constraints ---*/
	    {
	      if (minval < min_nconstr[j])
		minval = min_nconstr[j];
	    }
	  else        /*--- relative noise parameter constraints ---*/
	    {
	      if (minval < min_nconstr[j] + par_rdcd[j])
		minval = min_nconstr[j] + par_rdcd[j];
	    }

	  maxval = simplex[0][j] + step_size[j];
	  if (nabs)
	    {
	      if (maxval > max_nconstr[j])
		maxval = max_nconstr[j];
	    }
	  else
	    {
	      if (maxval > max_nconstr[j] + par_rdcd[j])
		maxval = max_nconstr[j] + par_rdcd[j];
	    }

	  simplex[i][j] = get_random_value (minval, maxval);
	}


      /*----- choose signal model parameters -----*/
      for (j = r;  j < dimension;  j++)
	{
	  minval = simplex[0][j] - step_size[j];
	  if (minval < min_sconstr[j-r])
	    minval = min_sconstr[j-r];
	  maxval = simplex[0][j] + step_size[j];
	  if (maxval > max_sconstr[j-r])
	    maxval = max_sconstr[j-r];
	  simplex[i][j] = get_random_value (minval, maxval);
	}
    }


  /* initialize response for each vector */
  for (i = 0;  i < dimension+1;  i++)
    response[i] = calc_sse (nmodel, smodel, r, p, nabs,
			   min_nconstr, max_nconstr, min_sconstr, max_sconstr,
			   par_rdcd, simplex[i], ts_length, x_array, ts_array);
}
Example #14
0
void initialize_simplex
(
  int dimension,          /* dimension of the full model */
  vfp nmodel,             /* pointer to noise model */
  vfp smodel,             /* pointer to signal model */
  int r,                  /* number of parameters in the noise model */
  int p,                  /* number of parameters in the signal model */
  int nabs,               /* use absolute constraints for noise parameters */
  float * min_nconstr,    /* minimum parameter constraints for noise model */
  float * max_nconstr,    /* maximum parameter constraints for noise model */
  float * min_sconstr,    /* minimum parameter constraints for signal model */
  float * max_sconstr,    /* maximum parameter constraints for signal model */
  float * par_rdcd,       /* estimated parameters for the reduced model */
  float * parameters,     /* starting point */
  float ** simplex,       /* the simplex itself */
  float * response,       /* sse at each vertex of the simplex */
  float * step_size,      /* amount of allowed variation at each parameter */
  int ts_length,          /* length of time series array */
  float ** x_array,       /* independent variable matrix */
  float * ts_array        /* observed time series */
)

{
  int i, j;
  float minval, maxval;


  /*----- copy parameter vector into first vertex of simplex -----*/
  for (i = 0;  i < dimension;  i++)
    simplex[0][i] = parameters[i];


  /*----- set up initial step sizes -----*/
  for (i = 0;  i < r;  i++)
    step_size[i] = 0.1 * (max_nconstr[i] - min_nconstr[i]);
  for (i = r;  i < dimension;  i++)
    step_size[i] = 0.1 * (max_sconstr[i-r] - min_sconstr[i-r]);


  /*----- choose random vectors for remaining vertices -----*/
  for (i = 1;  i < dimension+1;  i++)
    {
      /*----- choose noise model parameters -----*/
      for (j = 0;  j < r;  j++)
	{
	  minval = simplex[0][j] - step_size[j];
	  if (nabs)   /*--- absolute noise parameter constraints ---*/
	    {
	      if (minval < min_nconstr[j])
		minval = min_nconstr[j];
	    }
	  else        /*--- relative noise parameter constraints ---*/
	    {
	      if (minval < min_nconstr[j] + par_rdcd[j])
		minval = min_nconstr[j] + par_rdcd[j];
	    }

	  maxval = simplex[0][j] + step_size[j];
	  if (nabs)   /*--- absolute noise parameter constraints ---*/
	    {
	      if (maxval > max_nconstr[j])
		maxval = max_nconstr[j];
	    }
	  else        /*--- relative noise parameter constraints ---*/
	    {
	      if (maxval > max_nconstr[j] + par_rdcd[j])
		maxval = max_nconstr[j] + par_rdcd[j];
	    }
	  simplex[i][j] = get_random_value (minval, maxval);
	}


      /*----- choose signal model parameters -----*/
      for (j = r;  j < dimension;  j++)
	{
	  minval = simplex[0][j] - step_size[j];
	  if (minval < min_sconstr[j-r])
	    minval = min_sconstr[j-r];
	  maxval = simplex[0][j] + step_size[j];
	  if (maxval > max_sconstr[j-r])
	    maxval = max_sconstr[j-r];
	  simplex[i][j] = get_random_value (minval, maxval);
	}
    }


  /*----- calculate and save sse for each vertex of simplex -----*/
  for (i = 0;  i < dimension+1;  i++)
    response[i] = calc_sse(nmodel, smodel, r, p, nabs,
			   min_nconstr, max_nconstr, min_sconstr, max_sconstr,
			   par_rdcd, simplex[i], ts_length, x_array, ts_array);

}
Example #15
0
ae_error_t CertificateProvisioningProtocol::msg1_generate(const GroupId gid, upse::Buffer& serializedMsg1)
{
    ae_error_t status = AE_FAILURE;
    tlv_status_t tlv_status = TLV_UNKNOWN_ERROR;
    GroupId be_gid; //gid from init_quote is little endian, change to bigendian for backend server here
    be_gid.data[0]=gid.data[3];
    be_gid.data[1]=gid.data[2];
    be_gid.data[2]=gid.data[1];
    be_gid.data[3]=gid.data[0];

    provision_request_header_t header;
    memset(&header, 0, sizeof(header));

    TLVsMsg seq2_0_tlv_cipher_text;
    TLVsMsg seq2_1_tlv_block_cipher_info;
    TLVsMsg seq3_0_tlv_block_cipher_text;
    TLVsMsg seq3_1_tlv_epid_gid;
    TLVsMsg seq4_0_tlv_mac;

    do
    {
        status = get_random_value(XID_SIZE, TransactionID);
        if (AE_FAILED(status))
            break;

        // Prepare sequence 2.1 -- Block Cipher Text TLV with SK
        status = msg1_create_seq2_1(seq2_1_tlv_block_cipher_info);
        if (AE_FAILED(status))
            break;

        // Prepare sequence 2.0 -- Cipher Text TLV with KeyID and encrypted 2.1
        status = msg1_create_seq2_0(seq2_1_tlv_block_cipher_info, seq2_0_tlv_cipher_text);
        if (AE_FAILED(status))
            break;

        // Prepare sequence 3.1 -- EPID GID TLV
        tlv_status = seq3_1_tlv_epid_gid.add_epid_gid(be_gid);
        status = tlv_error_2_pve_error(tlv_status);
        if (AE_FAILED(status))
            break;

        // Derive EK1
        upse::Buffer EK1;
        status = aesCMAC(M1SK, TransactionID, EK1);
        if (AE_FAILED(status))
            break;

        // Create Request Header (we need to calculate size before AES-GCM CMAC)
        status = msg1_create_header(seq2_0_tlv_cipher_text.get_tlv_msg_size(), seq3_1_tlv_epid_gid.get_tlv_msg_size(), TransactionID, header);
        if (AE_FAILED(status))
            break;

        // Prepare sequence 3.0 -- Block Cipher Text TLV with IV and encrypted 3.1
        upse::Buffer mac;
        status = msg1_create_seq3_0(seq3_1_tlv_epid_gid, header, EK1, seq3_0_tlv_block_cipher_text, mac);
        if (AE_FAILED(status))
            break;

        // Prepare sequence 4.0 -- MAC TLV
        tlv_status = seq4_0_tlv_mac.add_mac(mac.getData());
        status = tlv_error_2_pve_error(tlv_status);
        if (AE_FAILED(status))
            break;

        //*********************************************************************
        // Prepare serialized message buffer
        //*********************************************************************
        uint32_t size_msg1 = static_cast<uint32_t>(PROVISION_REQUEST_HEADER_SIZE) + seq2_0_tlv_cipher_text.get_tlv_msg_size() +
                                seq3_0_tlv_block_cipher_text.get_tlv_msg_size() + seq4_0_tlv_mac.get_tlv_msg_size();

        status = serializedMsg1.Alloc(size_msg1);
        if (AE_FAILED(status))
            break;

        serializedMsg1.zeroMemory();
        upse::BufferWriter bwMsg1(serializedMsg1);

        // Write serialized request header to serialized message
        status = bwMsg1.writeRaw((uint8_t*)&header, sizeof(header));
        if (AE_FAILED(status))
            break;

        // Write sequence 2.0 - Cipher Text TLV (contains 2.1 as encrypted payload)
        status = bwMsg1.writeRaw(const_cast<uint8_t*>(seq2_0_tlv_cipher_text.get_tlv_msg()), seq2_0_tlv_cipher_text.get_tlv_msg_size());
        if (AE_FAILED(status))
            break;

        // Write sequence 3.0 - Block Cipher Text TLV (contains 3.1 as encrypted payload)
        status = bwMsg1.writeRaw(const_cast<uint8_t*>(seq3_0_tlv_block_cipher_text.get_tlv_msg()), seq3_0_tlv_block_cipher_text.get_tlv_msg_size());
        if (AE_FAILED(status))
            break;

        // Write sequence 4.0 - MAC TLV
        status = bwMsg1.writeRaw(const_cast<uint8_t*>(seq4_0_tlv_mac.get_tlv_msg()), seq4_0_tlv_mac.get_tlv_msg_size());
        if (AE_FAILED(status))
            break;

        status = AE_SUCCESS;

    } while (0);

    return status;
}
Example #16
0
PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv)
{
  int i, rv;
  const char *user = NULL;
  char *password;
  unsigned int slot_num = 0;
  int is_a_screen_saver = 0;
  struct configuration_st *configuration;
  int pkcs11_pam_fail = PAM_AUTHINFO_UNAVAIL;

  pkcs11_handle_t *ph;
  cert_object_t *chosen_cert = NULL;
  cert_object_t **cert_list;
  int ncert;
  unsigned char random_value[128];
  unsigned char *signature;
  unsigned long signature_length;
  /* enough space to hold an issuer DN */
  char env_temp[256] = "";
  char **issuer, **serial;
  const char *login_token_name = NULL;

  pam_prompt(pamh, PAM_TEXT_INFO , NULL, _("Smartcard authentication starts"));

  /* first of all check whether debugging should be enabled */
  for (i = 0; i < argc; i++)
    if (strcmp("debug", argv[i]) == 0) {
      set_debug_level(1);
    }

  /* call configure routines */
  configuration = pk_configure(argc,argv);
  if (!configuration ) {
	ERR("Error setting configuration parameters");
	return PAM_AUTHINFO_UNAVAIL;
  }

  /* Either slot_description or slot_num, but not both, needs to be used */
  if ((configuration->slot_description != NULL && configuration->slot_num != -1) || (configuration->slot_description == NULL && configuration->slot_num == -1)) {
	ERR("Error setting configuration parameters");
	return PAM_AUTHINFO_UNAVAIL;
  }

  /* fail if we are using a remote server
   * local login: DISPLAY=:0
   * XDMCP login: DISPLAY=host:0 */
  {
	  char *display = getenv("DISPLAY");

	  if (display)
	  {
		  if (strncmp(display, "localhost:", 10) != 0 && (display[0] != ':')
			  && (display[0] != '\0')) {
			  ERR1("Remote login (from %s) is not (yet) supported", display);
			  pam_syslog(pamh, LOG_ERR,
				  "Remote login (from %s) is not (yet) supported", display);
			  return PAM_AUTHINFO_UNAVAIL;
		  }
	  }
  }

#ifdef ENABLE_NLS
  setlocale(LC_ALL, "");
  bindtextdomain(PACKAGE, "/usr/share/locale");
  textdomain(PACKAGE);
#endif

  /* init openssl */
  rv = crypto_init(&configuration->policy);
  if (rv != 0) {
    ERR("Failed to initialize crypto");
    if (!configuration->quiet)
      pam_syslog(pamh,LOG_ERR, "Failed to initialize crypto");
    return PAM_AUTHINFO_UNAVAIL;
  }


  /*
   * card_only means:
   *  1) always get the userid from the certificate.
   *  2) don't prompt for the user name if the card is present.
   *  3) if the token is present, then we must use the cardAuth mechanism.
   *
   * wait_for_card means:
   *  1) nothing if card_only isn't set
   *  2) if logged in, block in pam conversation until the token used for login
   *     is inserted
   *  3) if not logged in, block until a token that could be used for logging in
   *     is inserted
   * right now, logged in means PKC11_LOGIN_TOKEN_NAME is set,
   * but we could something else later (like set some per-user state in
   * a pam session module keyed off uid)
   */
  if (configuration->card_only) {
	char *service;
	if (configuration->screen_savers) {
	    DBG("Is it a screen saver?");
		pam_get_item(pamh, PAM_SERVICE, &service);
	    for (i=0; configuration->screen_savers[i]; i++) {
		if (strcmp(configuration->screen_savers[i], service) == 0) {
		    is_a_screen_saver = 1;
		    break;
		}
	    }
	}

	pkcs11_pam_fail = PAM_CRED_INSUFFICIENT;

	/* look to see if username is already set */
	pam_get_item(pamh, PAM_USER, &user);
	if (user) {
	    DBG1("explicit username = [%s]", user);
	}
  } else {
	rv = pam_get_item(pamh, PAM_USER, &user);
	if (rv != PAM_SUCCESS || user == NULL || user[0] == '\0') {
	  pam_prompt(pamh, PAM_TEXT_INFO, NULL,
		  _("Please insert your %s or enter your username."),
		  _(configuration->token_type));
	  /* get user name */
	  rv = pam_get_user(pamh, &user, NULL);

	  if (rv != PAM_SUCCESS) {
		pam_syslog(pamh, LOG_ERR,
			"pam_get_user() failed %s", pam_strerror(pamh, rv));
		return PAM_USER_UNKNOWN;
	  }
	}
	DBG1("username = [%s]", user);
  }
  login_token_name = getenv("PKCS11_LOGIN_TOKEN_NAME");

  /* if we are using a screen saver, and we didn't log in using the smart card
   * drop to the next pam module.  */
  if (is_a_screen_saver && !login_token_name) {
    return PAM_IGNORE;
  }

  /* load pkcs #11 module */
  DBG("loading pkcs #11 module...");
  rv = load_pkcs11_module(configuration->pkcs11_modulepath, &ph);
  if (rv != 0) {
    ERR2("load_pkcs11_module() failed loading %s: %s",
		configuration->pkcs11_modulepath, get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "load_pkcs11_module() failed loading %s: %s",
			configuration->pkcs11_modulepath, get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2302: PKCS#11 module failed loading"));
		sleep(configuration->err_display_time);
	}
    return PAM_AUTHINFO_UNAVAIL;
  }

  /* initialise pkcs #11 module */
  DBG("initialising pkcs #11 module...");
  rv = init_pkcs11_module(ph,configuration->support_threads);
  if (rv != 0) {
    release_pkcs11_module(ph);
    ERR1("init_pkcs11_module() failed: %s", get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "init_pkcs11_module() failed: %s", get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2304: PKCS#11 module could not be initialized"));
		sleep(configuration->err_display_time);
	}
    return PAM_AUTHINFO_UNAVAIL;
  }

  /* open pkcs #11 session */
  if (configuration->slot_description != NULL) {
    rv = find_slot_by_slotlabel_and_tokenlabel(ph,
      configuration->slot_description, login_token_name, &slot_num);
  } else if (configuration->slot_num != -1) {
    rv = find_slot_by_number_and_label(ph, configuration->slot_num,
                                     login_token_name, &slot_num);
  }

  if (rv != 0) {
    ERR("no suitable token available");
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "no suitable token available");
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2306: No suitable token available"));
		sleep(configuration->err_display_time);
	}

    if (!configuration->card_only) {
      release_pkcs11_module(ph);
      return PAM_AUTHINFO_UNAVAIL;
    }

    /* we must have a smart card, either because we've configured it as such,
     * or because we used one to log in */
    if (login_token_name || configuration->wait_for_card) {
      if (login_token_name) {
        pam_prompt(pamh, PAM_TEXT_INFO, NULL,
			_("Please insert your smart card called \"%.32s\"."),
			login_token_name);
      } else {
        pam_prompt(pamh, PAM_TEXT_INFO, NULL,
                 _("Please insert your smart card."));
      }

      if (configuration->slot_description != NULL) {
	rv = wait_for_token_by_slotlabel(ph, configuration->slot_description,
          login_token_name, &slot_num);
      } else if (configuration->slot_num != -1) {
        rv = wait_for_token(ph, configuration->slot_num,
                          login_token_name, &slot_num);
      }

      if (rv != 0) {
        release_pkcs11_module(ph);
        return pkcs11_pam_fail;
      }
    } else if (user) {
		if (!configuration->quiet) {
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2308: No smartcard found"));
			sleep(configuration->err_display_time);
		}

      /* we have a user and no smart card, go to the next pam module */
      release_pkcs11_module(ph);
      return PAM_AUTHINFO_UNAVAIL;
    } else {
      /* we haven't prompted for the user yet, get the user and see if
       * the smart card has been inserted in the mean time */
      pam_prompt(pamh, PAM_TEXT_INFO, NULL,
	    _("Please insert your %s or enter your username."),
		_(configuration->token_type));
      rv = pam_get_user(pamh, &user, NULL);

      /* check one last time for the smart card before bouncing to the next
       * module */
      if (configuration->slot_description != NULL) {
	rv = find_slot_by_slotlabel(ph, configuration->slot_description,
	  &slot_num);
      } else if (configuration->slot_num != -1) {
        rv = find_slot_by_number(ph, configuration->slot_num, &slot_num);
      }

      if (rv != 0) {
        /* user gave us a user id and no smart card go to next module */
		if (!configuration->quiet) {
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2310: No smartcard found"));
			sleep(configuration->err_display_time);
		}

        release_pkcs11_module(ph);
        return PAM_AUTHINFO_UNAVAIL;
      }
    }
  } else {
      pam_prompt(pamh, PAM_TEXT_INFO, NULL,
		  _("%s found."), _(configuration->token_type));
  }
  rv = open_pkcs11_session(ph, slot_num);
  if (rv != 0) {
    ERR1("open_pkcs11_session() failed: %s", get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "open_pkcs11_session() failed: %s", get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2312: open PKCS#11 session failed"));
		sleep(configuration->err_display_time);
	}
    release_pkcs11_module(ph);
    return pkcs11_pam_fail;
  }

  rv = get_slot_login_required(ph);
  if (rv == -1) {
    ERR1("get_slot_login_required() failed: %s", get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "get_slot_login_required() failed: %s", get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2314: Slot login failed"));
		sleep(configuration->err_display_time);
	}
    release_pkcs11_module(ph);
    return pkcs11_pam_fail;
  } else if (rv) {
    /* get password */
	pam_prompt(pamh, PAM_TEXT_INFO, NULL,
		_("Welcome %.32s!"), get_slot_tokenlabel(ph));

	/* no CKF_PROTECTED_AUTHENTICATION_PATH */
	rv = get_slot_protected_authentication_path(ph);
	if ((-1 == rv) || (0 == rv))
	{
		char password_prompt[128];

		snprintf(password_prompt,  sizeof(password_prompt), _("%s PIN: "), _(configuration->token_type));
		if (configuration->use_first_pass) {
			rv = pam_get_pwd(pamh, &password, NULL, PAM_AUTHTOK, 0);
		} else if (configuration->try_first_pass) {
			rv = pam_get_pwd(pamh, &password, password_prompt, PAM_AUTHTOK,
					PAM_AUTHTOK);
		} else {
			rv = pam_get_pwd(pamh, &password, password_prompt, 0, PAM_AUTHTOK);
		}
		if (rv != PAM_SUCCESS) {
			if (!configuration->quiet) {
				pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2316: password could not be read"));
				sleep(configuration->err_display_time);
			}
			release_pkcs11_module(ph);
			pam_syslog(pamh, LOG_ERR,
					"pam_get_pwd() failed: %s", pam_strerror(pamh, rv));
			return pkcs11_pam_fail;
		}
#ifdef DEBUG_SHOW_PASSWORD
		DBG1("password = [%s]", password);
#endif

		/* check password length */
		if (!configuration->nullok && strlen(password) == 0) {
			release_pkcs11_module(ph);
			memset(password, 0, strlen(password));
			free(password);
			pam_syslog(pamh, LOG_ERR,
					"password length is zero but the 'nullok' argument was not defined.");
			if (!configuration->quiet) {
				pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2318: Empty smartcard PIN not allowed."));
				sleep(configuration->err_display_time);
			}
			return PAM_AUTH_ERR;
		}
	}
	else
	{
		pam_prompt(pamh, PAM_TEXT_INFO, NULL,
			_("Enter your %s PIN on the pinpad"), _(configuration->token_type));
		/* use pin pad */
		password = NULL;
	}

    /* call pkcs#11 login to ensure that the user is the real owner of the card
     * we need to do thise before get_certificate_list because some tokens
     * can not read their certificates until the token is authenticated */
    rv = pkcs11_login(ph, password);
    /* erase and free in-memory password data asap */
	if (password)
	{
		memset(password, 0, strlen(password));
		free(password);
	}
    if (rv != 0) {
      ERR1("open_pkcs11_login() failed: %s", get_error());
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR, "open_pkcs11_login() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2320: Wrong smartcard PIN"));
			sleep(configuration->err_display_time);
		}
      goto auth_failed_nopw;
    }
  }

  cert_list = get_certificate_list(ph, &ncert);
  if (rv<0) {
    ERR1("get_certificate_list() failed: %s", get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "get_certificate_list() failed: %s", get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2322: No certificate found"));
		sleep(configuration->err_display_time);
	}
    goto auth_failed_nopw;
  }

  /* load mapper modules */
  load_mappers(configuration->ctx);

  /* find a valid and matching certificates */
  for (i = 0; i < ncert; i++) {
    X509 *x509 = (X509 *)get_X509_certificate(cert_list[i]);
    if (!x509 ) continue; /* sanity check */
    DBG1("verifying the certificate #%d", i + 1);
	if (!configuration->quiet) {
		pam_prompt(pamh, PAM_TEXT_INFO, NULL, _("verifying certificate"));
	}

      /* verify certificate (date, signature, CRL, ...) */
      rv = verify_certificate(x509,&configuration->policy);
      if (rv < 0) {
        ERR1("verify_certificate() failed: %s", get_error());
        if (!configuration->quiet) {
          pam_syslog(pamh, LOG_ERR,
                   "verify_certificate() failed: %s", get_error());
			switch (rv) {
				case -2: // X509_V_ERR_CERT_HAS_EXPIRED:
					pam_prompt(pamh, PAM_ERROR_MSG , NULL,
						_("Error 2324: Certificate has expired"));
					break;
				case -3: // X509_V_ERR_CERT_NOT_YET_VALID:
					pam_prompt(pamh, PAM_ERROR_MSG , NULL,
						_("Error 2326: Certificate not yet valid"));
					break;
				case -4: // X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
					pam_prompt(pamh, PAM_ERROR_MSG , NULL,
						_("Error 2328: Certificate signature invalid"));
					break;
				default:
					pam_prompt(pamh, PAM_ERROR_MSG , NULL,
						_("Error 2330: Certificate invalid"));
					break;
			}
			sleep(configuration->err_display_time);
		}
        continue; /* try next certificate */
      } else if (rv != 1) {
        ERR1("verify_certificate() failed: %s", get_error());
        continue; /* try next certificate */
      }

    /* CA and CRL verified, now check/find user */

    if ( is_spaced_str(user) ) {
      /*
	if provided user is null or empty extract and set user
	name from certificate
      */
	DBG("Empty login: try to deduce from certificate");
	user=find_user(x509);
	if (!user) {
          ERR2("find_user() failed: %s on cert #%d", get_error(),i+1);
          if (!configuration->quiet)
            pam_syslog(pamh, LOG_ERR,
                     "find_user() failed: %s on cert #%d",get_error(),i+1);
	  continue; /* try on next certificate */
	} else {
          DBG1("certificate is valid and matches user %s",user);
	  /* try to set up PAM user entry with evaluated value */
	  rv = pam_set_item(pamh, PAM_USER,(const void *)user);
	  if (rv != PAM_SUCCESS) {
	    ERR1("pam_set_item() failed %s", pam_strerror(pamh, rv));
            if (!configuration->quiet) {
				pam_syslog(pamh, LOG_ERR,
                       "pam_set_item() failed %s", pam_strerror(pamh, rv));
				pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2332: setting PAM userentry failed"));
				sleep(configuration->err_display_time);
			}
	    goto auth_failed_nopw;
	}
          chosen_cert = cert_list[i];
          break; /* end loop, as find user success */
      }
    } else {
      /* User provided:
         check whether the certificate matches the user */
        rv = match_user(x509, user);
        if (rv < 0) { /* match error; abort and return */
          ERR1("match_user() failed: %s", get_error());
			if (!configuration->quiet) {
				pam_syslog(pamh, LOG_ERR, "match_user() failed: %s", get_error());
				pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2334: No matching user"));
				sleep(configuration->err_display_time);
			}
	  goto auth_failed_nopw;
        } else if (rv == 0) { /* match didn't success */
          DBG("certificate is valid but does not match the user");
	  continue; /* try next certificate */
        } else { /* match success */
          DBG("certificate is valid and matches the user");
          chosen_cert = cert_list[i];
          break;
      }
    } /* if is_spaced string */
  } /* for (i=0; i<ncerts; i++) */

  /* now myCert points to our found certificate or null if no user found */
  if (!chosen_cert) {
    ERR("no valid certificate which meets all requirements found");
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR,
				"no valid certificate which meets all requirements found");
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2336: No matching certificate found"));
		sleep(configuration->err_display_time);
	}
    goto auth_failed_nopw;
  }


  /* if signature check is enforced, generate random data, sign and verify */
  if (configuration->policy.signature_policy) {
		pam_prompt(pamh, PAM_TEXT_INFO, NULL, _("Checking signature"));


#ifdef notdef
    rv = get_private_key(ph);
    if (rv != 0) {
      ERR1("get_private_key() failed: %s", get_error());
      if (!configuration->quiet)
        pam_syslog(pamh, LOG_ERR,
                 "get_private_key() failed: %s", get_error());
      goto auth_failed_nopw;
    }
#endif

    /* read random value */
    rv = get_random_value(random_value, sizeof(random_value));
    if (rv != 0) {
      ERR1("get_random_value() failed: %s", get_error());
		if (!configuration->quiet){
			pam_syslog(pamh, LOG_ERR, "get_random_value() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2338: Getting random value failed"));
			sleep(configuration->err_display_time);
		}
      goto auth_failed_nopw;
    }

    /* sign random value */
    signature = NULL;
    rv = sign_value(ph, chosen_cert, random_value, sizeof(random_value),
		    &signature, &signature_length);
    if (rv != 0) {
      ERR1("sign_value() failed: %s", get_error());
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR, "sign_value() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2340: Signing failed"));
			sleep(configuration->err_display_time);
		}
      goto auth_failed_nopw;
    }

    /* verify the signature */
    DBG("verifying signature...");
    rv = verify_signature((X509 *)get_X509_certificate(chosen_cert),
             random_value, sizeof(random_value), signature, signature_length);
    if (signature != NULL) {
      free(signature);
    }
    if (rv != 0) {
      close_pkcs11_session(ph);
      release_pkcs11_module(ph);
      ERR1("verify_signature() failed: %s", get_error());
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR, "verify_signature() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2342: Verifying signature failed"));
			sleep(configuration->err_display_time);
		}
      return PAM_AUTH_ERR;
    }

  } else {
      DBG("Skipping signature check");
  }

  /*
   * fill in the environment variables.
   */
  snprintf(env_temp, sizeof(env_temp) - 1,
	   "PKCS11_LOGIN_TOKEN_NAME=%.*s",
	   (int)((sizeof(env_temp) - 1) - strlen("PKCS11_LOGIN_TOKEN_NAME=")),
	   get_slot_tokenlabel(ph));
  rv = pam_putenv(pamh, env_temp);

  if (rv != PAM_SUCCESS) {
    ERR1("could not put token name in environment: %s",
         pam_strerror(pamh, rv));
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "could not put token name in environment: %s",
           pam_strerror(pamh, rv));
  }

  issuer = cert_info((X509 *)get_X509_certificate(chosen_cert), CERT_ISSUER,
                     ALGORITHM_NULL);
  if (issuer) {
    snprintf(env_temp, sizeof(env_temp) - 1,
	   "PKCS11_LOGIN_CERT_ISSUER=%.*s",
	   (int)((sizeof(env_temp) - 1) - strlen("PKCS11_LOGIN_CERT_ISSUER=")),
	   issuer[0]);
    rv = pam_putenv(pamh, env_temp);
  } else {
    ERR("couldn't get certificate issuer.");
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "couldn't get certificate issuer.");
  }

  if (rv != PAM_SUCCESS) {
    ERR1("could not put cert issuer in environment: %s",
         pam_strerror(pamh, rv));
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "could not put cert issuer in environment: %s",
           pam_strerror(pamh, rv));
  }

  serial = cert_info((X509 *)get_X509_certificate(chosen_cert), CERT_SERIAL,
                     ALGORITHM_NULL);
  if (serial) {
    snprintf(env_temp, sizeof(env_temp) - 1,
	   "PKCS11_LOGIN_CERT_SERIAL=%.*s",
	   (int)((sizeof(env_temp) - 1) - strlen("PKCS11_LOGIN_CERT_SERIAL=")),
	   serial[0]);
    rv = pam_putenv(pamh, env_temp);
  } else {
    ERR("couldn't get certificate serial number.");
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "couldn't get certificate serial number.");
  }

  if (rv != PAM_SUCCESS) {
    ERR1("could not put cert serial in environment: %s",
         pam_strerror(pamh, rv));
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "could not put cert serial in environment: %s",
           pam_strerror(pamh, rv));
  }

  /* unload mapper modules */
  unload_mappers();

  /* close pkcs #11 session */
  rv = close_pkcs11_session(ph);
  if (rv != 0) {
    release_pkcs11_module(ph);
    ERR1("close_pkcs11_session() failed: %s", get_error());
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR, "close_pkcs11_module() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, ("Error 2344: Closing PKCS#11 session failed"));
			sleep(configuration->err_display_time);
		}
    return pkcs11_pam_fail;
  }

  /* release pkcs #11 module */
  DBG("releasing pkcs #11 module...");
  release_pkcs11_module(ph);

  DBG("authentication succeeded");
  return PAM_SUCCESS;

    /* quick and dirty fail exit point */
    memset(password, 0, strlen(password));
    free(password); /* erase and free in-memory password data */

auth_failed_nopw:
    unload_mappers();
    close_pkcs11_session(ph);
    release_pkcs11_module(ph);
    return pkcs11_pam_fail;
}
Example #17
0
void zap_em(FILE* file, int* tzaps[2], int ntzaps, int fzaps[1024], int nfzaps,float mean, float sigma, char zap_mode){
	long long unsigned cur_sample;
	int sample_nbytes;
	int cur_tzap;
	int tz_start;
	int tz_end;
	int c,i;
	int rval;
	char byte;
	int max, min;
	char rndarr[ARRL];
	int mask;
	int rem,stor;
	long fpos;
	long pool_offset;

	printf("Zapping data, replacing with");
	switch(zap_mode){
		case REPLACE_GAUSSIAN:
			printf(" random Gaussian numbers\n");
			break;
		case REPLACE_ZERO:
			printf(" zeros\n");
			break;
		default:
			printf(" randomly selected samples\n");
			break;
	}
	byte=0;
	// rewind the file
	fseek(file,0,SEEK_SET);

	// read the file header
	read_header(file);

	if ((nchans*nbits)%8){
		fprintf(stderr,"ERROR: bytes per sample is not an integer\n");
		exit(1);
	}
	sample_nbytes = (nchans*nbits)/8;
	max=(int)(pow(2,nbits))-1;
	min=0;

	cur_sample=0;
	cur_tzap=0;

	if (cur_tzap < ntzaps){
		tz_start = tzaps[0][0];
		tz_end = tzaps[1][0];
	}

	srand ( time(NULL) );
	if (zap_mode==REPLACE_GAUSSIAN){
		// Generate gaussian random numbers
		rem=0;
		for(c=0;c<ARRL;c++){
			byte=0;
			i=0;
			while(1){
				if(i==8){
					rndarr[c] = byte;
					break;
				}

				rval=(int)rint(get_random_value(mean,sigma));
				stor=rval;
				rval+=rem;
				if(rval > max){
					rem = rval-max;
					rval=max;
				} else if(rval < min){
					rem = rval-min;
					rval=min;
				} else {
					rem=0;
				}
				//printf("%d %d %d\n",rval,stor,rem);
				byte |= (rval << i);
				i+=nbits;
			}
		}
	} else if (zap_mode==REPLACE_ZERO) {
		for(c=0;c<ARRL;c++){
			rndarr[c]=0;
		}
	} else {
		// read the first ARRL bytes for the random sample
		fread(rndarr,1,ARRL,file);
	}

	// rewind the file
	fseek(file,0,SEEK_SET);

	// read the file header
	read_header(file);


	while (cur_tzap < ntzaps){
		while (cur_sample < tz_start){
			// need to fzap, but for now we seek over...
			fseek(file,sample_nbytes,SEEK_CUR);
			cur_sample++;
		}
		if (zap_mode == REPLACE_SAMPLES){
			// check if our random sample pool is up-to-date
			fpos = ftell(file); // the current position in the file
			if (fpos - pool_offset > POOL_VALID && fpos > ARRL){
				// our pool is out of date!
//				fprintf(stderr,"Refilling random pool\n");
				fseek(file,-ARRL,SEEK_CUR);
				fread(rndarr,1,ARRL,file);
			}


		}

		// printf("Zapping: %d -> %d\n",tz_start,tz_end);
		// start zapping
		while (cur_sample < tz_end){
			i=0;
			for(c=0;c<sample_nbytes;c++){
				i=(int)((rand()*(ARRL-1.0))/(float)RAND_MAX);
				byte=rndarr[i];
				fwrite(&byte,1,1,file);
			}
			cur_sample++;
		}
		cur_tzap++;
		if (cur_tzap < ntzaps){
			tz_start = tzaps[0][cur_tzap];
			tz_end = tzaps[1][cur_tzap];
		}
	}
}
Example #18
0
static void person_process(int id)
{
	init_random();
	
	long long int travel_time_array[ITERATIONS];
	
	struct timeval starttime;
	struct timeval stoptime;
	long long int timediff;
		
	int start_floor;
	int destination_floor;
	 
	char buf[4096];
	struct lift_msg m;
	struct lift_msg* reply;
	int travel_count;
	for(travel_count = 0; travel_count < ITERATIONS; travel_count++){
	  /* Create a LIFT_TRAVEL message and send it */
	  m.type = LIFT_TRAVEL;
	  m.person_id = id;
	  int i;
	  for(i = 0; i < NUMBER_MESSAGES; i++){
	    /* Generate ranom floors */
	    start_floor = get_random_value(id, N_FLOORS-1);
	    destination_floor = start_floor;
	    while(destination_floor == start_floor){
	      destination_floor = get_random_value(id, N_FLOORS-1);
	    }

	    m.from_floor[i] = start_floor;
	    m.to_floor[i] = destination_floor;
	  }

	  gettimeofday(&starttime, NULL);//Start timing
	  message_send((char *)&m, sizeof(struct lift_msg), QUEUE_LIFT, 0);
	  
	  /* Wait for LIFT_TRAVEL_DONE message*/
	  message_receive(buf, 4096, QUEUE_FIRSTPERSON + id);
	  gettimeofday(&stoptime, NULL);//Stop timing
	  
	  timediff = (stoptime.tv_sec*1000000ULL + stoptime.tv_usec) -
	    (starttime.tv_sec*1000000ULL + starttime.tv_usec);
	  travel_time_array[travel_count] = timediff;

	  reply = (struct lift_msg *)buf;

	}
	m.type = PROCESS_DONE;
	message_send((char *)&m, sizeof(struct lift_msg), QUEUE_RESULT,0);
	
	while(1){
	  message_receive(buf, 4096, QUEUE_FIRSTPERSON + id);
	  reply = (struct lift_msg *)buf;
	  if(reply->type == WRITE_TO_FILE){
	    int i;
	    FILE *f = fopen("multi_travels.txt", "a");
	    if (f == NULL)
	      {
		printf("Error opening file!\n");
		exit(1);
	      }
	      for(i = 0; i < ITERATIONS; i++){
		fprintf(f, "%d ", (int)travel_time_array[i]);
	      }
	      fprintf(f, "\n");
	    
	      fclose(f);

	    break;
	  }
	}

	
	m.type = WRITE_DONE;
	message_send((char *)&m, sizeof(struct lift_msg), QUEUE_RESULT,0);
	exit(0);
}