Exemplo n.º 1
0
void dumpHaCommandResult(void *data, size_t size)
{
	uint8 *cr = (uint8 *)data;
	uint32 type = ntohl(*(uint32 *)(cr + SHAP_CR_TYPE_OFFSET));
	uint16 len = ntohs(*(uint16 *)(cr + SHAP_CR_DATA_LEN_OFFSET));
	assert(type < 8);
	printf("\t\t%-20s\n", "[Command Result]");
	printf("\t\t\t%-20s:	%s(%u)\n", "type", haCommandTypeMap[type], type);
	printf("\t\t\t%-20s:	%u\n", "data len", len);
	printf("\t\t\t%-20s\n", "[Data]");
	switch(type)
	{
		case SHAP_CM_GET_LOGIN:
			printf("\t\t\t%-20s:	", "random number");
			dumpHex(cr + SHAP_CR_DATA_OFFSET, HA_RANDOMSTRING_SIZE);
			printf("\t\t\t%-20s:	", "auth seed");
			dumpHex(cr + SHAP_CR_DATA_OFFSET + HA_RANDOMSTRING_SIZE, HA_RANDOMSTRING_SIZE);
			printf("\t\t\t%-20s:	", "admin name");
			dumpHex(cr + SHAP_CR_DATA_OFFSET + HA_RANDOMSTRING_SIZE + HA_RANDOMSTRING_SIZE, HA_ADMIN_NAME_SIZE);
			printf("\t\t\t%-20s:	", "password");
			dumpHex(cr + SHAP_CR_DATA_OFFSET + HA_RANDOMSTRING_SIZE + HA_RANDOMSTRING_SIZE + HA_ADMIN_NAME_SIZE, HA_ADMIN_PASSWORD_SIZE);
			break;
		default:
		dumpHex(cr + SHAP_CR_DATA_OFFSET, len);
		break;
		
	}
}
Exemplo n.º 2
0
int TestPK(prng_state * PRNG)
{
    int     err = CRYPT_OK;
    int     i;
    
    ecc_key     eccKey;
    uint8_t        PT[PTsize];
    uint8_t        CT[256];
    uint8_t        DT[PTsize];
    unsigned long   z,w;
    
 
    uint8_t        PrivKey[256];
    uint8_t        PubKey[256];
   
 //   uint8_t             tempBuf[256];
 //   unsigned long       tempLen;

    
    printf("\nTesting PK\n");
   
    // fill PT
    for(i = 0; i< PTsize; i++) PT[i]= i;
      
    DO( ecc_make_key(PRNG, find_prng ("yarrow"),  384/8, &eccKey));
  
    z = sizeof(PubKey);
     DO( ecc_export(PubKey, &z, PK_PUBLIC, &eccKey));
    printf("\tPub Key (%ld bytes)\n", z);
    dumpHex(PubKey,  z, 8);
     
    z = sizeof(PrivKey);
   DO( ecc_export(PrivKey, &z, PK_PRIVATE, &eccKey));
    printf("\n\tPriv Key (%ld bytes)\n", z);
    dumpHex(PrivKey,  z, 8);
     
    z = 384; 
    DO( ecc_encrypt_key(PT, PTsize, CT, &z, 
                        PRNG, 
                        find_prng("yarrow"), 
                        find_hash("sha256"),
                        &eccKey));
 
    printf("\n\tEncrypted message (%ld bytes)\n", z);
    dumpHex(CT,  z, 0);
    
    DO( ecc_decrypt_key(CT, z, DT, &w, &eccKey));
      
    /* check against know-answer */
    DO(compareResults( DT, PT, PTsize , kResultFormat_Byte, "ECC Decrypt"));
    printf("\n\tDecrypted OK\n");
    dumpHex(DT,  w, 0);
 
      ecc_free(&eccKey);
    
    return err;
    
}
Exemplo n.º 3
0
int checkFile(void)
{
	md5_state_t state;
	md5_byte_t md5Tag[16] = {0};
	md5_byte_t md5Clc[16] = {0};
	//struct MD5Context md5c;
	
	if( imageLen < 80 )
	{
		do_upload_finnal();
		return BOOL_FALSE;
	}
	if( imagePtr == NULL )
	{
		do_upload_finnal();
		return BOOL_FALSE;
	}
	memcpy(md5Tag, imagePtr+64, 16);

	printf("boardapi_checkCpuEndian = %s\n", boardapi_checkCpuEndian()?"little-endian":"big-endian");
	
	//MD5Init( &md5c );
	//MD5Update( &md5c, imagePtr+80, imageLen-80 );
	//MD5Final( md5Clc, &md5c );

	md5_init(&state);
	md5_append(&state, (const md5_byte_t *)(imagePtr+80), (imageLen-80));
	md5_finish(&state, md5Clc);	

	printf("MD5 SRC:\n");
	dumpHex((unsigned char *)md5Tag, 16);
	printf("MD5 CLC:\n");
	dumpHex((unsigned char *)md5Clc, 16);

	if( memcmp(md5Tag, md5Clc, 16) == 0 )
	{
		if( CMM_SUCCESS != extract_file("/var/tmp/wec9720ek.tar.bz2", imagePtr+80, imageLen-80) )
		{
			do_upload_finnal();
			return BOOL_FALSE;
		}
		return BOOL_TRUE;
	}
	else
	{
		do_upload_finnal();
		return BOOL_FALSE;
	}    
}
Exemplo n.º 4
0
int main(void)
{
	FILE * fp;
	
	if((fp = fopen("data.txt", "r")) == 0)
	{
		perror("fopen");
		
		return 1;
	}
	
	printf("HEXADECIMAL DUMP:\n\n");
	dumpHex(fp);
	
	printf("\n\n");
	
	if(fseek(fp, 0, SEEK_SET) != 0)
	{
		perror("fseek");
		
		return 1;
	}
	
	printf("OCTAL DUMP:\n\n");
	dumpOct(fp);
	
	fclose(fp);
	
	return 0;
}
Exemplo n.º 5
0
void DumpSections( void )
{
    dw_sectnum  sect;

    sortTables();
    for( sect = 0; sect < DW_DEBUG_MAX; ++sect ) {
        if( sect > 0 )
            printf( "\n" );
        printf( "%s:\n", sectionNames[sect] );
        switch( sect ) {
        case DW_DEBUG_ABBREV:
            dumpAbbrevs( Sections[sect].data, Sections[sect].max_offset );
            break;
        case DW_DEBUG_INFO:
            dumpInfo( Sections[sect].data, Sections[sect].max_offset );
            break;
        case DW_DEBUG_LINE:
            dumpLines( Sections[sect].data, Sections[sect].max_offset );
            break;
        case DW_DEBUG_REF:
            dumpRef( Sections[sect].data, Sections[sect].max_offset );
            break;
        case DW_DEBUG_ARANGES:
            dumpARanges( Sections[sect].data, Sections[sect].max_offset );
            break;
        case DW_DEBUG_STR:
            // Strings are displayed when dumping other sections
            break;
        default:
            dumpHex( Sections[sect].data, Sections[sect].max_offset, 0 );
            break;
        }
    }
}
Exemplo n.º 6
0
/*
	Determines how to proceed with the file dump based on finalized
	command-line arguments.
*/
void processDump(int *flags, int *values, FILE *fp)
{		
	if(flags[0] == ON)
	{
		dumpHex(fp, values);
	}
	
	if(flags[1] == ON)
	{
		dumpOct(fp, values);
	}
	
	if(flags[2] == ON)
	{
		dumpOctPrt(fp, values);
	}
	
	if(flags[3] == ON)
	{
		dumpHexAsc(fp);
	}
	
	if(fclose(fp) != 0)
	{
		perror("fclose");
	}
}
Exemplo n.º 7
0
static u2fs_rc
parse_signatureData(const char *signatureData, uint8_t * user_presence,
                    uint32_t * counter, u2fs_ECDSA_t ** signature)
{

  base64_decodestate b64;
  size_t signatureData_len = strlen(signatureData);
  unsigned char *data;
  int data_len;
  u2fs_rc rc;

  data = malloc(signatureData_len + 1);
  if (data == NULL)
    return U2FS_MEMORY_ERROR;

  data[signatureData_len] = '\0';

  base64_init_decodestate(&b64);
  data_len =
      base64_decode_block(signatureData, signatureData_len, (char *) data,
                          &b64);

  if (debug) {
    fprintf(stderr, "signatureData Hex: ");
    dumpHex((unsigned char *) data, 0, data_len);
  }

  rc = parse_signatureData2(data, data_len, user_presence, counter,
                            signature);

  free(data);
  data = NULL;

  return rc;
}
Exemplo n.º 8
0
/**********************************************************************
*%FUNCTION: dumpPacket
*%ARGUMENTS:
* fp -- file to dump to
* packet -- a PPPoE packet
* dir -- either SENT or RCVD
*%RETURNS:
* Nothing
*%DESCRIPTION:
* Dumps the PPPoE packet to fp in an easy-to-read format
***********************************************************************/
void
dumpPacket(FILE *fp, PPPoEPacket *packet, char const *dir)
{
    int len = ntohs(packet->length);

    /* Sheesh... printing times is a pain... */
    struct timeval tv;
    time_t now;
    int millisec;
    struct tm *lt;
    char timebuf[256];

    UINT16_t type = etherType(packet);
    if (!fp) return;
    gettimeofday(&tv, NULL);
    now = (time_t) tv.tv_sec;
    millisec = tv.tv_usec / 1000;
    lt = localtime(&now);
    strftime(timebuf, 256, "%H:%M:%S", lt);
    fprintf(fp, "%s.%03d %s PPPoE ", timebuf, millisec, dir);
    if (type == Eth_PPPOE_Discovery) {
	fprintf(fp, "Discovery (%x) ", (unsigned) type);
    } else if (type == Eth_PPPOE_Session) {
	fprintf(fp, "Session (%x) ", (unsigned) type);
    } else {
	fprintf(fp, "Unknown (%x) ", (unsigned) type);
    }

    switch(packet->code) {
    case CODE_PADI: fprintf(fp, "PADI "); break;
    case CODE_PADO: fprintf(fp, "PADO "); break;
    case CODE_PADR: fprintf(fp, "PADR "); break;
    case CODE_PADS: fprintf(fp, "PADS "); break;
    case CODE_PADT: fprintf(fp, "PADT "); break;
    case CODE_SESS: fprintf(fp, "SESS "); break;
    }

    fprintf(fp, "sess-id %d length %d\n",
	    (int) ntohs(packet->session),
	    len);

    /* Ugly... I apologize... */
    fprintf(fp,
	    "SourceAddr %02x:%02x:%02x:%02x:%02x:%02x "
	    "DestAddr %02x:%02x:%02x:%02x:%02x:%02x\n",
	    (unsigned) packet->ethHdr.h_source[0],
	    (unsigned) packet->ethHdr.h_source[1],
	    (unsigned) packet->ethHdr.h_source[2],
	    (unsigned) packet->ethHdr.h_source[3],
	    (unsigned) packet->ethHdr.h_source[4],
	    (unsigned) packet->ethHdr.h_source[5],
	    (unsigned) packet->ethHdr.h_dest[0],
	    (unsigned) packet->ethHdr.h_dest[1],
	    (unsigned) packet->ethHdr.h_dest[2],
	    (unsigned) packet->ethHdr.h_dest[3],
	    (unsigned) packet->ethHdr.h_dest[4],
	    (unsigned) packet->ethHdr.h_dest[5]);
    dumpHex(fp, packet->payload, ntohs(packet->length));
}
Exemplo n.º 9
0
C4Err compareResults(const void* expected, const void* calculated, size_t len,
                        DumpFormatType format, char* comment  )
{
    C4Err err = kC4Err_NoErr;
    
    err = CMP(expected, calculated, len)
    ? kC4Err_NoErr : kC4Err_SelfTestFailed;
    
    if( (err != kC4Err_NoErr)  && IsntNull(comment) && (format != kResultFormat_None))
    {
        OPTESTLogError( "\n\t\tFAILED %s\n",comment );
        switch(format)
        {
            case kResultFormat_Byte:
                OPTESTLogError( "\t\texpected:\n");
                dumpHex(IF_LOG_ERROR, ( uint8_t*) expected, (int)len, 0);
                OPTESTLogError( "\t\tcalulated:\n");
                dumpHex(IF_LOG_ERROR,( uint8_t*) calculated, (int)len, 0);
                OPTESTLogError( "\n");
                break;
                
            case kResultFormat_Long:
                OPTESTLogError( "\t\texpected:\n");
                dump64(IF_LOG_ERROR,( uint8_t*) expected, len);
                OPTESTLogError( "\t\tcalulated:\n");
                dump64(IF_LOG_ERROR,( uint8_t*) calculated, len );
                OPTESTLogError( "\n");
                break;
                
            case kResultFormat_Cstr:
                OPTESTLogError( "\t\texpected:\n");
                dump8(IF_LOG_ERROR,( uint8_t*) expected, len);
                OPTESTLogError( "\t\tcalulated:\n");
                dump8(IF_LOG_ERROR,( uint8_t*) calculated, len );
                OPTESTLogError( "\n");
                break;
               
                
            default:
                break;
        }
    }
    
    return err;
}
Exemplo n.º 10
0
void dumpHaConfigAck(void *data, size_t size)
{
	uint8 *ca = (uint8 *)data;
	uint16 type = ntohs(*(uint16 *)(ca + SHAP_CA_TYPE_OFFSET));
	assert(type< 5);
	printf("\t\t%-20s\n", "[Config Ack]");
	printf("\t\t\t%-20s:	%s(%u)\n", "type", haConfigAckTypeMap[type], type);
	printf("\t\t\t%-20s:	%u\n", "error code", ntohl(*(uint32 *)(ca + SHAP_CA_ERROR_CODE_OFFSET)));
	printf("\t\t\t%-20s:	", "data");
	dumpHex(ca + SHAP_CA_DATA_OFFSET, 4);
}
Exemplo n.º 11
0
void dumpHaUpgrade(void *data, size_t size)
{
	uint8 *up = (uint8 *)data;
	uint16 type = ntohs(*(uint16 *)(up + SHAP_UP_TYPE_OFFSET));
	printf("\t\t%-20s\n", "[Upgrade]");
	printf("\t\t\t%-20s:	%u\n", "type", type);
	if(size - sizeof(type) > 0)
	{
		printf("\t\t\t%-20s:	", "data");
		dumpHex(up + SHAP_UP_DATA_OFFSET, size - sizeof(type));
	}
}
Exemplo n.º 12
0
DeviceState_t GetDeviceState(int fd)
{
    unsigned buf = 0;

    if (!VendorCmdGetData(fd, 0, (unsigned char*)&buf, 4)) {
        return STATE_INVALIDxx;
    }

    printf("GetDeviceState: ");
    dumpHex((unsigned char*)&buf, 4);

    return (DeviceState_t)buf;
}
Exemplo n.º 13
0
void HashDump(HashHandle handle)
{
#ifdef WEBCFG_DEBUG
    HashTable   * table = NULL;
    HashElement * e     = NULL;

    table   = __validate(handle);

    WEBLOG_API();

    ASSERT(table);
    dumpHex((void *)table, sizeof(HashTable));

    ASSERT(table->table);
    dumpHex((void *)table->table, table->size * sizeof(HashElement*));

    e = HashFirst(handle);
    while(e)
    {
        switch(e->value.type)
        {
        case eHashString:
            WEBLOG_INFO("<%s> [%s]-[%s]\n", __FUNCTION__, e->name, e->value.data.string);
            break;
        case eHashInt:
            WEBLOG_INFO("<%s> [%s]-[%d]\n", __FUNCTION__, e->name, e->value.data.integer);
            break;
        case eHashPointer:
            WEBLOG_INFO("<%s> [%s]-[0x%p]\n", __FUNCTION__, e->name, e->value.data.pointer);
            break;
        default:
            WEBLOG_INFO("<%s> [%s]-[????]\n", __FUNCTION__, e->name);
            break;
        }
        e = HashNext(handle, e);
    }
#endif
}
Exemplo n.º 14
0
bool VendorCmdGetData(int fd, unsigned char code, unsigned char *buf, unsigned char buflen)
{
    bool ret = false;

    memset(buf, 0, buflen);

    if (!ServiceOpen(fd)) {
        return false;
    }

    unsigned char cdb[16] = { 0xc5, 7, 0, 0, 0, 0, 0, 0, 0, buflen, 2, 1, code, 0, 0, 0 };

    bool ok = lowlevelCmd(fd, cdb, sizeof(cdb), buf, buflen);
    if (!ok) {
        printf("VendorCmdGetData fail 1\n");
        goto vcgd_fail;
    }
    printf("VendorCmdGetData(code=%d)#1: ", code);
    dumpHex(buf, buflen);

    ServiceIsFinished(fd);

    cdb[11] = 2;
    ok = lowlevelCmd(fd, cdb, sizeof(cdb), buf, buflen);
    if (!ok) {
        printf("VendorCmdGetData fail 2\n");
        goto vcgd_fail;
    }
    printf("VendorCmdGetData(code=%d)#1: ", code);
    dumpHex(buf, buflen);

    ret = true;

vcgd_fail:
    ServiceClose(fd);
    return ret;
}
int sendFirmware(int fd, uint8* data, uint8* pages_used)
{
	uint32 u_addr;
	
	
	uint32 page  = 0;
	uint32 done  = 0;
	uint32 row   = 0;
	uint8  command[256] = {0};
	
	
	for( page=0; page<PIC_NUM_PAGES; page++)
	//for( page=0; page<3; page++)
	{
		
		u_addr = page * ( PIC_NUM_WORDS_IN_ROW * 2 * PIC_NUM_ROWS_IN_PAGE );
		//u_addr = page * ( 2 * 32 );
		
		if( pages_used[page] != 1 ) {
			if(cmdLineArgs.g_verbose && u_addr < PIC_FLASHSIZE) {
				fprintf(stdout, "Skipping page %ld [ %06lx ], not used\n", page, u_addr);
			}
			continue;
		}
		
		if( u_addr >= PIC_FLASHSIZE ) {
			fprintf(stderr, "Address out of flash\n");
			continue; //return -1;
		}
		
		//write 64 bytes
		//for( row = 0; row < PIC_NUM_ROWS_IN_PAGE; row ++, u_addr += (PIC_NUM_WORDS_IN_ROW * 2))
		//{
		
			memcpy(&command[0], &data[page*64], 64);
			
			printf("Writing page %ld, %04lx... \n", page, u_addr);
			if( cmdLineArgs.g_verbose ) {
				dumpHex(command,64);
			}

			writePIC(u_addr, command, 64);
			
			done += 64;//PIC_ROW_SIZE;
		//}
	}
	
	return done;
}
Exemplo n.º 16
0
void QSpyWrk::variableRecord(const QString& name, const QByteArray& data)
{
    QString s = name;
    bool isReadable = ( name == "Title" || name == "Author" ||
                       name == "Copyright" || name == "Subtitle" ||
                       name == "Instructions" || name == "Keywords" );
    if (isReadable) {
        s += ": ";
        if (m_engine->getTextCodec() == 0)
            s += QString(data);
        else
            s += m_engine->getTextCodec()->toUnicode(data);
    }
    dumpStr(0, "Variable Record", s.trimmed());
    if (!isReadable)
        dumpHex(data);
}
Exemplo n.º 17
0
bool lowlevelReadCmd(int fd, unsigned char *buf, unsigned chunk_size, unsigned addr)
{
    // interpret arguments as arrays of bytes
    unsigned char cs[4] = { 0 };
    unsigned char ad[4] = { 0 };
    *((unsigned*)cs) = chunk_size;
    *((unsigned*)ad) = addr;

    // create cmd packet
    unsigned char cdb[16] = { 0xc3, 7, ad[3], ad[2], ad[1], ad[0], cs[3], cs[2], cs[1], cs[0], 0, 0, 0, 0, 0, 0 };

#ifdef MEMREAD_DEBUG
    printf("lowlevelReadCmd: ");
    dumpHex(cdb, sizeof(cdb));
#endif

    return lowlevelCmd(fd, cdb, sizeof(cdb), buf, chunk_size);
}
Exemplo n.º 18
0
unsigned lowlevelServiceCmd(int fd, unsigned char code)
{
    unsigned char rxbuf[16] = { 0 };
    unsigned char cdb[16] = { 0xc5, 7, 0, 0, 0, 0, 0, 0, 0, 0x10, 0xff, code, 0, 0, 0, 0 };

    bool ok = lowlevelCmd(fd, cdb, sizeof(cdb), rxbuf, sizeof(rxbuf));
    if (!ok) {
        return -1;
    }

#ifdef SERVICE_DEBUG
    printf("lowlevelServiceCmd(code=%d): ", code);
    dumpHex(rxbuf, sizeof(rxbuf));
#endif

    // return first 4 bytes
    return *((unsigned*)rxbuf);
}
Exemplo n.º 19
0
bool checkDevice(int fd)
{
    unsigned rxbuf = 0;
    unsigned char cdb[16] = { 0xc5, 7, 0, 0, 0, 0, 0, 0, 0, 4, 0xff, 2, 0, 0, 0, 0 };

    bool ok = lowlevelCmd(fd, cdb, sizeof(cdb), (unsigned char*)&rxbuf, 4);
    if (!ok) {
        return false;
    }

    if ((unsigned)rxbuf == 0x41564f4e) {
        return true;
    }

    printf("checkDevice fail: ");
    dumpHex((unsigned char*)&rxbuf, sizeof(rxbuf));

    return false;
}
Exemplo n.º 20
0
static u2fs_rc parse_registrationData(const char *registrationData,
                                      unsigned char **user_public_key,
                                      size_t * keyHandle_len,
                                      char **keyHandle,
                                      u2fs_X509_t **
                                      attestation_certificate,
                                      u2fs_ECDSA_t ** signature)
{
  base64_decodestate b64;
  size_t registrationData_len = strlen(registrationData);
  unsigned char *data;
  int data_len;
  u2fs_rc rc;

  data = malloc(registrationData_len + 1);
  if (data == NULL)
    return U2FS_MEMORY_ERROR;

  data[registrationData_len] = '\0';

  base64_init_decodestate(&b64);
  data_len =
      base64_decode_block(registrationData, registrationData_len,
                          (char *) data, &b64);

  if (debug) {
    fprintf(stderr, "registrationData Hex: ");
    dumpHex((unsigned char *) data, 0, data_len);
  }

  rc = parse_registrationData2(data, data_len,
                               user_public_key, keyHandle_len, keyHandle,
                               attestation_certificate, signature);

  free(data);
  data = NULL;

  return rc;
}
Exemplo n.º 21
0
TEST(Dict, Compress) {

	const char* dictStr = "quickfoxdogjumps";

	DictFlex dict;
	dict.setDict( (const uint8_t*) dictStr, strlen(dictStr) );

	const char* toEncode = "The quick brown fox jumps over the lazy dog123";

	DictEncStream stream(1024*1024);
	DictEncoder enc(&dict);

	enc.append( (const uint8_t*) toEncode, strlen(toEncode), stream);

	dumpHex(std::cout, stream.data, stream.getNumBytes());

	// check
	ASSERT_EQ(42, stream.getNumBytes());
	ASSERT_EQ(0xFF, stream.data[4]);
	ASSERT_EQ(0x00, stream.data[5]);
	ASSERT_EQ(0x05, stream.data[6]);

	ASSERT_EQ(0xFF, stream.data[14]);
	ASSERT_EQ(0x00, stream.data[15]);
	ASSERT_EQ(0x53, stream.data[16]);		// (offset 5) * 16 + (length 3)

	ASSERT_EQ(0xFF, stream.data[18]);
	ASSERT_EQ(0x00, stream.data[19]);
	ASSERT_EQ(0xB5, stream.data[20]);		// (offset 11) * 16 + (length 5)

	ASSERT_EQ(0xFF, stream.data[36]);
	ASSERT_EQ(0x00, stream.data[37]);
	ASSERT_EQ(0x83, stream.data[38]);		// (offset 8) * 16 + (length 3)



}
Exemplo n.º 22
0
void BinaryUtils::dumpHex(const QByteArray & byteArray)
{
    dumpHex(byteArray.constData(), byteArray.size());
}
Exemplo n.º 23
0
S4Err  TestSecretSharing()
{
   
    S4Err       err = kS4Err_NoErr;
    uint8_t     PT[PTsize];
    uint8_t     PT1[sizeof (PT)];
    size_t      keyLen      = 0;

    SHARES_ShareInfo*   shareInfo[kNumShares];
    SHARES_ShareInfo*   testShares[kShareThreshold];
    uint8_t             testOffset[kShareThreshold];
    
    SHARES_ContextRef   shareCTX  = kInvalidSHARES_ContextRef;
    
      uint32_t 	i;

    
    OPTESTLogInfo("\nTesting Shamir Key Spliting\n");
 
    // create a random key
    err = RNG_GetBytes(PT, sizeof(PT)); CKERR;
    
    OPTESTLogVerbose("\t\tKey Data: (%ld bytes)\n", PTsize);
    dumpHex(IF_LOG_DEBUG, PT,  (int)sizeof (PT), 0);
    OPTESTLogDebug("\n");
 
    
    err = SHARES_Init( PT, sizeof(PT),
                      kNumShares,
                      kShareThreshold,
                      &shareCTX); CKERR;
 
    for(i = 0; i < kNumShares; i++)
    {
        size_t shareLen = 0;
        
        err = SHARES_GetShareInfo(shareCTX, i, &shareInfo[i], &shareLen); CKERR;
      
        if(IF_LOG_VERBOSE)
        {
            OPTESTLogVerbose("\t  Share %d: (%d bytes)\n", i,shareLen);
            dumpHex(IF_LOG_DEBUG, shareInfo[i]->shareSecret  , (int)shareInfo[i]->shareSecretLen, 0);
            OPTESTLogVerbose("\n");
        }
        
        
//        OPTESTLogVerbose("\t Check shares for data leakage against known original message...");
//             /*  check shares for data leakage against known original message */
//            err = CMP(shareBuf+(shareSize *i) + kSHAMIR_HEADERSIZE,
//                      PT,  sizeof (PT))
//            ? kS4Err_SelfTestFailed : kS4Err_NoErr;
//            CKERR;
    
      }
    
    // create threshold number of shares to test with
    sCreateTestOffsets(testOffset, sizeof(testOffset));
    
    for(i = 0; i < kShareThreshold; i++)
          testShares[i] = shareInfo[testOffset[i]];
  
 
    /* attempt to combine with not enough shares */
   err =  SHARES_CombineShareInfo(kShareThreshold -1, testShares, PT1, sizeof(PT1),
                             &keyLen);
    
    OPTESTLogVerbose("\t Attempt to combine with not enough shares = %s\n",
                     IsS4Err(err)?"fail":"pass");
    if(err == kS4Err_NotEnoughShares) err = kS4Err_NoErr;
    CKERR;
    
    /* Reconstruct data */
    OPTESTLogVerbose("\t Reconstructing data with just %d shares...",kShareThreshold);
  err = SHARES_CombineShareInfo(kShareThreshold, testShares, PT1, sizeof(PT1),
                              &keyLen); CKERR;

    OPTESTLogVerbose("OK\n");
    
    /*  check result against known original message */
    OPTESTLogVerbose("\t Check result against known original message...\n");
    err = compare2Results(PT, sizeof(PT), PT1, keyLen, kResultFormat_Byte, "SHAMIR Reconstruct");  //CKERR;

   
    OPTESTLogInfo("\n");
    
done:
    
    for(i = 0; i < kNumShares; i++)
    {
        if(shareInfo[i]) XFREE(shareInfo[i]);
    }
    
    if(SHARES_ContextRefIsValid(shareCTX))
        SHARES_Free(shareCTX);
    
    return err;
    
}
int sendFirmware(int fd, uint8* data, uint8* pages_used)
{
    uint32 u_addr;


    uint32 page  = 0;
    uint32 done  = 0;
    uint32 row   = 0;
    uint8  command[256] = {0};


    for( page=0; page<PIC_NUM_PAGES; page++)
    {

        u_addr = page * ( PIC_NUM_WORDS_IN_ROW * 2 * PIC_NUM_ROWS_IN_PAGE );

        if( pages_used[page] != 1 )
        {
            if( g_verbose && u_addr < flashsize)
            {
                fprintf(stdout, "Skipping page %ld [ %06lx ], not used\n", page, u_addr);
            }
            continue;
        }

        if( u_addr >= flashsize )
        {
            fprintf(stderr, "Address out of flash\n");
            return -1;
        }

        //erase page
        command[0] = (u_addr & 0x00FF0000) >> 16;
        command[1] = (u_addr & 0x0000FF00) >>  8;
        command[2] = (u_addr & 0x000000FF) >>  0;
        command[COMMAND_OFFSET] = 0x01; //erase command
        command[LENGTH_OFFSET ] = 0x01; //1 byte, CRC
        command[PAYLOAD_OFFSET] = makeCrc(command, 5);

        if( g_verbose )
        {
            dumpHex(command, HEADER_LENGTH + command[LENGTH_OFFSET]);
        }

        printf("Erasing page %ld, %04lx...", page, u_addr);

        if( g_simulate == 0 && sendCommandAndWaitForResponse(fd, command) < 0 )
        {
            return -1;
        }

        puts("OK");

        //write 8 rows
        for( row = 0; row < PIC_NUM_ROWS_IN_PAGE; row ++, u_addr += (PIC_NUM_WORDS_IN_ROW * 2))
        {
            command[0] = (u_addr & 0x00FF0000) >> 16;
            command[1] = (u_addr & 0x0000FF00) >>  8;
            command[2] = (u_addr & 0x000000FF) >>  0;
            command[COMMAND_OFFSET] = 0x02; //write command
            command[LENGTH_OFFSET ] = PIC_ROW_SIZE + 0x01; //DATA_LENGTH + CRC

            memcpy(&command[PAYLOAD_OFFSET], &data[PIC_ROW_ADDR(page, row)], PIC_ROW_SIZE);

            command[PAYLOAD_OFFSET + PIC_ROW_SIZE] = makeCrc(command, HEADER_LENGTH + PIC_ROW_SIZE);

            printf("Writing page %ld row %ld, %04lx...", page, row + page*PIC_NUM_ROWS_IN_PAGE, u_addr);

            if( g_verbose )
            {
                dumpHex(command, HEADER_LENGTH + command[LENGTH_OFFSET]);
            }

            if( g_simulate == 0 && sendCommandAndWaitForResponse(fd, command) < 0 )
            {
                return -1;
            }

            puts("OK");

            sleep(0);


            done += PIC_ROW_SIZE;
        }
    }

    return done;
}
Exemplo n.º 25
0
static void dumpInfo( const uint_8 *input, uint length ) {

    const uint_8 *p;
    uint_32     abbrev_code;
    uint_32     abbrev_offset;
    uint_8 *    abbrev;
    uint_32     tag;
    uint_32     attr;
    uint_32     form;
    uint_32     len;
    uint_32     tmp;
    int_32      stmp;
    uint_32     unit_length;
    int         address_size;
    const uint_8 *unit_base;

    p = input;
    while( p - input < length ) {
        unit_length = getU32( (uint_32 *)p );
        unit_base = p + sizeof( uint_32 );
        address_size = *(p + 10);
        abbrev_offset = getU32( (uint_32 *)(p + 6) );
        printf( "Length: %08lx\nVersion: %04x\nAbbrev: %08lx\nAddress Size %02x\n",
            unit_length, getU16( (uint_16 *)(p + 4) ), abbrev_offset, address_size );
        p += 11;
        while( p - unit_base < unit_length ) {
            printf( "offset %08x: ", p - input );
            p = DecodeULEB128( p, &abbrev_code );
            printf( "Code: %08lx\n", abbrev_code );
            if( abbrev_code == 0 )
                continue;
            abbrev = findAbbrev( abbrev_code, abbrev_offset );
            if( abbrev == NULL ) {
                printf( "can't find abbreviation %08lx\n", abbrev_code );
                break;
            }
            if( p >= input + length )
                break;
            abbrev = DecodeULEB128( abbrev, &tag );
            printf( "\t%s\n", getTAG( tag ) );
            abbrev++;
            for( ;; ) {
                abbrev = DecodeULEB128( abbrev, &attr );
                abbrev = DecodeULEB128( abbrev, &form );
                if( attr == 0 )
                    break;
                printf( "\t%-20s", getAT( attr ) );
    decode_form:
                switch( form ) {
                case DW_FORM_addr:
                    switch( address_size ) {
                    case 4:
                        tmp = getU32( (uint_32 *)p );
                        p += sizeof( uint_32 );
                        printf( "\t%08lx\n", tmp );
                        break;
                    case 2:
                        tmp = getU16( (uint_16 *)p );
                        p += sizeof( uint_16 );
                        printf( "\t%04lx\n", tmp );
                        break;
                    default:
                        printf( "Unknown address size\n" );
                        p += address_size;
                        break;
                    }
                    break;
                case DW_FORM_block:
                    p = DecodeULEB128( p, &len );
                    printf( "\n" );
                    dumpHex( p, len, 0 );
                    p += len;
                    break;
                case DW_FORM_block1:
                    len = *p++;
                    printf( "\n" );
                    dumpHex( p, len, 0 );
                    p += len;
                    break;
                case DW_FORM_block2:
                    len = getU16( (uint_16 *)p );
                    p += sizeof( uint_16 );
                    printf( "\n" );
                    dumpHex( p, len, 0 );
                    p += len;
                    break;
                case DW_FORM_block4:
                    len = getU32( (uint_32 *)p );
                    p += sizeof( uint_32 );
                    printf( "\n" );
                    dumpHex( p, len, 0 );
                    p += len;
                    break;
                case DW_FORM_data1:
                case DW_FORM_ref1:
                    printf( "\t%02x\n", *p++ );
                    break;
                case DW_FORM_data2:
                case DW_FORM_ref2:
                    printf( "\t%04x\n", getU16( (uint_16 *)p ) );
                    p += sizeof( uint_16 );
                    break;
                case DW_FORM_data4:
                case DW_FORM_ref4:
                    printf( "\t%08lx\n", getU32( (uint_32 *)p ) );
                    p += sizeof( uint_32 );
                    break;
                case DW_FORM_flag:
                    printf( "\t%s\n", *p++ ? "True" : "False" );
                    break;
                case DW_FORM_indirect:
                    p = DecodeULEB128( p, &form );
                    printf( "\t(%s)", getFORM( form ) );
                    goto decode_form;
                case DW_FORM_sdata:
                    p = DecodeLEB128( p, &stmp );
                    printf( "\t%08lx\n", stmp );
                    break;
                case DW_FORM_string:
                    printf( "\t\"%s\"\n", p );
                    p += strlen( (const char *)p ) + 1;
                    break;
                case DW_FORM_strp:  /* 4 byte index into .debug_str */
                    printf_debug_str( getU32( (uint_32 *)p ) );
                    p += 4;
                    break;
                case DW_FORM_udata:
                case DW_FORM_ref_udata:
                    p = DecodeULEB128( p, &tmp );
                    printf( "\t%08lx\n", tmp );
                    break;
                case DW_FORM_ref_addr:  //KLUDGE should really check addr_size
                    printf( "\t%08lx\n", getU32( (uint_32 *)p ) );
                    p += sizeof(uint_32);
                    break;
                default:
                    printf( "unknown form!\n" );
                    return;
                }
            }
        }
    }
}
Exemplo n.º 26
0
static void dumpLines( const uint_8 *input, uint length )
{
    const uint_8    *p;
    uint            opcode_base;
    uint            *opcode_lengths;
    uint            u;
    uint            file_index;
    const uint_8    *name;
    uint_32         dir_index;
    uint_32         mod_time;
    uint_32         file_length;
    uint_32         directory;
    uint_8          op_code;
    uint_8          op_len;
    uint_32         tmp;
    uint_16         tmp_seg;
    uint            line_range;
    int             line_base;
    int_32          itmp;
    int             default_is_stmt;
    state_info      state;
    uint            min_instr;
    uint_32         unit_length;
    const uint_8    *unit_base;

    p = input;
    while( p - input < length ) {
        unit_length = getU32( (uint_32 *)p );
        p += sizeof( uint_32 );
        unit_base = p;

        printf( "total_length: 0x%08lx (%u)\n", unit_length, unit_length );

        printf( "=== unit dump start ===\n" );
        dumpHex( unit_base - sizeof( uint_32 ), unit_length + sizeof (uint_32 ), 1 );
        printf( "=== unit dump end ===\n" );

        printf( "version: 0x%04x\n", getU16( (uint_16 *)p ) );
        p += sizeof( uint_16 );

        printf( "prologue_length: 0x%08lx (%u)\n", getU32( (uint_32 *)p ), getU32( (uint_32 *)p ) );
        p += sizeof( uint_32 );

        min_instr = *p;
        printf( "minimum_instruction_length: 0x%02x (%u)\n", min_instr, min_instr );
        p += 1;

        default_is_stmt = *p;
        printf( "default_is_stmt: 0x%02x (%u)\n", default_is_stmt, default_is_stmt );
        p += 1;

        line_base = *(int_8 *)p;
        printf( "line_base: 0x%02x (%d)\n", (unsigned char)line_base, line_base );
        p += 1;

        line_range = *(uint_8 *)p;
        printf( "line_range: 0x%02x (%u)\n", line_range, line_range );
        p += 1;

        opcode_base = *p;
        printf( "opcode_base: 0x%02x (%u)\n", opcode_base, opcode_base );
        p += 1;
        opcode_lengths = alloca( sizeof( uint ) * opcode_base );
        printf( "standard_opcode_lengths:\n" );
        for( u = 0; u < opcode_base - 1; ++u ) {
            opcode_lengths[u] = *p;
            ++p;
            printf( "%4u: %u\n", u + 1, opcode_lengths[u] );
        }

        printf( "-- current_offset = %08x\n", p - input );

        if( p - input >= length )
            return;

        printf( "-- start include paths --\n");
        file_index = 0;
        while( *p != 0 ) {
            ++file_index;
            name = p;
            p += strlen( (const char *)p ) + 1;
            printf( "path %u: '%s'\n", file_index, name );
            if( p - input >= length ) {
                return;
            }
        }
        printf( "-- end include paths --\n");
        p++;
        printf( "-- start files --\n");
        file_index = 0;
        while( *p != 0 ) {
            ++file_index;
            name = p;
            p += strlen( (const char *)p ) + 1;
            p = DecodeULEB128( p, &dir_index );
            p = DecodeULEB128( p, &mod_time );
            p = DecodeULEB128( p, &file_length );
            printf( "file %u: '%s' dir_index %08lx mod_time %08lx length %08lx\n",
                file_index, name, dir_index, mod_time, file_length );
            if( p - input >= length ) {
                return;
            }
        }
        printf( "-- end files --\n");
        p++;
        initState( &state, default_is_stmt );

        while( p - unit_base < unit_length ) {
            op_code = *p;
            ++p;
            if( op_code == 0 ) {
                printf( "EXTENDED 0x%02x: ", op_code );
                /* extended op_code */
                op_len = *p;
                ++p;
                printf( "len: %03d ", op_len );
                op_code = *p;
                ++p;
                switch( op_code ) {
                case DW_LNE_end_sequence:
                    printf( "END_SEQUENCE\n" );
                    state.end_sequence = 1;
                    dumpState( &state );
                    initState( &state, default_is_stmt );
                    break;
                case DW_LNE_set_address:
                    if( op_len == 3 ) {
                        tmp = getU16( (uint_16 *)p );
                        p += sizeof( uint_16 );
                    } else {
                        tmp = getU32( (uint_32 *)p );
                        p += sizeof( uint_32 );
                    }
#if 0   /* Why did they choose 6 byte here?  */
                    tmp_seg = getU16( (uint_16 *)p );
                    p += sizeof( uint_16 );
                    printf( "SET_ADDRESS %04x:%08lx\n", tmp_seg, tmp );
#else
                    tmp_seg = 0;    /* stop warning */
                    printf( "SET_ADDRESS %08lx\n", tmp );
#endif
                    break;
                case DW_LNE_WATCOM_set_segment_OLD:
                case DW_LNE_WATCOM_set_segment:
                    tmp_seg = getU16( (uint_16 *)p );
                    p += sizeof( uint_16 );
                    printf( "SET_ADDRESS_SEG %04x\n", tmp_seg );
                    break;
                case DW_LNE_define_file:
                    ++file_index;
                    name = p;
                    p += strlen( (const char *)p ) + 1;
                    p = DecodeULEB128( p, &directory );
                    p = DecodeULEB128( p, &mod_time );
                    p = DecodeULEB128( p, &file_length );
                    printf( "DEFINE_FILE %u: '%s' directory %ld mod_time %08lx length %08lx\n",
                        file_index, name, directory, mod_time, file_length );
                    break;
                default:
                    printf( "** unknown extended opcode: %02x - %u bytes\n", op_code, op_len );
                    printf( "** losing %u bytes\n", unit_length - ( p - unit_base ));

                    dumpHex( p-3, (unit_length - ( p - unit_base )) + 3, 1 );

                    p = unit_base + unit_length;
                    goto hacky;
//                    return;
                }
            } else if( op_code < opcode_base ) {
                printf( "%s", getStandardOp( op_code ) );
                switch( op_code ) {
                case DW_LNS_copy:
                    printf( "\n" );
                    dumpState( &state );
                    state.basic_block = 0;
                    break;
                case DW_LNS_advance_pc:
                    p = DecodeLEB128( p, &itmp );
                    printf( " %ld\n", itmp );
                    state.address += itmp * min_instr;
                    break;
                case DW_LNS_advance_line:
                    p = DecodeLEB128( p, &itmp );
                    printf( " %ld\n", itmp );
                    state.line += itmp;
                    break;
                case DW_LNS_set_file:
                    p = DecodeLEB128( p, &itmp );
                    printf( " %ld\n", itmp );
                    state.file = itmp;
                    break;
                case DW_LNS_set_column:
                    p = DecodeLEB128( p, &itmp );
                    printf( " %ld\n", itmp );
                    state.column = itmp;
                    break;
                case DW_LNS_negate_stmt:
                    printf( "\n" );
                    state.is_stmt = !state.is_stmt;
                    break;
                case DW_LNS_set_basic_block:
                    printf( "\n" );
                    state.basic_block = 1;
                    break;
                case DW_LNS_const_add_pc:
                    printf( "\n" );
                    state.address += ( ( 255 - opcode_base ) / line_range ) * min_instr;
                    break;
                case DW_LNS_fixed_advance_pc:
                    tmp = getU16( (uint_16 *)p );
                    p += sizeof( uint_16 );
                    printf( " %04x\n", tmp );
                    state.address += tmp;
                    break;
                default:
                    for( u = 0; u < opcode_lengths[op_code - 1]; ++u ) {
                        p = DecodeLEB128( p, &itmp );
                        printf( " %08lx", itmp );
                    }
                    printf( "\n" );
                }
            } else {
                printf( "SPECIAL 0x%02x:", op_code );
                op_code -= opcode_base;
                printf( " addr incr: %d  line incr: %d\n",
                    op_code / line_range,
                    line_base + op_code % line_range );
                state.line += line_base + op_code % line_range;
                state.address += ( op_code / line_range ) * min_instr;
                dumpState( &state );
                state.basic_block = 0;
            }
        }
hacky:
        printf( "-- current_offset = %08x\n", p - input );
    }
}
Exemplo n.º 27
0
int CChannel::sendto(const sockaddr* addr, CPacket& packet) const
{

   // convert control information into network order
   if (packet.getFlag()) {
      for (int i = 0, n = packet.getLength() / 4; i < n; ++ i)
         *((uint32_t *)packet.m_pcData + i) = htonl(*((uint32_t *)packet.m_pcData + i));
   } 

   uint32_t* p = packet.m_nHeader;
   for (int j = 0; j < 4; ++ j)
   {
      *p = htonl(*p);
      ++ p;
   }

#ifdef DEBUGP
   //dump ctrl packet
    printf("\nSend Header:\n");
    dumpHex((char *)packet.m_PacketVector[0].iov_base, packet.m_PacketVector[0].iov_len);
   char *bb = (char *)packet.m_PacketVector[0].iov_base;
   if(bb[0]&0x80) {
      printf("Data:\n");
      dumpHex((char *)packet.m_PacketVector[1].iov_base, packet.m_PacketVector[1].iov_len);
      printf("================\n");
   }
#endif

   int res = -1;
   unsigned size;
   unsigned len;
   natnl_hdr hdr = {0xff, 0x00, 0x0000};
   int is_tnl_data = 0;
   pj_thread_desc desc;
   pj_thread_t *thread = 0;

   if(m_iSocket == -1) {
      pjsua_call *call = (pjsua_call *)m_call;
	  if(call == NULL) return -1;

	  // DEAN, prevent assert fail while garbage collector remove UDT socket on multiple instance. 
	  if (!pj_thread_is_registered(call->inst_id)) {
		  int status = pj_thread_register(call->inst_id, "CChannel::sendto", desc, &thread );
		  if (status != PJ_SUCCESS)
			  return -1;
	  }

	  pj_mutex_lock(call->tnl_stream_lock2);

	  natnl_stream *stream = (natnl_stream *)call->tnl_stream;
	  if(stream == NULL) {
	     pj_mutex_unlock(call->tnl_stream_lock2);
	     return -1;
	  }

     size = CPacket::m_iPktHdrSize + packet.getLength() + sizeof(natnl_hdr);
     len = (CPacket::m_iPktHdrSize + packet.getLength());
	  hdr.length = htons(len);

      memcpy((char *)&m_pktBuffer[sizeof(natnl_hdr)], packet.m_PacketVector[0].iov_base, packet.m_PacketVector[0].iov_len);
      memcpy((char *)&m_pktBuffer[packet.m_PacketVector[0].iov_len+sizeof(natnl_hdr)], packet.m_PacketVector[1].iov_base, packet.m_PacketVector[1].iov_len);
      memcpy((char *)&m_pktBuffer[0], &hdr, sizeof(natnl_hdr));

resend:
	  // DEAN, check if this is tunnel data. If true, update last_data time.
	  is_tnl_data = pjmedia_natnl_udt_packet_is_tnl_data(&m_pktBuffer[0], size);

	  pj_assert(size < sizeof(m_pktBuffer));
		
	  ((pj_uint8_t*)m_pktBuffer)[size] = 0;  // tunnel data flag off

	  if (is_tnl_data) {
		  pj_get_timestamp(&stream->last_data);  // DEAN save current time 
		  ((pj_uint8_t*)m_pktBuffer)[size] = 1;  // tunnel data flag on
	  }

	  res = pjmedia_transport_send_rtp(stream->med_tp, m_pktBuffer, size);	// +Roger modified - stream pointer to med_tp
#if 0 // No need to resend it, because UDT will handle this.
	  if(res == 70011) { //EAGAIN
		  m_pTimer->sleepto(50000); //sleep for 50 us
	      goto resend;   
      }
#endif
      pj_mutex_unlock(call->tnl_stream_lock2);
   }
   res = (0 == res) ? size : -1;

   // convert back into local host order
   //for (int k = 0; k < 4; ++ k)
   //   packet.m_nHeader[k] = ntohl(packet.m_nHeader[k]);
   p = packet.m_nHeader;
   for (int k = 0; k < 4; ++ k)
   {
      *p = ntohl(*p);
       ++ p;
   }

   if (packet.getFlag())
   {
      for (int l = 0, n = packet.getLength() / 4; l < n; ++ l)
         *((uint32_t *)packet.m_pcData + l) = ntohl(*((uint32_t *)packet.m_pcData + l));
   }

   return res;
}
Exemplo n.º 28
0
static SCLError sTestECC(int keySize)
{
#define PTsize 32

    SCLError     err = kSCLError_NoErr;
    int     i;
    
    uint8_t        PT[PTsize];
    
    uint8_t        CT[256];
    size_t         CTlen = 0;
    
    uint8_t        DT[PTsize];
    size_t         DTlen = 0;
    
    uint8_t         pubKey[256];
    size_t          pubKeyLen = 0;
    
    uint8_t         privKey[256];
    size_t          privKeyLen = 0;
 
    bool isPrivate = false;
    size_t  importKeySize = 0;
    bool    isANSIx963 = false;

    //   uint8_t             tempBuf[256];
    //   unsigned long       tempLen;
    
    
    OPTESTLogInfo("\tECC-%d \n",  keySize);
    
    ECC_ContextRef ecc = kInvalidECC_ContextRef;
    ECC_ContextRef eccPub = kInvalidECC_ContextRef;
    
    // fill PT
    for(i = 0; i< PTsize; i++) PT[i]= i;
    
    err = ECC_Init(&ecc);

    OPTESTLogVerbose("\t\tGenerate Pub Key (%ld bytes)\n", pubKeyLen);
    err = ECC_Generate(ecc, keySize); CKERR;
    
    err =  ECC_Export_ANSI_X963( ecc, pubKey, sizeof(pubKey), &pubKeyLen);CKERR;
    OPTESTLogVerbose("\t\tExport Public Key (%ld bytes)\n", pubKeyLen);
    dumpHex(IF_LOG_DEBUG, pubKey,  (int)pubKeyLen, 0);

    err = ECC_Import_Info( pubKey, pubKeyLen, &isPrivate, &isANSIx963, &importKeySize );CKERR;
    OPTESTLogVerbose("\t\t\t%d bit %s%s key\n", (int)importKeySize , isANSIx963 ?"ANSI x9.63 ":"", isPrivate ?"private":"public");
    
    err =  ECC_Export(ecc, true, privKey, sizeof(privKey), &privKeyLen);CKERR;
    OPTESTLogVerbose("\t\tExport Private Key (%ld bytes)\n", privKeyLen);
    dumpHex(IF_LOG_DEBUG, privKey,  (int)privKeyLen, 0);
    
    err = ECC_Import_Info( privKey, privKeyLen, &isPrivate, &isANSIx963, &importKeySize );CKERR;
    OPTESTLogVerbose("\t\t\t%d bit %s%s key\n", (int)importKeySize , isANSIx963 ?"ANSI x9.63 ":"", isPrivate ?"private":"public");

    // delete keys
    if(ECC_ContextRefIsValid(ecc) ) ECC_Free(ecc );
    ecc = kInvalidECC_ContextRef;
    
    err = ECC_Init(&eccPub);
    err = ECC_Import_ANSI_X963( eccPub, pubKey, pubKeyLen);CKERR;
    
    importKeySize = 0;
    err =  ECC_KeySize(eccPub, &importKeySize);
    OPTESTLogVerbose("\t\tImported %d bit public key\n", (int)importKeySize  );
    
    err = ECC_Encrypt(eccPub, PT, sizeof(PT),  CT, sizeof(CT), &CTlen);CKERR;
    OPTESTLogVerbose("\t\tEncrypt message: (%ld bytes)\n", CTlen);
    dumpHex(IF_LOG_DEBUG, CT,  (int)CTlen, 0);
    
     err = ECC_Init(&ecc);
    err = ECC_Import(ecc, privKey, privKeyLen);CKERR;

    err =  ECC_KeySize(ecc, &importKeySize);
    OPTESTLogVerbose("\t\tImported %d bit private key\n", (int)importKeySize  );
    
    err = ECC_Decrypt(ecc, CT, CTlen,  DT, sizeof(DT), &DTlen); CKERR;
    
    /* check against know-answer */
    err= compareResults( DT, PT, PTsize , kResultFormat_Byte, "ECC Decrypt"); CKERR;
   OPTESTLogVerbose("\t\tDecrypted OK\n");
   dumpHex(IF_LOG_DEBUG, DT,  (int)DTlen, 0);
    
    err = ECC_Sign(ecc, PT, sizeof(PT),  CT, sizeof(CT), &CTlen);CKERR;
    OPTESTLogVerbose("\t\tSigned message (%ld bytes)\n", CTlen);
    dumpHex(IF_LOG_DEBUG, CT,  (int)CTlen, 0);
    
    err = ECC_Verify(ecc, CT, CTlen, PT, sizeof(PT));
    OPTESTLogVerbose("\t\tVerify = %s\n",  IsSCLError(err)?"fail":"pass");
    
    PT[3]= 9;
    err = ECC_Verify(ecc, CT, CTlen, PT, sizeof(PT));
    OPTESTLogVerbose("\t\tVerify bad packet = %s\n",  IsSCLError(err)?"fail":"pass");
    if(err == kSCLError_BadIntegrity) err = kSCLError_NoErr;
    
    OPTESTLogVerbose("\n");
done:
    
    if(ECC_ContextRefIsValid(ecc) ) ECC_Free(ecc );
    if(ECC_ContextRefIsValid(eccPub)) ECC_Free(eccPub);
    
    return err;
    
}
Exemplo n.º 29
0
SCLError sTestECC_DH(int keySize)
{
    
    SCLError     err = kSCLError_NoErr;
    
    uint8_t         pubKey1[256];
    size_t          pubKeyLen1 = 0;
    uint8_t         privKey1[256];
    size_t          privKeyLen1 = 0;

    uint8_t         pubKey2[256];
    size_t          pubKeyLen2 = 0;
    uint8_t         privKey2[256];
    size_t          privKeyLen2 = 0;
  
    
    ECC_ContextRef eccPriv = kInvalidECC_ContextRef;
    ECC_ContextRef eccPub  = kInvalidECC_ContextRef;
    
    uint8_t         Z1       [256];
    size_t          Zlen1;
    uint8_t         Z2       [256];
    size_t          Zlen2;
    
    
    OPTESTLogInfo("\tTesting ECC-DH (%d)\n",  keySize);
    
    /* create keys   */
    OPTESTLogDebug("\t\tGenerate Key 1\n");
    err = ECC_Init(&eccPriv); CKERR;
    err = ECC_Generate(eccPriv, keySize ); CKERR;
  
    err =  ECC_Export_ANSI_X963( eccPriv, pubKey1, sizeof(pubKey1), &pubKeyLen1);CKERR;
    err =  ECC_Export(eccPriv, true, privKey1, sizeof(privKey1), &privKeyLen1);CKERR;
    
    OPTESTLogDebug("\t\tKey 1 Pub/Priv  (%ld,%ld) bytes\n", pubKeyLen1, privKeyLen1);
    OPTESTLogDebug("\t\tPublic\n");
    dumpHex(IF_LOG_DEBUG, pubKey1,  (int)pubKeyLen1, 0);
    OPTESTLogDebug("\t\tPrivate\n");
    dumpHex(IF_LOG_DEBUG, privKey1,  (int)privKeyLen1, 0);
    OPTESTLogDebug("\n");
    
    if(ECC_ContextRefIsValid(eccPriv) ) ECC_Free(eccPriv );
    eccPriv = kInvalidECC_ContextRef;

    
    OPTESTLogDebug("\t\tGenerate Key 2\n");
    err = ECC_Init(&eccPriv); CKERR;
    err = ECC_Generate(eccPriv, keySize ); CKERR;
    
    err =  ECC_Export_ANSI_X963( eccPriv, pubKey2, sizeof(pubKey2), &pubKeyLen2);CKERR;
    err =  ECC_Export(eccPriv, true, privKey2, sizeof(privKey2), &privKeyLen2);CKERR;
    
    OPTESTLogDebug("\t\tKey 2 Pub/Priv  (%ld,%ld) bytes\n", pubKeyLen2, privKeyLen2);
    OPTESTLogDebug("\t\tPublic\n");
    dumpHex(IF_LOG_DEBUG, pubKey2,  (int)pubKeyLen2, 0);
    OPTESTLogDebug("\t\tPrivate\n");
    dumpHex(IF_LOG_DEBUG, privKey2,  (int)privKeyLen2, 0);
    OPTESTLogDebug("\n");
    
    // delete keys
   if(ECC_ContextRefIsValid(eccPriv) ) ECC_Free(eccPriv );
    eccPriv = kInvalidECC_ContextRef;
    
    OPTESTLogDebug("\t\tCalculate Secret for Key1 -> Key2\n");
    err = ECC_Init(&eccPriv);
    err = ECC_Import(eccPriv, privKey1, privKeyLen1);CKERR;
 
    err = ECC_Init(&eccPub);
    err = ECC_Import_ANSI_X963( eccPub, pubKey2, pubKeyLen2);CKERR;
    
    /* Kdk = MAC(Htotal,Z)    where Z is the DH of Pki and PKr */
    Zlen1 = sizeof(Z1);
     err = ECC_SharedSecret(eccPriv, eccPub, Z1, sizeof(Z1), &Zlen1);CKERR;

    OPTESTLogVerbose("\t\tECC Shared Secret (Z1):  (%ld bytes)\n",Zlen1);
    dumpHex(IF_LOG_DEBUG, Z1,  (int)Zlen1 , 0);
    OPTESTLogDebug("\n");

    
    // delete keys
    if(ECC_ContextRefIsValid(eccPriv) ) ECC_Free(eccPriv );
    eccPriv = kInvalidECC_ContextRef;
    // delete keys
    if(ECC_ContextRefIsValid(eccPub) ) ECC_Free(eccPub );
    eccPub = kInvalidECC_ContextRef;
    
    OPTESTLogDebug("\t\tCalculate Secret for Key2 -> Key1\n");
    err = ECC_Init(&eccPriv);
    err = ECC_Import(eccPriv, privKey2, privKeyLen2);CKERR;
    
    err = ECC_Init(&eccPub);
    err = ECC_Import_ANSI_X963( eccPub, pubKey1, pubKeyLen1);CKERR;
    
    /* Kdk = MAC(Htotal,Z)    where Z is the DH of Pki and PKr */
    Zlen2 = sizeof(Z2);
    err = ECC_SharedSecret(eccPriv, eccPub, Z2, sizeof(Z2), &Zlen2);CKERR;
    
    OPTESTLogVerbose("\t\tECC Shared Secret (Z2):  (%ld bytes)\n",Zlen2);
    dumpHex(IF_LOG_DEBUG, Z2,  (int)Zlen2 , 0);
    OPTESTLogDebug("\n");
    
    OPTESTLogVerbose("\t\tCompare Secrets\n");
   err = compare2Results(Z1, Zlen1, Z2, Zlen2, kResultFormat_Byte, "ECC Shared Secret");CKERR;
    
    
done:
    if(eccPriv)
    {
        ECC_Free(eccPriv);
        eccPriv = kInvalidECC_ContextRef;
    }
    
    if(eccPub)
    {
        ECC_Free(eccPub);
        eccPub = kInvalidECC_ContextRef;
    }
    
    
    return err;
    
}
Exemplo n.º 30
0
int CChannel::recvfrom(sockaddr* addr, CPacket& packet) const
{
   int res = -1;
   recv_buff *rb = NULL;
   pj_thread_desc desc;
   pj_thread_t *thread = 0;

    if (m_iSocket == -1) {
        pjsua_call *call = (pjsua_call *)m_call;
        if(call == NULL)
                return -1;
		if(call->tnl_stream==NULL)
			return -1;

		// DEAN, prevent assert fail while garbage collector remove UDT socket on multiple instance. 
		if (!pj_thread_is_registered(call->inst_id)) {
			int status = pj_thread_register(call->inst_id, "CChannel::recvfrom", desc, &thread );
			if (status != PJ_SUCCESS)
				return -1;
		}

		pj_mutex_lock(call->tnl_stream_lock3);

		natnl_stream *stream = (natnl_stream *)call->tnl_stream;

		//get data from rBuff
		if (stream == NULL) {
			pj_mutex_unlock(call->tnl_stream_lock3);
			return -1;
		}
		// charles CHARLES
		// DEAN commeted, for using pj_sem_try_wait2
        //pj_mutex_unlock(call->tnl_stream_lock3);
		//pj_sem_wait(stream->rbuff_sem);
		pj_sem_trywait2(stream->rbuff_sem);
        //pj_mutex_lock(call->tnl_stream_lock3);

        pj_mutex_lock(stream->rbuff_mutex);

        if (!pj_list_empty(&stream->rbuff)) {
			rb = stream->rbuff.next;
			stream->rbuff_cnt--;
			//PJ_LOG(4, ("channel.cpp", "rbuff_cnt=%d", stream->rbuff_cnt));
			pj_list_erase(rb);
			/*if (rb->len > 0 && 
				((pj_uint32_t *)rb->buff)[0] == NO_CTL_SESS_MGR_HEADER_MAGIC) {  // check the magic
					char *data = (char *)&rb->buff[sizeof(NO_CTL_SESS_MGR_HEADER_MAGIC)];
					int len = rb->len - sizeof(NO_CTL_SESS_MGR_HEADER_MAGIC);
					natnl_handle_recv_msg(call->index, call->tnl_stream->med_tp, data, len);
			} else */if (!check_packet_integrity(rb)) {
				int ds = UMIN(packet.m_PacketVector[1].iov_len, rb->len - sizeof(natnl_hdr) - CPacket::m_iPktHdrSize);
				memcpy(packet.m_PacketVector[0].iov_base, &rb->buff[sizeof(natnl_hdr)], packet.m_PacketVector[0].iov_len);
				memcpy(packet.m_PacketVector[1].iov_base, &rb->buff[packet.m_PacketVector[0].iov_len+sizeof(natnl_hdr)], ds);
				res = rb->len - sizeof(natnl_hdr);
			}
	  }
        pj_mutex_unlock(stream->rbuff_mutex);

		if (rb != NULL) {
#if 1
			//move rb to gcbuff
			pj_mutex_lock(stream->gcbuff_mutex);
			pj_list_push_back(&stream->gcbuff, rb);
			pj_mutex_unlock(stream->gcbuff_mutex);
#else
			free(rb);
			rb = NULL;
#endif
		}
		pj_mutex_unlock(call->tnl_stream_lock3);
    }

   if (res <= 0)
   {
      packet.setLength(-1);
      return -1;
   }

   packet.setLength(res - CPacket::m_iPktHdrSize);

#ifdef DEBUGP
   printf("\nRecv Header:\n");
   dumpHex((char *)packet.m_PacketVector[0].iov_base, packet.m_PacketVector[0].iov_len);
   char *bb = (char *)packet.m_PacketVector[0].iov_base;
   if(bb[0]&0x80) {
      printf("Data:\n");
      dumpHex((char *)packet.m_PacketVector[1].iov_base, packet.m_PacketVector[1].iov_len);
      printf("================\n");
   }
#endif

   // convert back into local host order
   //for (int i = 0; i < 4; ++ i)
   //   packet.m_nHeader[i] = ntohl(packet.m_nHeader[i]);
   uint32_t* p = packet.m_nHeader;
   for (int i = 0; i < 4; ++ i)
   {
      *p = ntohl(*p);
      ++ p;
   }

   if (packet.getFlag())
   {
      for (int j = 0, n = packet.getLength() / 4; j < n; ++ j)
         *((uint32_t *)packet.m_pcData + j) = ntohl(*((uint32_t *)packet.m_pcData + j));
   }
   return packet.getLength();
}