Exemple #1
0
int
net_baseline_fsproto_recv (__sock pso, pmda base, pmda threadr, void *data)
{
  mutex_lock (&pso->mutex);

  if (pso->counters.b_read < pso->unit_size)
    {
      pthread_mutex_unlock (&pso->mutex);
      return -2;
    }

  //size_t in_read, blk_sz;

  __fs_sts psts = (__fs_sts ) pso->va_p1;

  psts->data_in += (uint64_t) pso->counters.b_read;

  SHA1_Update (&psts->sha_00.context, pso->buffer0,
	       (size_t) pso->counters.b_read);

  if (time (NULL) - psts->l_stat >= 1)
    {

      uint64_t dpt = psts->data_in - psts->cyc_data_last;
      uint32_t speed = dpt / (time (NULL) - psts->l_stat);
      psts->cyc_data_last = psts->data_in;
      psts->l_stat = time (NULL);

      double p_done = (double) (((double) psts->data_in
	  / (double) psts->hstat.file_size) * 100);

      fprintf (stderr, "STATS: [%d]: recv: %llu/%llu [%.2f%%] [%u K/s] bytes\r",
	       pso->sock, (unsigned long long int) psts->data_in,
	       (unsigned long long int) psts->hstat.file_size, p_done,
	       (unsigned int) speed / 1024);

    }

  if (psts->data_in == psts->hstat.file_size)
    {
      net_proto_reset_to_baseline (pso);
      psts->notify_cb = net_baseline_fsproto_xfer_validate;
      psts->stage = FS_STSS_XFER_R_WSHA;

      if (!SHA1_Final ((unsigned char*) psts->sha_00.value.data,
		       &psts->sha_00.context))
	{
	  print_str (
	      "ERROR: net_baseline_fsproto_recv: [%d]: [%d]: SHA1_Final failed\n",
	      pso->sock, psts->handle);

	  net_baseline_fsproto_recv_validate (pso, F_RQH_OP_FAILED,
					      "XFER FAILED");
	  pthread_mutex_unlock (&pso->mutex);
	  return 1;
	}
      char buffer[128];

      print_str (
	  "D4: net_baseline_fsproto_recv: [%d]: recieved %llu bytes [%s]\n",
	  pso->sock,
	  psts->data_in,
	  bb_to_ascii (psts->sha_00.value.data, sizeof(psts->sha_00.value.data),
		       buffer));
      //pso->flags |= F_OPSOCK_TERM;
    }
  else if (psts->data_in > psts->hstat.file_size)
    {
      print_str (
	  "ERROR: net_baseline_fsproto_recv: [%d]: got too much data: %llu bytes\n",
	  pso->sock, psts->data_in);

      net_proto_reset_to_baseline (pso);
      net_baseline_fsproto_recv_validate (pso, F_RQH_OP_FAILED, "XFER FAILED");
    }
  else if (((uint64_t) psts->hstat.file_size - psts->data_in)
      < (uint64_t) pso->unit_size)
    {
      pso->unit_size = (uint64_t) psts->hstat.file_size - psts->data_in;
      print_str (
	  "D4: net_baseline_fsproto_recv: [%d]: scaling unit size to %llu\n",
	  pso->sock, (uint64_t) pso->unit_size);
    }

  pso->counters.b_read = 0;

  /* }
   else if (pso->counters.b_read > pso->unit_size)
   {
   print_str(
   "ERROR: net_baseline_fsproto_recv: got too much data: %d bytes\n",
   pso->counters.b_read);
   net_proto_reset_to_baseline(pso);
   pso->flags |= F_OPSOCK_TERM;
   }*/

  pthread_mutex_unlock (&pso->mutex);

  return 0;
}
Exemple #2
0
uint32_t TSS_GenPCRInfo(uint32_t pcrmap, unsigned char *pcrinfo, uint32_t *len)
   {
   struct pcrinfo
      {
      uint16_t selsize;
      unsigned char select[TPM_PCR_MASK_SIZE];
      unsigned char relhash[TPM_HASH_SIZE];
      unsigned char crthash[TPM_HASH_SIZE];
      } myinfo;
   uint32_t i;
   int j;
   uint32_t work;
   unsigned char *valarray;
   uint32_t numregs;
   uint32_t ret;
   uint32_t valsize;
   SHA_CTX sha;
   
   
   /* check arguments */
   if (pcrinfo == NULL || len == NULL) return ERR_NULL_ARG;
   /* build pcr selection array */
   work = pcrmap;
   memset(myinfo.select,0,TPM_PCR_MASK_SIZE);
   for (i = 0; i < TPM_PCR_MASK_SIZE; ++i)
      {
      myinfo.select[i] = work & 0x000000FF;
      work = work >> 8;
      }
   /* calculate number of PCR registers requested */
   numregs = 0;
   work = pcrmap;
   for (i = 0; i < (TPM_PCR_MASK_SIZE * 8); ++i)
      {
      if (work & 1) ++numregs;
      work = work >> 1;
      }
   if (numregs == 0)
      {
      *len = 0;
      return 0;
      }
   /* create the array of PCR values */
   valarray = (unsigned char *)malloc(TPM_HASH_SIZE * numregs);
   /* read the PCR values into the value array */
   work = pcrmap;
   j = 0;
   for (i = 0; i < (TPM_PCR_MASK_SIZE * 8); ++i, work = work >> 1)
      {
      if ((work & 1) == 0) continue;
      ret = TPM_PcrRead(i,&(valarray[(j*TPM_HASH_SIZE)]));
      if (ret) return ret;
      ++j;
      }
   myinfo.selsize = ntohs(TPM_PCR_MASK_SIZE);
   valsize = ntohl(numregs * TPM_HASH_SIZE);
   /* calculate composite hash */
   SHA1_Init(&sha);
   SHA1_Update(&sha,&myinfo.selsize,TPM_U16_SIZE);
   SHA1_Update(&sha,&myinfo.select,TPM_PCR_MASK_SIZE);
   SHA1_Update(&sha,&valsize,TPM_U32_SIZE);
   for (i = 0;i < numregs;++i)
      {
      SHA1_Update(&sha,&(valarray[(i*TPM_HASH_SIZE)]),TPM_HASH_SIZE);
      }
   SHA1_Final(myinfo.relhash,&sha);
   memcpy(myinfo.crthash,myinfo.relhash,TPM_HASH_SIZE);
   memcpy(pcrinfo,&myinfo,sizeof (struct pcrinfo));
   *len = sizeof (struct pcrinfo);
   return 0;
   }
Exemple #3
0
void
trap_init(const char *ver)
{
  int r;
  uint8_t digest[20];
  struct sigaction sa, old;
  char path[256];

  SHA_CTX binsum;
  int fd;

  r = readlink("/proc/self/exe", self, sizeof(self) - 1);
  if(r == -1)
    self[0] = 0;
  else
    self[r] = 0;

  memset(digest, 0, sizeof(digest));  
  if((fd = open("/proc/self/exe", O_RDONLY)) != -1) {
    struct stat st;
    if(!fstat(fd, &st)) {
      char *m = malloc(st.st_size);
      if(m != NULL) {
	if(read(fd, m, st.st_size) == st.st_size) {
	  SHA1_Init(&binsum);
	  SHA1_Update(&binsum, (void *)m, st.st_size);
	  SHA1_Final(digest, &binsum);
	}
	free(m);
      }
    }
    close(fd);
  }
  
  snprintf(line1, sizeof(line1),
	   "PRG: %s (%s) "
	   "[%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x"
	   "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x] "
	   "CWD: %s ", ver, tvheadend_version,
	   digest[0],
	   digest[1],
	   digest[2],
	   digest[3],
	   digest[4],
	   digest[5],
	   digest[6],
	   digest[7],
	   digest[8],
	   digest[9],
	   digest[10],
	   digest[11],
	   digest[12],
	   digest[13],
	   digest[14],
	   digest[15],
	   digest[16],
	   digest[17],
	   digest[18],
	   digest[19],
	   getcwd(path, sizeof(path)));

  memcpy(tvh_binshasum, digest, 20);

  dl_iterate_phdr(callback, NULL);
  

  memset(&sa, 0, sizeof(sa));

  sigset_t m;
  sigemptyset(&m);
  sigaddset(&m, SIGSEGV);
  sigaddset(&m, SIGBUS);
  sigaddset(&m, SIGILL);
  sigaddset(&m, SIGABRT);
  sigaddset(&m, SIGFPE);

  sa.sa_sigaction = traphandler;
  sa.sa_flags = SA_SIGINFO | SA_RESETHAND;
  sigaction(SIGSEGV, &sa, &old);
  sigaction(SIGBUS,  &sa, &old);
  sigaction(SIGILL,  &sa, &old);
  sigaction(SIGABRT, &sa, &old);
  sigaction(SIGFPE,  &sa, &old);

  sigprocmask(SIG_UNBLOCK, &m, NULL);
}
int ICACHE_FLASH_ATTR http_ws_handle_connect(http_connection *c) {	

	NODE_DBG("http_ws_handle_connect c =%p",c);

	if(c->state == HTTPD_STATE_ON_URL){
		http_set_save_header(c,HTTP_ORIGIN);	
		http_set_save_header(c,HTTP_CONNECTION);	
		http_set_save_header(c,HTTP_UPGRADE);		
		http_set_save_header(c,HTTP_SEC_WEBSOCKET_KEY);
		http_set_save_header(c,HTTP_SEC_WEBSOCKET_PROTOCOL);
		http_set_save_header(c,HTTP_SEC_WEBSOCKET_VERSION);

		return HTTP_WS_CGI_MORE;
	}

	//wait handshake request complete
	if(c->state != HTTPD_STATE_BODY_END)
		return HTTP_WS_CGI_MORE;


	header * upgrade_header = http_get_header(c,HTTP_UPGRADE);
	header * connection_header = http_get_header(c,HTTP_CONNECTION);
	header * origin_header = http_get_header(c,HTTP_ORIGIN);
	header * key_header = http_get_header(c,HTTP_SEC_WEBSOCKET_KEY);

	if(upgrade_header==NULL) goto badrequest;
	if(connection_header==NULL) goto badrequest;
	if(origin_header==NULL) goto badrequest;
	if(key_header==NULL) goto badrequest;

	NODE_DBG("headers ok");

	if(os_strcasecmp(upgrade_header->value,"websocket")!=0) goto badrequest;

	// Following (https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17)
	//calculate sha1 of concatenetion key+uuid
	uint8_t digest[20]; //sha1 is always 20 byte long
	SHA1_CTX ctx;
	SHA1_Init(&ctx);
	SHA1_Update(&ctx,key_header->value,os_strlen(key_header->value));
	SHA1_Update(&ctx,ws_uuid,os_strlen(ws_uuid));
	SHA1_Final(digest,&ctx);
		
	char base64Digest[31]; // 
	Base64encode(base64Digest,(const char*)digest,20);

	//accept the handshake
	http_SET_HEADER(c,HTTP_UPGRADE,"websocket");
	http_SET_HEADER(c,HTTP_CONNECTION,"Upgrade");
	
	http_SET_HEADER(c,HTTP_WEBSOCKET_ACCEPT,base64Digest);

	http_websocket_HANDSHAKE(c);
	c->handshake_ok=1;

	if(client_connected_callback!=NULL)
		client_connected_callback(c);

	return HTTP_WS_CGI_MORE;

badrequest:
	http_response_BAD_REQUEST(c);
	return HTTP_WS_CGI_DONE;

}
CFDictionaryRef APCreateDictionaryForLicenseData(CFDataRef data)
{
    if (!rsaKey->n || !rsaKey->e)
        return NULL;

    // Make the property list from the data
    CFStringRef errorString = NULL;
    CFPropertyListRef propertyList;
    propertyList = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, data, kCFPropertyListMutableContainers, &errorString);
    if (errorString || CFDictionaryGetTypeID() != CFGetTypeID(propertyList) || !CFPropertyListIsValid(propertyList, kCFPropertyListXMLFormat_v1_0)) {
        if (propertyList)
            CFRelease(propertyList);
        return NULL;
    }

    // Load the signature
    CFMutableDictionaryRef licenseDictionary = (CFMutableDictionaryRef)propertyList;
    if (!CFDictionaryContainsKey(licenseDictionary, CFSTR("Signature"))) {
        CFRelease(licenseDictionary);
        return NULL;
    }

    CFDataRef sigData = CFDictionaryGetValue(licenseDictionary, CFSTR("Signature"));
    CFIndex sigDataLength = CFDataGetLength(sigData);
    UInt8 sigBytes[sigDataLength];
    CFDataGetBytes(sigData, CFRangeMake(0, sigDataLength), sigBytes);
    CFDictionaryRemoveValue(licenseDictionary, CFSTR("Signature"));

    // Decrypt the signature
    int checkDigestMaxSize = RSA_size(rsaKey)-11;
    unsigned char checkDigest[checkDigestMaxSize];

    if (sigDataLength < 0 || sigDataLength > INT_MAX ||
            RSA_public_decrypt((int)sigDataLength, sigBytes, checkDigest, rsaKey, RSA_PKCS1_PADDING) != SHA_DIGEST_LENGTH) {
        CFRelease(licenseDictionary);
        return NULL;
    }

    // Get the license hash
    CFMutableStringRef hashCheck = CFStringCreateMutable(kCFAllocatorDefault,0);
    int hashIndex;
    for (hashIndex = 0; hashIndex < SHA_DIGEST_LENGTH; hashIndex++)
        CFStringAppendFormat(hashCheck, nil, CFSTR("%02x"), checkDigest[hashIndex]);
    APSetHash(hashCheck);
    CFRelease(hashCheck);

    if (blacklist && (CFArrayContainsValue(blacklist, CFRangeMake(0, CFArrayGetCount(blacklist)), hash) == true))
        return NULL;

    // Get the number of elements
    CFIndex count = CFDictionaryGetCount(licenseDictionary);
    // Load the keys and build up the key array
    CFMutableArrayRef keyArray = CFArrayCreateMutable(kCFAllocatorDefault, count, NULL);
    CFStringRef keys[count];
    CFDictionaryGetKeysAndValues(licenseDictionary, (const void**)&keys, NULL);
    int i;
    for (i = 0; i < count; i++)
        CFArrayAppendValue(keyArray, keys[i]);

    // Sort the array
    int context = kCFCompareCaseInsensitive;
    CFArraySortValues(keyArray, CFRangeMake(0, count), (CFComparatorFunction)CFStringCompare, &context);

    // Setup up the hash context
    SHA_CTX ctx;
    SHA1_Init(&ctx);
    // Convert into UTF8 strings
    for (i = 0; i < count; i++)
    {
        char *valueBytes;
        CFIndex valueLengthAsUTF8;
        CFStringRef key = CFArrayGetValueAtIndex(keyArray, i);
        CFStringRef value = CFDictionaryGetValue(licenseDictionary, key);

        // Account for the null terminator
        valueLengthAsUTF8 = CFStringGetMaximumSizeForEncoding(CFStringGetLength(value), kCFStringEncodingUTF8) + 1;
        valueBytes = (char *)malloc(valueLengthAsUTF8);
        CFStringGetCString(value, valueBytes, valueLengthAsUTF8, kCFStringEncodingUTF8);
        SHA1_Update(&ctx, valueBytes, strlen(valueBytes));
        free(valueBytes);
    }
    unsigned char digest[SHA_DIGEST_LENGTH];
    SHA1_Final(digest, &ctx);

    if (keyArray != NULL)
        CFRelease(keyArray);

    // Check if the signature is a match
    for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
        if (checkDigest[i] ^ digest[i]) {
            CFRelease(licenseDictionary);
            return NULL;
        }
    }

    // If it's a match, we return the dictionary; otherwise, we never reach this
    return licenseDictionary;
}
Exemple #6
0
void close8900(AbstractFile* file) {
	unsigned char ivec[16];
	SHA_CTX sha_ctx;
	unsigned char md[20];
	/*int align;*/
	size_t origSize;
	uint32_t cksum;
	Info8900* info = (Info8900*) (file->data);
	
	if(info->dirty) {
		if(info->header.format == 3) {
			/* we need to block-align our data, or AES will break */
			origSize = info->header.sizeOfData;
			/* gotta break abstraction here, because Apple is mean */
			if(((Img2Header*)info->buffer)->signature == IMG2_SIGNATURE) {
				((Img2Header*)info->buffer)->dataLenPadded = ((Img2Header*)info->buffer)->dataLenPadded % 16 == 0 ? ((Img2Header*)info->buffer)->dataLenPadded : ((((Img2Header*)info->buffer)->dataLenPadded/16) + 1) * 16;
				info->header.sizeOfData = ((Img2Header*)info->buffer)->dataLenPadded + sizeof(Img2Header);
				
				cksum = "";//crc32(0, (unsigned char *)info->buffer, 0x64);
				FLIPENDIANLE(cksum);
				((Img2Header*)info->buffer)->header_checksum = cksum;
			}
			
			info->header.sizeOfData = (info->header.sizeOfData) % 16 == 0 ? info->header.sizeOfData : ((info->header.sizeOfData/16) + 1) * 16;
			if(info->header.sizeOfData != origSize) {
				info->buffer = realloc(info->buffer, info->header.sizeOfData);
				memset((void*)((uint8_t*)info->buffer + origSize), 0, info->header.sizeOfData - origSize);
			}
		}
	
		info->header.footerSignatureOffset = info->header.sizeOfData;
		info->header.footerCertOffset = info->header.footerSignatureOffset + 0x80;

		if(info->header.format == 3) {
			memset(ivec, 0, 16);
			AES_cbc_encrypt(info->buffer, info->buffer, info->header.sizeOfData, &(info->encryptKey), ivec, AES_ENCRYPT);
		}
		
		info->file->seek(info->file, sizeof(info->header));
		info->file->write(info->file, info->buffer, info->header.sizeOfData);
		info->file->seek(info->file, sizeof(info->header) + info->header.footerSignatureOffset);
		info->file->write(info->file, info->footerSignature, 0x80);
		info->file->seek(info->file, sizeof(info->header) + info->header.footerCertOffset);

		if(info->exploit) {
			info->footerCertificate[0x8be] = 0x9F;
			info->footerCertificate[0xb08] = 0x55;
		}

		info->file->write(info->file, info->footerCertificate, info->header.footerCertLen);

		unsigned char exploit_data[0x54] = {0};

		if(info->exploit) {
			info->header.footerCertLen = 0xc5e;
			exploit_data[0x30] = 0x01;
			exploit_data[0x50] = 0xEC;
			exploit_data[0x51] = 0x57;
			exploit_data[0x53] = 0x20;
			info->file->write(info->file, exploit_data, sizeof(exploit_data));
		}
		
		flipApple8900Header(&(info->header));
		SHA1_Init(&sha_ctx);
		SHA1_Update(&sha_ctx, &(info->header), 0x40);
		SHA1_Final(md, &sha_ctx);
		
		memset(ivec, 0, 16);
		AES_cbc_encrypt(md, (unsigned char*)&(info->header.headerSignature), 0x10, &(info->encryptKey), ivec, AES_ENCRYPT);
			
		info->file->seek(info->file, 0);
		info->file->write(info->file, &(info->header), sizeof(info->header));
	}
	
	free(info->footerCertificate);
	free(info->buffer);
	info->file->close(info->file);
	free(info);
	free(file);
}
Exemple #7
0
/* content-defined chunking */
int file_chunk_cdc(int fd_src,
                   CDCFileDescriptor *file_descr,
                   SeafileCrypt *crypt,
                   gboolean write_data)
{
    char *buf;
    uint32_t buf_sz;
    SHA_CTX file_ctx;
    CDCDescriptor chunk_descr;
    SHA1_Init (&file_ctx);

    SeafStat sb;
    if (seaf_fstat (fd_src, &sb) < 0) {
        return -1;
    }
    uint64_t expected_size = sb.st_size;

    init_cdc_file_descriptor (fd_src, expected_size, file_descr);
    uint32_t block_min_sz = file_descr->block_min_sz;
    uint32_t block_mask = file_descr->block_sz - 1;

    int fingerprint = 0;
    int offset = 0;
    int ret = 0;
    int tail, cur, rsize;

    buf_sz = file_descr->block_max_sz;
    buf = chunk_descr.block_buf = malloc (buf_sz);
    if (!buf)
        return -1;

    /* buf: a fix-sized buffer.
     * cur: data behind (inclusive) this offset has been scanned.
     *      cur + 1 is the bytes that has been scanned.
     * tail: length of data loaded into memory. buf[tail] is invalid.
     */
    tail = cur = 0;
    while (1) {
        if (cur < block_min_sz) {
            rsize = block_min_sz - cur + READ_SIZE;
        } else {
            rsize = (buf_sz - tail < READ_SIZE) ? (buf_sz - tail) : READ_SIZE;
        }
        ret = readn (fd_src, buf + tail, rsize);
        if (ret < 0) {
            free (buf);
            return -1;
        }
        tail += ret;
        file_descr->file_size += ret;

        if (file_descr->file_size > expected_size) {
            g_warning ("File size changed while chunking.\n");
            free (buf);
            return -1;
        }

        /* We've read all the data in this file. Output the block immediately
         * in two cases:
         * 1. The data left in the file is less than block_min_sz;
         * 2. We cannot find the break value until the end of this file.
         */
        if (tail < block_min_sz || cur >= tail) {
            if (tail > 0) {
                if (file_descr->block_nr == file_descr->max_block_nr) {
                    g_warning ("Block id array is not large enough, bail out.\n");
                    free (buf);
                    return -1;
                }
                WRITE_CDC_BLOCK (tail, write_data);
            }
            break;
        }

        /*
         * A block is at least of size block_min_sz.
         */
        if (cur < block_min_sz - 1)
            cur = block_min_sz - 1;

        while (cur < tail) {
            fingerprint = (cur == block_min_sz - 1) ?
                          finger(buf + cur - BLOCK_WIN_SZ + 1, BLOCK_WIN_SZ) :
                          rolling_finger (fingerprint, BLOCK_WIN_SZ,
                                          *(buf+cur-BLOCK_WIN_SZ), *(buf + cur));

            /* get a chunk, write block info to chunk file */
            if (((fingerprint & block_mask) ==  ((BREAK_VALUE & block_mask)))
                    || cur + 1 >= file_descr->block_max_sz)
            {
                if (file_descr->block_nr == file_descr->max_block_nr) {
                    g_warning ("Block id array is not large enough, bail out.\n");
                    free (buf);
                    return -1;
                }

                WRITE_CDC_BLOCK (cur + 1, write_data);
                break;
            } else {
                cur ++;
            }
        }
    }

    SHA1_Final (file_descr->file_sum, &file_ctx);

    free (buf);

    return 0;
}
JNIEXPORT jobjectArray JNICALL Java_org_exobel_routerkeygen_ThomsonKeygen_thirdDicNative
  (JNIEnv * env, jobject obj , jbyteArray ess , jbyteArray ent, jint size)
{
	int year = 4;
	int week = 1;
	int i = 0 , j = 0;
	char  debug[80];
	char input[13];
	char result[5][11];
	int keys = 0;
	unsigned int sequenceNumber;
	unsigned int inc = 0;
	uint8_t message_digest[20];
	SHA_CTX sha1;
	int a,b,c;

    jclass cls = (*env)->GetObjectClass(env, obj);
    jfieldID fid_s = (*env)->GetFieldID(env, cls, "stopRequested", "Z");
    if ( fid_s == NULL ) {
        return; /* exception already thrown */
    }
    unsigned char stop = (*env)->GetBooleanField(env, obj, fid_s);
    int len = size;
    jbyte *entry_native= (*env)->GetByteArrayElements(env, ent, 0);
    uint8_t * entry = ( uint8_t * )malloc( len * sizeof(uint8_t) );
    for( i = 0; i < len; ++i  )
    {
    	entry[i] = entry_native[i];
    }
    jbyte *e_native= (*env)->GetByteArrayElements(env, ess, 0);
    uint8_t ssid[3];
    ssid[0] = e_native[0];
    ssid[1] = e_native[1];
    ssid[2] = e_native[2];


	input[0] = 'C';
	input[1] = 'P';
	input[2] = '0';
	sequenceNumber = 0;
	for( i = 0; i < len; i+=2  )
	{
		sequenceNumber += ( entry[i + 0 ]<<8 ) |  entry[i + 1 ];
		for ( j = 0 ; j < 18 ; ++j )
		{
			inc = j* ( 36*36*36*6*3);
			year = ( (sequenceNumber+inc) / ( 36*36*36 )% 6) + 4 ;
			week = (sequenceNumber+inc) / ( 36*36*36*6 )  + 1 ;
			c = sequenceNumber % 36;
			b = sequenceNumber/36 % 36;
			a = sequenceNumber/(36*36) % 36;

			input[3] = '0' + year % 10 ;
			input[4] = '0' + week / 10;
			input[5] = '0' + week % 10;
			input[6] = charectbytes0[a];
			input[7] = charectbytes1[a];
			input[8] = charectbytes0[b];
			input[9] = charectbytes1[b];
			input[10] = charectbytes0[c];
			input[11] = charectbytes1[c];
			SHA1_Init(&sha1);
			SHA1_Update(&sha1 ,(const void *) input , 12 );
			SHA1_Final(message_digest , &sha1 );
			if( ( memcmp(&message_digest[17],&ssid[0],3) == 0) ){
			sprintf( result[keys++], "%02X%02X%02X%02X%02X\0" , message_digest[0], message_digest[1] ,
								message_digest[2] , message_digest[3], message_digest[4] );
			}
		}
	}
	jobjectArray ret;
	ret= (jobjectArray)(*env)->NewObjectArray(env,keys, (*env)->FindClass(env,"java/lang/String"),0);
	for ( i = 0; i < keys ; ++i )
		(*env)->SetObjectArrayElement(env,ret,i,(*env)->NewStringUTF(env, result[i]));
	(*env)->ReleaseByteArrayElements(env, ess, e_native, 0);
 	return ret;
}
Exemple #9
0
int asr_send_payload(asr_client_t asr, const char* filesystem) {
	char data[ASR_PAYLOAD_PACKET_SIZE];
	FILE* file = NULL;
	off_t i, length, bytes = 0;
	double progress = 0;

	file = fopen(filesystem, "rb");
	if (file == NULL) {
		error("ERROR: Unable to open filesystem image %s: %s\n",
		      filesystem, strerror(errno));
		return -1;
	}

	fseeko(file, 0, SEEK_END);
	length = ftello(file);
	fseeko(file, 0, SEEK_SET);

	int chunk = 0;
	int add_checksum = 0;

	SHA_CTX sha1;

	if (asr->checksum_chunks) {
		SHA1_Init(&sha1);
	}

	int size = 0;
	for (i = length; i > 0; i -= size) {
		size = ASR_PAYLOAD_PACKET_SIZE;
		if (i < ASR_PAYLOAD_PACKET_SIZE) {
			size = i;
		}

		if (add_checksum) {
			add_checksum = 0;
		}

		if (asr->checksum_chunks && ((chunk + size) >= ASR_CHECKSUM_CHUNK_SIZE)) {
			// reduce packet size to match checksum chunk size
			size -= ((chunk + size) - ASR_CHECKSUM_CHUNK_SIZE);
			add_checksum = 1;
		}

		if (fread(data, 1, size, file) != (unsigned int) size) {
			error("Error reading filesystem\n");
			fclose(file);
			return -1;
		}

		if (asr_send_buffer(asr, data, size) < 0) {
			error("ERROR: Unable to send filesystem payload\n");
			fclose(file);
			return -1;
		}

		if (asr->checksum_chunks) {
			SHA1_Update(&sha1, data, size);
			chunk += size;

			if (add_checksum) {
				// get sha1 of last chunk
				SHA1_Final((unsigned char*)data, &sha1);

				// send checksum
				if (asr_send_buffer(asr, data, 20) < 0) {
					error("ERROR: Unable to send chunk checksum\n");
					fclose(file);
					return -1;
				}

				// reset SHA1 context
				SHA1_Init(&sha1);

				// reset chunk byte counter
				chunk = 0;
			}
		}

		bytes += size;
		progress = ((double)bytes / (double)length);
		if (asr->progress_cb && ((int)(progress*100) > asr->lastprogress)) {
			asr->progress_cb(progress, asr->progress_cb_data);
			asr->lastprogress = (int)(progress*100);
		}
	}

	// if last chunk wasn't terminated with a checksum we do it here
	if (asr->checksum_chunks && !add_checksum) {
		// get sha1 of last chunk
		SHA1_Final((unsigned char*)data, &sha1);

		// send checksum
		if (asr_send_buffer(asr, data, 20) < 0) {
			error("ERROR: Unable to send chunk checksum\n");
			fclose(file);
			return -1;
		}
	}

	fclose(file);
	return 0;
}
Exemple #10
0
// don't forward the first argument
void CL_ForwardToServer_f (void) {
// Added by VVD {
	char		*server_string, client_time_str[9];
	int		i, server_string_len;
	extern cvar_t	cl_crypt_rcon;
	time_t		client_time;
// Added by VVD }

	if (cls.mvdplayback == QTV_PLAYBACK) {
		QTV_Cl_ForwardToServer_f();
		return;
	}

	if (cls.state == ca_disconnected) {
		Com_Printf ("Can't \"%s\", not connected\n", Cmd_Argv(0));
		return;
	}

	if (cls.demoplayback)
		return;		// not really connected

	if (Cmd_Argc() > 1) {
		if (strcasecmp(Cmd_Argv(1), "snap") == 0) {
			SCR_RSShot_f ();
			return;
		}

//bliP ->
		if (strcasecmp(Cmd_Argv(1), "fileul") == 0) {
			CL_StartFileUpload ();
			return;
		}
//<-
		MSG_WriteByte (&cls.netchan.message, clc_stringcmd);
/* johnnycz: disabled due to security reasons -- fixme
		if (strcasecmp(Cmd_Argv(1), "download") == 0 && Cmd_Argc() > 2)
		{
			strlcpy(cls.downloadname, Cmd_Argv(2), sizeof(cls.downloadname));
			COM_StripExtension(cls.downloadname, cls.downloadtempname);
			strlcat(cls.downloadtempname, ".tmp", sizeof(cls.downloadtempname));
			cls.downloadtype = dl_single;
			//snprintf (cls.downloadname, sizeof(cls.downloadname), "%s", Cmd_Argv(2));
			//strlcpy (cls.downloadtempname, cls.downloadname, sizeof(cls.downloadtempname));
		}
*/
// Added by VVD {
		if (cl_crypt_rcon.value && strcasecmp(Cmd_Argv(1), "techlogin") == 0 && Cmd_Argc() > 2)
		{
			time(&client_time);
			for (client_time_str[0] = i = 0; i < sizeof(client_time); i++) {
				char tmp[3];
				snprintf(tmp, sizeof(tmp), "%02X", (unsigned int)((client_time >> (i * 8)) & 0xFF));
				strlcat(client_time_str, tmp, sizeof(client_time_str));
			}

			server_string_len = Cmd_Argc() + strlen(Cmd_Argv(1)) + DIGEST_SIZE * 2 + 16;
			for (i = 3; i < Cmd_Argc(); ++i)
				server_string_len += strlen(Cmd_Argv(i));
			server_string = (char *) Q_malloc(server_string_len);

			SHA1_Init();
			SHA1_Update((unsigned char *)Cmd_Argv(1));
			SHA1_Update((unsigned char *)" ");
			SHA1_Update((unsigned char *)Cmd_Argv(2));
			SHA1_Update((unsigned char *)client_time_str);
			SHA1_Update((unsigned char *)" ");
			for (i = 3; i < Cmd_Argc(); ++i)
			{
				SHA1_Update((unsigned char *)Cmd_Argv(i));
				SHA1_Update((unsigned char *)" ");
			}

			snprintf(server_string, server_string_len, "%s %s%s ",
				Cmd_Argv(1), SHA1_Final(), client_time_str);
			for (i = 3; i < Cmd_Argc(); ++i)
			{
				strlcat(server_string, Cmd_Argv(i), server_string_len);
				strlcat(server_string, " ", server_string_len);
			}
			SZ_Print (&cls.netchan.message, server_string);
			Q_free(server_string);
		}
		else
Exemple #11
0
int
main(int argc, char *argv[])
{
#if HAVE_OPENSSL_SHA_H
	unsigned char boot_aggregate[SHA_DIGEST_LENGTH];
	struct {
		struct {
			u_int32_t pcr;
			int type;
			unsigned char digest[SHA_DIGEST_LENGTH];
			u_int16_t len;
		} header;
		unsigned char data[MAX_EVENT_DATA_SIZE];
	} event;
	struct {
		unsigned char digest[SHA_DIGEST_LENGTH];
	} pcr[NUM_PCRS];
	FILE *fp;
	int i;
	int debug = 0;
	SHA_CTX c;

	if (argc != 2) {
		printf("format: %s binary_bios_measurement file\n", argv[0]);
		return 1;
	}
	fp = fopen(argv[1], "r");
	if (!fp) {
		perror("unable to open pcr file\n");
		return 1;
	}

	/* Initialize psuedo PCR registers 0 - 7 */
	for ( i = 0; i < NUM_PCRS; i++)
		memset(&pcr[i].digest, 0, SHA_DIGEST_LENGTH);

	/* Extend the pseudo PCRs with the event digest */
	while (fread(&event, sizeof(event.header), 1, fp)) {
		if (debug) {
			printf("%03u ", event.header.pcr);
			display_sha1_digest(event.header.digest);
		}
		SHA1_Init(&c);
		SHA1_Update(&c, pcr[event.header.pcr].digest, 20);
		SHA1_Update(&c, event.header.digest, 20);
		SHA1_Final(pcr[event.header.pcr].digest, &c);
		if (event.header.len > MAX_EVENT_DATA_SIZE) {
			printf("Error event too long");
			break;
		}
		fread(event.data, event.header.len, 1, fp);
	}
	fclose(fp);

	/* Extend the boot aggregate with the pseudo PCR digest values */
	memset(&boot_aggregate, 0, SHA_DIGEST_LENGTH);
	SHA1_Init(&c);
	for (i = 0; i < NUM_PCRS; i++) {
		if (debug) {
			printf("PCR-%2.2x: ", i);
			display_sha1_digest(pcr[i].digest);
		}
		SHA1_Update(&c, pcr[i].digest, 20);
	}
	SHA1_Final(boot_aggregate, &c);

	printf("boot_aggregate:");
	display_sha1_digest(boot_aggregate);
#else
	tst_resm(TCONF, "System doesn't have openssl/sha.h");
#endif
	tst_exit();
}
Exemple #12
0
/**
 * Construct a new x509 object.
 * @return 0 if ok. < 0 if there was a problem.
 */
int x509_new(const uint8_t *cert, int *len, X509_CTX **ctx)
{
    int begin_tbs, end_tbs, begin_spki, end_spki;
    int ret = X509_NOT_OK, offset = 0, cert_size = 0;
    int version = 0;
    X509_CTX *x509_ctx;
#ifdef CONFIG_SSL_CERT_VERIFICATION /* only care if doing verification */
    BI_CTX *bi_ctx;
#endif

    *ctx = (X509_CTX *)calloc(1, sizeof(X509_CTX));
    x509_ctx = *ctx;

    /* get the certificate size */
    asn1_skip_obj(cert, &cert_size, ASN1_SEQUENCE); 

    if (asn1_next_obj(cert, &offset, ASN1_SEQUENCE) < 0)
        goto end_cert;

    begin_tbs = offset;         /* start of the tbs */
    end_tbs = begin_tbs;        /* work out the end of the tbs */
    asn1_skip_obj(cert, &end_tbs, ASN1_SEQUENCE);

    if (asn1_next_obj(cert, &offset, ASN1_SEQUENCE) < 0)
        goto end_cert;

    /* optional version */
    if (cert[offset] == ASN1_EXPLICIT_TAG && 
            asn1_version(cert, &offset, &version) == X509_NOT_OK)
        goto end_cert;

    if (asn1_skip_obj(cert, &offset, ASN1_INTEGER) || /* serial number */ 
            asn1_next_obj(cert, &offset, ASN1_SEQUENCE) < 0)
        goto end_cert;

    /* make sure the signature is ok */
    if (asn1_signature_type(cert, &offset, x509_ctx))
    {
        ret = X509_VFY_ERROR_UNSUPPORTED_DIGEST;
        goto end_cert;
    }

    if (asn1_name(cert, &offset, x509_ctx->ca_cert_dn) || 
            asn1_validity(cert, &offset, x509_ctx) ||
            asn1_name(cert, &offset, x509_ctx->cert_dn))
    {
        goto end_cert;
    }
    begin_spki = offset;
    if (asn1_public_key(cert, &offset, x509_ctx))
        goto end_cert;
    end_spki = offset;

    x509_ctx->fingerprint = malloc(SHA1_SIZE);
    SHA1_CTX sha_fp_ctx;
    SHA1_Init(&sha_fp_ctx);
    SHA1_Update(&sha_fp_ctx, &cert[0], cert_size);
    SHA1_Final(x509_ctx->fingerprint, &sha_fp_ctx);

    x509_ctx->spki_sha256 = malloc(SHA256_SIZE);
    SHA256_CTX spki_hash_ctx;
    SHA256_Init(&spki_hash_ctx);
    SHA256_Update(&spki_hash_ctx, &cert[begin_spki], end_spki-begin_spki);
    SHA256_Final(x509_ctx->spki_sha256, &spki_hash_ctx);

#ifdef CONFIG_SSL_CERT_VERIFICATION /* only care if doing verification */
    bi_ctx = x509_ctx->rsa_ctx->bi_ctx;

    /* use the appropriate signature algorithm */
    switch (x509_ctx->sig_type)
    {
        case SIG_TYPE_MD5:
        {
            MD5_CTX md5_ctx;
            uint8_t md5_dgst[MD5_SIZE];
            MD5_Init(&md5_ctx);
            MD5_Update(&md5_ctx, &cert[begin_tbs], end_tbs-begin_tbs);
            MD5_Final(md5_dgst, &md5_ctx);
            x509_ctx->digest = bi_import(bi_ctx, md5_dgst, MD5_SIZE);
        }
            break;

        case SIG_TYPE_SHA1:
        {
            SHA1_CTX sha_ctx;
            uint8_t sha_dgst[SHA1_SIZE];
            SHA1_Init(&sha_ctx);
            SHA1_Update(&sha_ctx, &cert[begin_tbs], end_tbs-begin_tbs);
            SHA1_Final(sha_dgst, &sha_ctx);
            x509_ctx->digest = bi_import(bi_ctx, sha_dgst, SHA1_SIZE);
        }
            break;

        case SIG_TYPE_SHA256:
        {
            SHA256_CTX sha256_ctx;
            uint8_t sha256_dgst[SHA256_SIZE];
            SHA256_Init(&sha256_ctx);
            SHA256_Update(&sha256_ctx, &cert[begin_tbs], end_tbs-begin_tbs);
            SHA256_Final(sha256_dgst, &sha256_ctx);
            x509_ctx->digest = bi_import(bi_ctx, sha256_dgst, SHA256_SIZE);
        }
            break;

        case SIG_TYPE_SHA384:
        {
            SHA384_CTX sha384_ctx;
            uint8_t sha384_dgst[SHA384_SIZE];
            SHA384_Init(&sha384_ctx);
            SHA384_Update(&sha384_ctx, &cert[begin_tbs], end_tbs-begin_tbs);
            SHA384_Final(sha384_dgst, &sha384_ctx);
            x509_ctx->digest = bi_import(bi_ctx, sha384_dgst, SHA384_SIZE);
        }
            break;

        case SIG_TYPE_SHA512:
        {
            SHA512_CTX sha512_ctx;
            uint8_t sha512_dgst[SHA512_SIZE];
            SHA512_Init(&sha512_ctx);
            SHA512_Update(&sha512_ctx, &cert[begin_tbs], end_tbs-begin_tbs);
            SHA512_Final(sha512_dgst, &sha512_ctx);
            x509_ctx->digest = bi_import(bi_ctx, sha512_dgst, SHA512_SIZE);
        }
            break;
    }

    if (version == 2 && asn1_next_obj(cert, &offset, ASN1_V3_DATA) > 0)
    {
        x509_v3_subject_alt_name(cert, offset, x509_ctx);
        x509_v3_basic_constraints(cert, offset, x509_ctx);
        x509_v3_key_usage(cert, offset, x509_ctx);
    }

    offset = end_tbs;   /* skip the rest of v3 data */
    if (asn1_skip_obj(cert, &offset, ASN1_SEQUENCE) || 
            asn1_signature(cert, &offset, x509_ctx))
        goto end_cert;

    /* Saves a few bytes of memory */
    bi_clear_cache(bi_ctx);
#endif
    ret = X509_OK;
end_cert:
    if (len)
    {
        *len = cert_size;
    }

    if (ret)
    {
#ifdef CONFIG_SSL_FULL_MODE
        char buff[64];
        printf("Error: Invalid X509 ASN.1 file (%s)\n",
                        x509_display_error(ret, buff));
#endif
        x509_free(x509_ctx);
        *ctx = NULL;
    }

    return ret;
}
Exemple #13
0
void binary_scan(char* binary){

	printf("Scanning %s ...\n", binary);

	char *bin_arr = NULL;
	unsigned int bin_sz = 0;

	int ret = read_binary(binary, &bin_arr, &bin_sz);
	if (ret < 0)
		return;

	//Printing Signature of binary. Random 20 bytes inside binary.
#if 0
	int i;
	for(i=bin_sz-20;i<bin_sz-0;i++){
		printf("%02x ", bin_arr[i]&0xff);
	}
	printf("\n");
	printf("Size of %s: %d bytes.\n", binary, bin_sz);
#endif

	unsigned char sha1[SHA_DIGEST_LENGTH];
	SHA_CTX ctx;
	SHA1_Init(&ctx);
	SHA1_Update(&ctx, bin_arr, bin_sz);
	SHA1_Final(sha1, &ctx);
#if 0
	printf("SHA1 of %s: ", binary);
	for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
		printf("%02x", sha1[i]);
	}
	printf("\n");
#endif
	char* details;
	ret = check_in_whitelist(sha1);
	if (ret < 0) {
		printf("Failed to check whitelist\n");
		sprintf(msg,"[%s] failed to check whitelist\n",binary);
		log_to_file(msg);
	} else if (ret == 0) {
		printf("Present in Whitelist. Binary is safe to execute.\n");
		sprintf(msg,"[%s]Present in Whitelist. Binary is safe to execute.\n",binary);
		log_to_file(msg);
		return;
	}
	ret = check_in_blacklist(binary, &details);
	if (ret < 0) {
		printf("Failed to check blacklist. Antivirus check failed.\n");
		sprintf(msg,"[%s] failed to check blacklist. Antivirus check failed\n",binary);
		log_to_file(msg);
		return;
	} else if (ret == 0) {
		printf("Virus Found! Details:%s", details);
		/* DO NOT CHANGE BELOW LINE WITHOUT WRITTEN PERMISSION*/
		sprintf(msg,"[%s]Virus Found! Details:%s\n",binary, details);
		log_to_file(msg);
		return;
	} 

	printf("File didn't match with any of virus database. Not likely a virus.\n");
	printf(msg,"[%s] File didn't match with any of virus database. Not likely a virus.\n",binary);
	log_to_file(msg);
}
Exemple #14
0
//--------------------------------------------------
// Calculates files SHA1 digest
// szFileName - file name
// nDigestType - digest type. Supports only SHA1 (0)
// pDigestBuf - buffer to store the digest
// nDigestLen - buffer size, must be at least 20
//				will be updated by actual digest length
// lFileLen - pointer to a buffer where to store the file length
// returns error code or ERR_OK for success
//--------------------------------------------------
EXP_OPTION int calculateFileDigest(const char* szFileName, int nDigestType,
				   byte* pDigestBuf, int* nDigestLen, long* lFileLen)
{
  int err = ERR_OK;
  byte buf[FILE_BUFSIZE];
  int i;
  FILE *f = NULL;

  RETURN_IF_NULL_PARAM(szFileName);
  RETURN_IF_NULL_PARAM(pDigestBuf);
  RETURN_IF_NULL_PARAM(nDigestLen);
  RETURN_IF_NULL_PARAM(lFileLen);

  memset(pDigestBuf, 0, *nDigestLen);
  if(nDigestType == DIGEST_SHA1) {
    if(*nDigestLen >= SHA_DIGEST_LENGTH) {
      SHA_CTX ctx;
			*nDigestLen = SHA_DIGEST_LENGTH;
      if((f = fopen(szFileName,"rb")) != NULL) {
	//byte *data,*temp_data;
	SHA1_Init(&ctx);
	*lFileLen = 0;
	for (;;) {
	  i = fread(buf, sizeof(char), FILE_BUFSIZE, f);
	  if (i <= 0) break;
	  *lFileLen += i;
	  SHA1_Update(&ctx, buf, (unsigned long)i);
	}
	SHA1_Final(pDigestBuf,&ctx);
	fclose(f);
      } // if - fopen
      else
	err = ERR_FILE_READ;
    } 
    else
      err = ERR_DIGEST_LEN;
  } //AM 22.04.08
	else if(nDigestType == DIGEST_SHA256){
    if(*nDigestLen >= SHA_DIGEST_LENGTH) {
      SHA256_CTX ctx;
			*nDigestLen = SHA256_DIGEST_LENGTH;
      if((f = fopen(szFileName,"rb")) != NULL) {
				//byte *data,*temp_data;
				SHA256_Init(&ctx);
				*lFileLen = 0;
				for (;;) {
					i = fread(buf, sizeof(char), FILE_BUFSIZE, f);
					if (i <= 0) break;
					*lFileLen += i;
					SHA256_Update(&ctx, buf, (unsigned long)i);
				}
			SHA256_Final(pDigestBuf,&ctx);
			fclose(f);
			} // if - fopen
      else
				err = ERR_FILE_READ;
    } 
    else
      err = ERR_DIGEST_LEN;
  }
  else
    err = ERR_UNSUPPORTED_DIGEST;
  if (err != ERR_OK) SET_LAST_ERROR(err);
  return err;
}
Exemple #15
0
static tr_bool
verifyTorrent( tr_torrent * tor, tr_bool * stopFlag )
{
    time_t end;
    SHA_CTX sha;
    int fd = -1;
    int64_t filePos = 0;
    tr_bool changed = 0;
    tr_bool hadPiece = 0;
    time_t lastSleptAt = 0;
    uint32_t piecePos = 0;
    tr_file_index_t fileIndex = 0;
    tr_file_index_t prevFileIndex = !fileIndex;
    tr_piece_index_t pieceIndex = 0;
    const time_t begin = tr_time( );
    const size_t buflen = 1024 * 128; /* 128 KiB buffer */
    uint8_t * buffer = tr_valloc( buflen );

    SHA1_Init( &sha );

    tr_tordbg( tor, "%s", "verifying torrent..." );
    tr_torrentSetChecked( tor, 0 );
    while( !*stopFlag && ( pieceIndex < tor->info.pieceCount ) )
    {
        uint32_t leftInPiece;
        uint32_t bytesThisPass;
        uint64_t leftInFile;
        const tr_file * file = &tor->info.files[fileIndex];

        /* if we're starting a new piece... */
        if( piecePos == 0 )
            hadPiece = tr_cpPieceIsComplete( &tor->completion, pieceIndex );

        /* if we're starting a new file... */
        if( !filePos && (fd<0) && (fileIndex!=prevFileIndex) )
        {
            char * filename = tr_torrentFindFile( tor, fileIndex );
            fd = filename == NULL ? -1 : tr_open_file_for_scanning( filename );
            tr_free( filename );
            prevFileIndex = fileIndex;
        }

        /* figure out how much we can read this pass */
        leftInPiece = tr_torPieceCountBytes( tor, pieceIndex ) - piecePos;
        leftInFile = file->length - filePos;
        bytesThisPass = MIN( leftInFile, leftInPiece );
        bytesThisPass = MIN( bytesThisPass, buflen );

        /* read a bit */
        if( fd >= 0 ) {
            const ssize_t numRead = tr_pread( fd, buffer, bytesThisPass, filePos );
            if( numRead > 0 ) {
                bytesThisPass = (uint32_t)numRead;
                SHA1_Update( &sha, buffer, bytesThisPass );
#if defined HAVE_POSIX_FADVISE && defined POSIX_FADV_DONTNEED
                posix_fadvise( fd, filePos, bytesThisPass, POSIX_FADV_DONTNEED );
#endif
            }
        }

        /* move our offsets */
        leftInPiece -= bytesThisPass;
        leftInFile -= bytesThisPass;
        piecePos += bytesThisPass;
        filePos += bytesThisPass;

        /* if we're finishing a piece... */
        if( leftInPiece == 0 )
        {
            time_t now;
            tr_bool hasPiece;
            uint8_t hash[SHA_DIGEST_LENGTH];

            SHA1_Final( hash, &sha );
            hasPiece = !memcmp( hash, tor->info.pieces[pieceIndex].hash, SHA_DIGEST_LENGTH );

            if( hasPiece || hadPiece ) {
                tr_torrentSetHasPiece( tor, pieceIndex, hasPiece );
                changed |= hasPiece != hadPiece;
            }
            tr_torrentSetPieceChecked( tor, pieceIndex );
            now = tr_time( );
            tor->anyDate = now;

            /* sleeping even just a few msec per second goes a long
             * way towards reducing IO load... */
            if( lastSleptAt != now ) {
                lastSleptAt = now;
                tr_wait_msec( MSEC_TO_SLEEP_PER_SECOND_DURING_VERIFY );
            }

            SHA1_Init( &sha );
            ++pieceIndex;
            piecePos = 0;
        }

        /* if we're finishing a file... */
        if( leftInFile == 0 )
        {
            if( fd >= 0 ) { tr_close_file( fd ); fd = -1; }
            ++fileIndex;
            filePos = 0;
        }
    }

    /* cleanup */
    if( fd >= 0 )
        tr_close_file( fd );
    free( buffer );

    /* stopwatch */
    end = tr_time( );
    tr_tordbg( tor, "Verification is done. It took %d seconds to verify %"PRIu64" bytes (%"PRIu64" bytes per second)",
               (int)(end-begin), tor->info.totalSize,
               (uint64_t)(tor->info.totalSize/(1+(end-begin))) );

    return changed;
}
Exemple #16
0
void Sha1Hash::Finalize(void)
{
    SHA1_Final(mDigest, &mC);
}
                _SCAPI_NOT_CONFIGURED
#endif                          /* */
/*
 * sc_hash(): a generic wrapper around whatever hashing package we are using.
 * 
 * IN:
 * hashtype    - oid pointer to a hash type
 * hashtypelen - length of oid pointer
 * buf         - u_char buffer to be hashed
 * buf_len     - integer length of buf data
 * MAC_len     - length of the passed MAC buffer size.
 * 
 * OUT:    
 * MAC         - pre-malloced space to store hash output.
 * MAC_len     - length of MAC output to the MAC buffer.
 * 
 * Returns:
 * SNMPERR_SUCCESS              Success.
 * SNMP_SC_GENERAL_FAILURE      Any error.
 */
int
sc_hash(const oid * hashtype, size_t hashtypelen, const u_char * buf,
        size_t buf_len, u_char * MAC, size_t * MAC_len)
#if defined(NETSNMP_USE_INTERNAL_MD5) || defined(NETSNMP_USE_OPENSSL) || defined(NETSNMP_USE_PKCS11) || defined(NETSNMP_USE_INTERNAL_CRYPTO)
{
#if defined(NETSNMP_USE_OPENSSL) || defined(NETSNMP_USE_PKCS11) || defined(NETSNMP_USE_INTERNAL_CRYPTO)
    int            rval = SNMPERR_SUCCESS;
    unsigned int   tmp_len;
#endif
    int            ret;

#ifdef NETSNMP_USE_OPENSSL
    const EVP_MD   *hashfn;
    EVP_MD_CTX     ctx, *cptr;
#endif
#ifdef NETSNMP_USE_INTERNAL_CRYPTO
    MD5_CTX        cmd5;
    SHA_CTX        csha1;
#endif
    DEBUGTRACE;

    if (hashtype == NULL || buf == NULL || buf_len <= 0 ||
        MAC == NULL || MAC_len == NULL )
        return (SNMPERR_GENERR);
    ret = sc_get_properlength(hashtype, hashtypelen);
    if (( ret < 0 ) || (*MAC_len < (size_t)ret ))
        return (SNMPERR_GENERR);

#ifdef NETSNMP_USE_OPENSSL
    /*
     * Determine transform type.
     */
#ifndef NETSNMP_DISABLE_MD5
    if (ISTRANSFORM(hashtype, HMACMD5Auth)) {
        hashfn = (const EVP_MD *) EVP_md5();
    } else
#endif
        if (ISTRANSFORM(hashtype, HMACSHA1Auth)) {
        hashfn = (const EVP_MD *) EVP_sha1();
    } else {
        return (SNMPERR_GENERR);
    }

/** initialize the pointer */
    memset(&ctx, 0, sizeof(ctx));
    cptr = &ctx;
#if defined(OLD_DES)
    EVP_DigestInit(cptr, hashfn);
#else /* !OLD_DES */
    /* this is needed if the runtime library is different than the compiled
       library since the openssl versions are very different. */
    if (SSLeay() < 0x907000) {
        /* the old version of the struct was bigger and thus more
           memory is needed. should be 152, but we use 256 for safety. */
        cptr = (EVP_MD_CTX *)malloc(256);
        EVP_DigestInit(cptr, hashfn);
    } else {
        EVP_MD_CTX_init(cptr);
        EVP_DigestInit(cptr, hashfn);
    }
#endif

/** pass the data */
    EVP_DigestUpdate(cptr, buf, buf_len);

/** do the final pass */
#if defined(OLD_DES)
    EVP_DigestFinal(cptr, MAC, &tmp_len);
    *MAC_len = tmp_len;
#else /* !OLD_DES */
    if (SSLeay() < 0x907000) {
        EVP_DigestFinal(cptr, MAC, &tmp_len);
        *MAC_len = tmp_len;
        free(cptr);
    } else {
        EVP_DigestFinal_ex(cptr, MAC, &tmp_len);
        *MAC_len = tmp_len;
        EVP_MD_CTX_cleanup(cptr);
    }
#endif                          /* OLD_DES */
    return (rval);

#elif NETSNMP_USE_INTERNAL_CRYPTO
#ifndef NETSNMP_DISABLE_MD5
    if (ISTRANSFORM(hashtype, HMACMD5Auth)) {
        if (*MAC_len < MD5_DIGEST_LENGTH)
            return (SNMPERR_GENERR);      /* the buffer isn't big enough */
	MD5_Init(&cmd5);
        MD5_Update(&cmd5, buf, buf_len);
        MD5_Final(MAC, &cmd5);
        *MAC_len = MD5_DIGEST_LENGTH;
    } else 
#endif
    if (ISTRANSFORM(hashtype, HMACSHA1Auth)) {
        if (*MAC_len < SHA_DIGEST_LENGTH)
            return (SNMPERR_GENERR);      /* the buffer isn't big enough */
	SHA1_Init(&csha1);
        SHA1_Update(&csha1, buf, buf_len);
        SHA1_Final(MAC, &csha1);
        *MAC_len = SHA_DIGEST_LENGTH;
            
    } else {
        return (SNMPERR_GENERR);
    }
    return (rval);
#elif NETSNMP_USE_PKCS11                  /* NETSNMP_USE_PKCS11 */

#ifndef NETSNMP_DISABLE_MD5
    if (ISTRANSFORM(hashtype, HMACMD5Auth)) {
	rval = pkcs_digest(CKM_MD5, buf, buf_len, MAC, &tmp_len);
        *MAC_len = tmp_len;
    } else
#endif
        if (ISTRANSFORM(hashtype, HMACSHA1Auth)) {
	rval = pkcs_digest(CKM_SHA_1, buf, buf_len, MAC, &tmp_len);
        *MAC_len = tmp_len;
    } else {
        return (SNMPERR_GENERR);
    }

     return (rval);

#else                           /* NETSNMP_USE_INTERNAL_MD5 */

    if (MDchecksum(buf, buf_len, MAC, *MAC_len)) {
        return SNMPERR_GENERR;
    }
    if (*MAC_len > 16)
        *MAC_len = 16;
    return SNMPERR_SUCCESS;

#endif                          /* NETSNMP_USE_OPENSSL */
}
Exemple #18
0
void crypto_sha1_final(CryptoSha1 sha1, BYTE* out_data)
{
	SHA1_Final(out_data, &sha1->sha_ctx);
	free(sha1);
}
int ssl_test_rc4(int argc, char *argv[])
	{
	int i,err=0;
	int j;
	unsigned char *p;
	RC4_KEY key;
	unsigned char obuf[512];

	for (i=0; i<6; i++)
		{
		RC4_set_key(&key,keys[i][0],&(keys[i][1]));
		TINYCLR_SSL_MEMSET(obuf,0x00,sizeof(obuf));
		RC4(&key,data_len[i],&(data[i][0]),obuf);
		if (TINYCLR_SSL_MEMCMP(obuf,output[i],data_len[i]+1) != 0)
			{
			TINYCLR_SSL_PRINTF("error calculating RC4\n");
			TINYCLR_SSL_PRINTF("output:");
			for (j=0; j<data_len[i]+1; j++)
				TINYCLR_SSL_PRINTF(" %02x",obuf[j]);
			TINYCLR_SSL_PRINTF("\n");
			TINYCLR_SSL_PRINTF("expect:");
			p= &(output[i][0]);
			for (j=0; j<data_len[i]+1; j++)
				TINYCLR_SSL_PRINTF(" %02x",*(p++));
			TINYCLR_SSL_PRINTF("\n");
			err++;
			}
		else
			TINYCLR_SSL_PRINTF("test %d ok\n",i);
		}
	TINYCLR_SSL_PRINTF("test end processing ");
	for (i=0; i<data_len[3]; i++)
		{
		RC4_set_key(&key,keys[3][0],&(keys[3][1]));
		TINYCLR_SSL_MEMSET(obuf,0x00,sizeof(obuf));
		RC4(&key,i,&(data[3][0]),obuf);
		if ((TINYCLR_SSL_MEMCMP(obuf,output[3],i) != 0) || (obuf[i] != 0))
			{
			TINYCLR_SSL_PRINTF("error in RC4 length processing\n");
			TINYCLR_SSL_PRINTF("output:");
			for (j=0; j<i+1; j++)
				TINYCLR_SSL_PRINTF(" %02x",obuf[j]);
			TINYCLR_SSL_PRINTF("\n");
			TINYCLR_SSL_PRINTF("expect:");
			p= &(output[3][0]);
			for (j=0; j<i; j++)
				TINYCLR_SSL_PRINTF(" %02x",*(p++));
			TINYCLR_SSL_PRINTF(" 00\n");
			err++;
			}
		else
			{
			TINYCLR_SSL_PRINTF(".");
			TINYCLR_SSL_FFLUSH(OPENSSL_TYPE__FILE_STDOUT);
			}
		}
	TINYCLR_SSL_PRINTF("done\n");
	TINYCLR_SSL_PRINTF("test multi-call ");
	for (i=0; i<data_len[3]; i++)
		{
		RC4_set_key(&key,keys[3][0],&(keys[3][1]));
		TINYCLR_SSL_MEMSET(obuf,0x00,sizeof(obuf));
		RC4(&key,i,&(data[3][0]),obuf);
		RC4(&key,data_len[3]-i,&(data[3][i]),&(obuf[i]));
		if (TINYCLR_SSL_MEMCMP(obuf,output[3],data_len[3]+1) != 0)
			{
			TINYCLR_SSL_PRINTF("error in RC4 multi-call processing\n");
			TINYCLR_SSL_PRINTF("output:");
			for (j=0; j<data_len[3]+1; j++)
				TINYCLR_SSL_PRINTF(" %02x",obuf[j]);
			TINYCLR_SSL_PRINTF("\n");
			TINYCLR_SSL_PRINTF("expect:");
			p= &(output[3][0]);
			for (j=0; j<data_len[3]+1; j++)
				TINYCLR_SSL_PRINTF(" %02x",*(p++));
			err++;
			}
		else
			{
			TINYCLR_SSL_PRINTF(".");
			TINYCLR_SSL_FFLUSH(OPENSSL_TYPE__FILE_STDOUT);
			}
		}
	TINYCLR_SSL_PRINTF("done\n");
	TINYCLR_SSL_PRINTF("bulk test ");
	{   unsigned char buf[513];
	    SHA_CTX c;
	    unsigned char md[SHA_DIGEST_LENGTH];
	    static unsigned char expected[]={
		0xa4,0x7b,0xcc,0x00,0x3d,0xd0,0xbd,0xe1,0xac,0x5f,
		0x12,0x1e,0x45,0xbc,0xfb,0x1a,0xa1,0xf2,0x7f,0xc5 };

		RC4_set_key(&key,keys[0][0],&(keys[3][1]));
		TINYCLR_SSL_MEMSET(buf,'\0',sizeof(buf));
		SHA1_Init(&c);
		for (i=0;i<2571;i++) {
			RC4(&key,sizeof(buf),buf,buf);
			SHA1_Update(&c,buf,sizeof(buf));
		}
		SHA1_Final(md,&c);

		if (TINYCLR_SSL_MEMCMP(md,expected,sizeof(md))) {
			TINYCLR_SSL_PRINTF("error in RC4 bulk test\n");
			TINYCLR_SSL_PRINTF("output:");
			for (j=0; j<(int)sizeof(md); j++)
				TINYCLR_SSL_PRINTF(" %02x",md[j]);
			TINYCLR_SSL_PRINTF("\n");
			TINYCLR_SSL_PRINTF("expect:");
			for (j=0; j<(int)sizeof(md); j++)
				TINYCLR_SSL_PRINTF(" %02x",expected[j]);
			TINYCLR_SSL_PRINTF("\n");
			err++;
		}
		else	TINYCLR_SSL_PRINTF("ok\n");
	}
#ifdef OPENSSL_SYS_NETWARE
    if (err) TINYCLR_SSL_PRINTF("ERROR: %d\n", err);
#endif
	return(err);
	}
Exemple #20
0
void crypto_sha1_final(CryptoSha1 sha1, uint8* out_data)
{
	SHA1_Final(out_data, &sha1->sha_ctx);
	xfree(sha1);
}
Exemple #21
0
int OS_MD5_SHA1_File(const char *fname, const char *prefilter_cmd, os_md5 md5output, os_sha1 sha1output, int mode)
{
    size_t n;
    FILE *fp;
    unsigned char buf[2048 + 2];
    unsigned char sha1_digest[SHA_DIGEST_LENGTH];
    unsigned char md5_digest[16];

    SHA_CTX sha1_ctx;
    MD5_CTX md5_ctx;

    /* Clear the memory */
    md5output[0] = '\0';
    sha1output[0] = '\0';
    buf[2048 + 1] = '\0';

    /* Use prefilter_cmd if set */
    if (prefilter_cmd == NULL) {
        fp = fopen(fname, mode == OS_BINARY ? "rb" : "r");
        if (!fp) {
            return (-1);
        }
    } else {
        char cmd[OS_MAXSTR];
        size_t target_length = strlen(prefilter_cmd) + 1 + strlen(fname);
        int res = snprintf(cmd, sizeof(cmd), "%s %s", prefilter_cmd, fname);
        if (res < 0 || (unsigned int)res != target_length) {
            return (-1);
        }
        fp = popen(cmd, "r");
        if (!fp) {
            return (-1);
        }
    }

    /* Initialize both hashes */
    MD5Init(&md5_ctx);
    SHA1_Init(&sha1_ctx);

    /* Update for each one */
    while ((n = fread(buf, 1, 2048, fp)) > 0) {
        buf[n] = '\0';
        SHA1_Update(&sha1_ctx, buf, n);
        MD5Update(&md5_ctx, buf, (unsigned)n);
    }

    SHA1_Final(&(sha1_digest[0]), &sha1_ctx);
    MD5Final(md5_digest, &md5_ctx);

    /* Set output for MD5 */
    for (n = 0; n < 16; n++) {
        snprintf(md5output, 3, "%02x", md5_digest[n]);
        md5output += 2;
    }

    /* Set output for SHA-1 */
    for (n = 0; n < SHA_DIGEST_LENGTH; n++) {
        snprintf(sha1output, 3, "%02x", sha1_digest[n]);
        sha1output += 2;
    }

    /* Close it */
    if (prefilter_cmd == NULL) {
        fclose(fp);
    } else {
        pclose(fp);
    }

    return (0);
}
Exemple #22
0
unsigned char *computeKey(struct NSSPKCS5PBEParameter * pbe_param, const unsigned char *pwdHash, SECItem *pkcs5_pfxpbe, SECItem *secPreHash)
{
	SECItem *ret_bits = pkcs5_pfxpbe;
	SHA_CTX ctx;
	unsigned char state[256];
	unsigned int state_len;
	unsigned char *saltData = pbe_param->salt.data;
	unsigned int saltLen = pbe_param->salt.len;
	SHA_CTX *fctx;
	struct HMACContext cx;
	SHA_CTX lctx;
	SHA_CTX ctx1, ctx2, ctx3;
	unsigned char *ret_data;
	int k;

	// First compute pkcs5 hash
	unsigned char firstHash[SHA1_LENGTH];
	SECItem *preHash = secPreHash;
	// copy password hash .....
	memcpy(preHash->data, pwdHash, SHA1_LENGTH);

	fctx = &ctx;
	SHA1_Init(fctx);
	SHA1_Update(fctx, preHash->data, preHash->len);
	SHA1_Final(firstHash, fctx);


	// Next compute pkcs5 extended hash


	ret_bits->len = SHA1_LENGTH << 1;	// (hash_iter * hash_size);
	state_len = SHA1_LENGTH;

	// this is important...you have to zero the contents before using it
	memset(state, 0, state_len);
	memcpy(state, saltData, saltLen);

	memset(cx.ipad, 0x36, HMAC_PAD_SIZE);
	memset(cx.opad, 0x5c, HMAC_PAD_SIZE);

	/* fold secret into padding */
	for (k = 0; k < SHA1_LENGTH; k++) {
		cx.ipad[k] ^= firstHash[k];
		cx.opad[k] ^= firstHash[k];
	}

	// Unrolled looop...........twice
	SHA1_Init(&lctx);
	SHA1_Update(&lctx, cx.ipad, HMAC_PAD_SIZE);

	// Stage1 : Store the current context for future use
	memcpy(&ctx1, &lctx, sizeof(SHA_CTX));


	SHA1_Update(&lctx, state, state_len);

	// Stage2 : Store this calculated data to avoid repeated copy....
	memcpy(&ctx2, &lctx, sizeof(SHA_CTX));

	SHA1_Update(&lctx, saltData, saltLen);
	ret_data = ret_bits->data;
	SHA1_Final(ret_data, &lctx);

	SHA1_Init(&lctx);
	SHA1_Update(&lctx, cx.opad, HMAC_PAD_SIZE);

	// Stage3 : Store this calculated data to avoid repeated copy....
	memcpy(&ctx3, &lctx, sizeof(SHA_CTX));


	SHA1_Update(&lctx, ret_data, SHA1_LENGTH);
	SHA1_Final(ret_data, &lctx);

	// generate new state
	// Just restore previous context from already calculated data..
	memcpy(&lctx, &ctx2, sizeof(SHA_CTX));

	SHA1_Final(state, &lctx);

	// Just restore previous context from already calculated data..
	memcpy(&lctx, &ctx3, sizeof(SHA_CTX));

	SHA1_Update(&lctx, state, state_len);
	SHA1_Final(state, &lctx);


	// Second loop....

	// Copy the previously stored data...
	memcpy(&lctx, &ctx1, sizeof(SHA_CTX));
	SHA1_Update(&lctx, state, state_len);
	SHA1_Update(&lctx, saltData, saltLen);

	SHA1_Final(ret_data + SHA1_LENGTH, &lctx);

	// Just restore previous context from already calculated data..
	memcpy(&lctx, &ctx3, sizeof(SHA_CTX));

	SHA1_Update(&lctx, ret_data + SHA1_LENGTH, SHA1_LENGTH);
	SHA1_Final(ret_data + SHA1_LENGTH, &lctx);


	return ret_bits->data;
}
Exemple #23
0
int
net_baseline_fsproto_send (__sock pso, pmda base, pmda threadr, void *data)
{
  mutex_lock (&pso->mutex);

  size_t in_read, blk_sz;

  __fs_sts psts = (__fs_sts ) pso->va_p1;

  if (psts->hstat.file_size < (uint64_t) pso->unit_size)
    {
      blk_sz = (size_t) psts->hstat.file_size;
    }
  else if ((uint64_t) psts->hstat.file_size - psts->data_out
      < (uint64_t) pso->unit_size)
    {
      blk_sz = (size_t) (psts->hstat.file_size - psts->data_out);
    }
  else
    {
      blk_sz = (size_t) pso->unit_size;
    }

  int ret = 0;

  in_read = read (psts->handle, pso->buffer0, blk_sz);

  if ((in_read) > 0)
    {
      SHA1_Update (&psts->sha_00.context, pso->buffer0, blk_sz);

      psts->data_out += (uint64_t) in_read;
      if (net_send_direct (pso, pso->buffer0, in_read))
	{
	  NET_BASELINE_FSPROTO_SEND_CLBAD()
	  ;
	}
      print_str ("STATS: [%d]: send: %llu/%llu     \r", pso->sock,
		 psts->data_out, psts->hstat.size);
      pso->timers.last_act = time (NULL);
    }
  else if (in_read == -1)
    {
      char err_buf[1024];
      print_str (
	  "ERROR: net_baseline_fsproto_send: [%d]: [%d]: read failed: [%d] [%s]\n",
	  pso->sock, psts->handle, errno,
	  strerror_r (errno, err_buf, sizeof(err_buf)));
      NET_BASELINE_FSPROTO_SEND_CLBAD()
      ;
    }
  else if (in_read < blk_sz)
    {
      print_str (
	  "ERROR: net_baseline_fsproto_send: [%d]: [%d]: partial read occured on file handle\n",
	  pso->sock, psts->handle);
      NET_BASELINE_FSPROTO_SEND_CLBAD()
      ;
    }

  if (psts->data_out == psts->hstat.file_size)
    {
      if (pso->flags & F_OPSOCK_HALT_RECV)
	{
	  pso->flags ^= F_OPSOCK_HALT_RECV;
	}

      net_proto_reset_to_baseline (pso);

      if (!SHA1_Final ((unsigned char*) psts->sha_00.value.data,
		       &psts->sha_00.context))
	{
	  print_str (
	      "ERROR: net_baseline_fsproto_send: [%d]: [%d]: SHA1_Final failed\n",
	      pso->sock, psts->handle);
	  NET_BASELINE_FSPROTO_SEND_CLBAD()
	  ;
	}

      __fs_rh_enc packet;

      packet = net_fs_compile_breq (CODE_FS_RESP_NOTIFY,
				    (unsigned char*) &psts->sha_00.value,
				    sizeof(_pid_sha1),
				    NULL);

      if ( NULL == packet)
	{
	  print_str (
	      "ERROR: net_baseline_fsproto_send: [%d]: [%d]: net_fs_compile_breq failed\n",
	      pso->sock, psts->handle);
	  NET_BASELINE_FSPROTO_SEND_CLBAD()
	  ;
	}

      if (net_send_direct (pso, (const void*) packet,
			   (size_t) packet->head.content_length))
	{
	  NET_BASELINE_FSPROTO_SEND_CLBAD()
	  ;
	}

      char buffer[128];
      print_str (
	  "DEBUG: net_baseline_fsproto_send: [%d]: all data sent [%s]\n",
	  pso->sock,
	  bb_to_ascii (psts->sha_00.value.data, sizeof(psts->sha_00.value.data),
		       buffer));

      //memset(psts, 0x0, sizeof(_fs_sts));
    }
  else if (psts->data_out > psts->hstat.file_size)
    {
      print_str (
	  "ERROR: net_baseline_fsproto_send: [%d]: too much data sent (report this)\n",
	  pso->sock);
      abort ();
    }

  _finish: ;

  pthread_mutex_unlock (&pso->mutex);

  return ret;
}
Exemple #24
0
int main(int argc, char *argv[])
{
    int i, err = 0;
    int j;
    unsigned char *p;
    RC4_KEY key;
    unsigned char obuf[512];

# if !defined(OPENSSL_PIC)
    void OPENSSL_cpuid_setup(void);

    OPENSSL_cpuid_setup();
# endif

    for (i = 0; i < 6; i++) {
        RC4_set_key(&key, keys[i][0], &(keys[i][1]));
        sgx_memset(obuf, 0x00, sizeof(obuf));
        RC4(&key, data_len[i], &(data[i][0]), obuf);
        if (sgx_memcmp(obuf, output[i], data_len[i] + 1) != 0) {
            printf("error calculating RC4\n");
            printf("output:");
            for (j = 0; j < data_len[i] + 1; j++)
                printf(" %02x", obuf[j]);
            printf("\n");
            printf("expect:");
            p = &(output[i][0]);
            for (j = 0; j < data_len[i] + 1; j++)
                printf(" %02x", *(p++));
            printf("\n");
            err++;
        } else
            printf("test %d ok\n", i);
    }
    printf("test end processing ");
    for (i = 0; i < data_len[3]; i++) {
        RC4_set_key(&key, keys[3][0], &(keys[3][1]));
        sgx_memset(obuf, 0x00, sizeof(obuf));
        RC4(&key, i, &(data[3][0]), obuf);
        if ((sgx_memcmp(obuf, output[3], i) != 0) || (obuf[i] != 0)) {
            printf("error in RC4 length processing\n");
            printf("output:");
            for (j = 0; j < i + 1; j++)
                printf(" %02x", obuf[j]);
            printf("\n");
            printf("expect:");
            p = &(output[3][0]);
            for (j = 0; j < i; j++)
                printf(" %02x", *(p++));
            printf(" 00\n");
            err++;
        } else {
            printf(".");
            fflush(stdout);
        }
    }
    printf("done\n");
    printf("test multi-call ");
    for (i = 0; i < data_len[3]; i++) {
        RC4_set_key(&key, keys[3][0], &(keys[3][1]));
        sgx_memset(obuf, 0x00, sizeof(obuf));
        RC4(&key, i, &(data[3][0]), obuf);
        RC4(&key, data_len[3] - i, &(data[3][i]), &(obuf[i]));
        if (sgx_memcmp(obuf, output[3], data_len[3] + 1) != 0) {
            printf("error in RC4 multi-call processing\n");
            printf("output:");
            for (j = 0; j < data_len[3] + 1; j++)
                printf(" %02x", obuf[j]);
            printf("\n");
            printf("expect:");
            p = &(output[3][0]);
            for (j = 0; j < data_len[3] + 1; j++)
                printf(" %02x", *(p++));
            err++;
        } else {
            printf(".");
            fflush(stdout);
        }
    }
    printf("done\n");
    printf("bulk test ");
    {
        unsigned char buf[513];
        SHA_CTX c;
        unsigned char md[SHA_DIGEST_LENGTH];
        static unsigned char expected[] = {
            0xa4, 0x7b, 0xcc, 0x00, 0x3d, 0xd0, 0xbd, 0xe1, 0xac, 0x5f,
            0x12, 0x1e, 0x45, 0xbc, 0xfb, 0x1a, 0xa1, 0xf2, 0x7f, 0xc5
        };

        RC4_set_key(&key, keys[0][0], &(keys[3][1]));
        sgx_memset(buf, '\0', sizeof(buf));
        SHA1_Init(&c);
        for (i = 0; i < 2571; i++) {
            RC4(&key, sizeof(buf), buf, buf);
            SHA1_Update(&c, buf, sizeof(buf));
        }
        SHA1_Final(md, &c);

        if (sgx_memcmp(md, expected, sizeof(md))) {
            printf("error in RC4 bulk test\n");
            printf("output:");
            for (j = 0; j < (int)sizeof(md); j++)
                printf(" %02x", md[j]);
            printf("\n");
            printf("expect:");
            for (j = 0; j < (int)sizeof(md); j++)
                printf(" %02x", expected[j]);
            printf("\n");
            err++;
        } else
            printf("ok\n");
    }
# ifdef OPENSSL_SYS_NETWARE
    if (err)
        printf("ERROR: %d\n", err);
# endif
    EXIT(err);
    return (0);
}
Exemple #25
0
///////////////////////////////////////////////////////////////////////////////
// Connect to a server.
// Return
// 0: no error
int cc_connect_srv(struct cs_server_data *srv, int fd)
{
	int n;
	uint8 data[20];
	uint8 hash[SHA_DIGEST_LENGTH];
	uint8 buf[CC_MAXMSGSIZE];
	char pwd[64];
	//
	if (fd < 0) return -1;
	// INIT
	srv->progname = NULL;
	memset( srv->version, 0, sizeof(srv->version) );
	// get init seed(random) from server
	if((n = recv_nonb(fd, data, 16,3000)) != 16) {
		static char msg[]= "Server does not return init sequence";
		srv->statmsg = msg;
		//debugf("Client: Server (%s:%d) does not return 16 bytes\n", srv->host->name,srv->port);
		close(fd);
		return -2;
	}

	if (flag_debugnet) {
		debugf(" CCcam: receive server init seed (%d)\n",n);
		debughex(data,n);
	}

	// Check Multics
	int ismultics = 0;
	uchar a = (data[0]^'M') + data[1] + data[2];
	uchar b = data[4] + (data[5]^'C') + data[6];
	uchar c = data[8] + data[9] + (data[10]^'S');
	if ( (a==data[3])&&(b==data[7])&&(c==data[11]) ) ismultics = 1;

	cc_crypt_xor(data);  // XOR init bytes with 'CCcam'

	SHA_CTX ctx;
	SHA1_Init(&ctx);
	SHA1_Update(&ctx, data, 16);
	SHA1_Final(hash, &ctx);

	//debugdump(hash, sizeof(hash), "CCcam: sha1 hash:");

	//initialisate crypto states
	cc_crypt_init(&srv->recvblock, hash, 20);
	cc_decrypt(&srv->recvblock, data, 16); 
	cc_crypt_init(&srv->sendblock, data, 16);
	cc_decrypt(&srv->sendblock, hash, 20);

	cc_msg_send( fd, &srv->sendblock, CC_MSG_NO_HEADER, 20,hash);   // send crypted hash to server
	memset(buf, 0, sizeof(buf));
	memcpy(buf, srv->user, 20);
	//debugf(" CCcam: username '%s'\n",srv->username);
	cc_msg_send( fd, &srv->sendblock, CC_MSG_NO_HEADER, 20, buf);    // send usr '0' padded -> 20 bytes

	memset(buf, 0, sizeof(buf));
	memset(pwd, 0, sizeof(pwd));

	//debugf("CCcam: 'CCcam' xor\n");
	memcpy(buf, "CCcam", 5);
	strncpy(pwd, srv->pass, 63);
	cc_encrypt(&srv->sendblock, (uint8 *)pwd, strlen(pwd));
	cc_msg_send( fd, &srv->sendblock, CC_MSG_NO_HEADER, 6, buf); // send 'CCcam' xor w/ pwd
	if ((n = recv_nonb(fd, data, 20,3000)) != 20) {
		static char msg[]= "Password ACK not received";
		srv->statmsg = msg;
		debugf(" CCcam: login failed to Server (%s:%d), pwd ack not received (n = %d)\n",srv->host->name,srv->port, n);
		return -2;
	}
	cc_decrypt(&srv->recvblock, data, 20);
	//hexdump(data, 20, "CCcam: pwd ack received:");

	if (memcmp(data, buf, 5)) {  // check server response
		static char msg[]= "Invalid user/pass";
		srv->statmsg = msg;
		debugf(" CCcam: login failed to Server (%s:%d), usr/pwd invalid\n",srv->host->name,srv->port);
		return -2;
	}// else debugf(" CCcam: login succeeded to Server (%s:%d)\n",srv->host->name,srv->port);

	srv->handle = fd;
	if (!cc_sendinfo_srv(srv,ismultics)) {
		srv->handle = -1;
		static char msg[]= "Error sending client data";
		srv->statmsg = msg;
		debugf(" CCcam: login failed to Server (%s:%d), could not send client data\n",srv->host->name,srv->port);
		return -3;
	}

	static char msg[]= "Connected";
	srv->statmsg = msg;

	srv->keepalivesent = 0;
	srv->keepalivetime = GetTickCount();
	srv->connected = GetTickCount();

	srv->busy = 0;
	srv->lastecmoktime = 0;
	srv->lastecmtime = 0;
	srv->lastdcwtime = 0;
	srv->chkrecvtime = 0;

	memset(srv->version,0,32);
	pipe_wakeup( srvsocks[1] );
	return 0;
}