Ejemplo n.º 1
0
int tst_md5(FILE *ifile, md5_byte_t *digest)
{
    char *file_data;
    unsigned int len;
    md5_state_t state;

    // allocate source buffer
    fseek(ifile, 0, SEEK_END);
    len = ftell(ifile);
    fseek(ifile, 0, SEEK_SET);

    file_data = (char*) malloc(len);

    // read file
    len = fread(file_data, 1, len, ifile);
    
    // compute md5
	md5_init(&state);
	md5_append(&state, (const md5_byte_t *)file_data, len);
	md5_finish(&state, digest);
    
    return 0;
}
Ejemplo n.º 2
0
void MatrixOpData::finalize()
{
    AutoMutex lock(m_mutex);

    std::ostringstream cacheIDStream;
    cacheIDStream << getID();

    md5_state_t state;
    md5_byte_t digest[16];

    // TODO: array and offset do not require double precison in cache.
    md5_init(&state);
    md5_append(&state,
        (const md5_byte_t *)&(getArray().getValues()[0]),
        (int)(16 * sizeof(double)));
    md5_append(&state,
        (const md5_byte_t *)getOffsets().getValues(),
        (int)(4 * sizeof(double)));
    md5_finish(&state, digest);

    cacheIDStream << GetPrintableHash(digest);
    m_cacheID = cacheIDStream.str();
}
Ejemplo n.º 3
0
int md5_file(const char* path, char* output, double& nbytes) {
    unsigned char buf[4096];
    unsigned char binout[16];
    md5_state_t state;
    int i, n;

    nbytes = 0;
#ifndef _USING_FCGI_
    FILE *f = fopen(path, "rb");
#else
    FILE *f = FCGI::fopen(path, "rb");
#endif
    if (!f) {
        fprintf(stderr, "md5_file: can't open %s\n", path);
#ifndef _USING_FCGI_
        std::perror("md5_file");
#else
        FCGI::perror("md5_file");
#endif

        return ERR_FOPEN;
    }
    md5_init(&state);
    while (1) {
        n = (int)fread(buf, 1, 4096, f);
        if (n<=0) break;
        nbytes += n;
        md5_append(&state, buf, n);
    }
    md5_finish(&state, binout);
    for (i=0; i<16; i++) {
        sprintf(output+2*i, "%02x", binout[i]);
    }
    output[32] = 0;
    fclose(f);
    return 0;
}
Ejemplo n.º 4
0
//----------------------------------------------------------------
void FileToMd5(HANDLE Hfic, char *md5)
{
  //ouverture du fichier en lecture partagé
  md5[0]=0;
  DWORD taille_fic = GetFileSize(Hfic,NULL);
  if (taille_fic>0 && taille_fic!=INVALID_FILE_SIZE)
  {
    unsigned char *buffer = (LPBYTE)HeapAlloc(GetProcessHeap(), 0, sizeof(unsigned char*)*taille_fic+1);
    if (buffer == NULL)return;

    //lecture du fichier
    DWORD copiee, position = 0, increm = 0;
    if (taille_fic > DIXM)increm = DIXM;
    else increm = taille_fic;
    BOOL read = TRUE;
    while (position<taille_fic && increm!=0 && read)//gestion pour éviter les bug de sync permet une ouverture de fichiers énormes ^^
    {
      copiee = 0;
      read =ReadFile(Hfic, buffer+position, increm,&copiee,0);
      position +=copiee;
      if (taille_fic-position < increm)increm = taille_fic-position ;
    }

    //traitement en MD5
    md5_state_t     state;
    md5_byte_t      digest[16];
    md5_init(&state);
    md5_append(&state,(const md5_byte_t  *)buffer,taille_fic);
    md5_finish(&state,digest);

    //génération du md5 en chaine
    unsigned short i;
    for(i=0;i<16;i++)snprintf(md5+i*2,3,"%02x",digest[i]);
    md5[32]=0;
    HeapFree(GetProcessHeap(), 0,buffer);
  }
}
Ejemplo n.º 5
0
/* multi query */
int alipay_query(char* precr, int* len, char* str_imsi)
{

        char https[1024];

        char encrypt[1024];
        char encrypt1wokey[1024];
        md5_state_t state;
        md5_byte_t digest[16];
        char hex_output[16*2 + 1];
        int di;
        if(time_mark[0]=='\0')
        *len = sprintf(encrypt,"IMSI=%s&time_mark=%s#%s", str_imsi, str_timemark, jfkey);
        else
        *len = sprintf(encrypt,"IMSI=%s&time_mark=%s#%s", str_imsi, time_mark, jfkey);
        printf("\nMD5 input:encrypt=%s", encrypt);

        md5_init(&state);
        md5_append(&state, (const md5_byte_t *)encrypt, strlen(encrypt));
        md5_finish(&state, digest);
        for (di = 0; di < 16; ++di)
            sprintf(hex_output + di * 2, "%02x", digest[di]);
        printf("\nencrypt output:");
        puts(hex_output);

        if(time_mark[0]=='\0')
        *len = sprintf(encrypt1wokey,"IMSI=%s&time_mark=%s", str_imsi, str_timemark);
        else
        *len = sprintf(encrypt1wokey,"IMSI=%s&time_mark=%s", str_imsi, time_mark);
        //*len = sprintf(https,"http://192.168.1.104:8180/qrcode/preorder/?IMSI=123456789012345&serial_number=12&total_fee=0.01&subject=ccc&order_time=2014-08-0211:21:20");
        //*len = sprintf(https,"http://%s:%d/qrcode/preorder/?IMSI=%s&serial_number=%d&total_fee=%d&subject=%s&order_time=%s", jfserver, portnumber, IMSI, serial_number, jftotal_fee, jfsubject, order_time);
        *len = sprintf(https,"http://%s:%d/qrcode/query/?%s&sign=%s",jfserver, portnumber, encrypt1wokey, hex_output);
        puts(https);
        memset(precr, 0, *len+1);
        memcpy(precr, https, *len);
        return *len;
}
Ejemplo n.º 6
0
int __cdecl main()
{
    static const char *const test[7] = {
	"", /*d41d8cd98f00b204e9800998ecf8427e*/
	"a", /*0cc175b9c0f1b6a831c399e269772661*/
	"abc", /*900150983cd24fb0d6963f7d28e17f72*/
	"message digest", /*f96b697d7cb7938d525a2f31aaf161d0*/
	"abcdefghijklmnopqrstuvwxyz", /*c3fcd3d76192e4007dfb496cca67e13b*/
	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
				/*d174ab98d277d9f5a5611c2c9f419d9f*/
	"12345678901234567890123456789012345678901234567890123456789012345678901234567890" /*57edf4a22be3c955ac49da2e2107b67a*/
    };
    int i;

    for (i = 0; i < 7; ++i) {
	md5_state_t state;
	md5_byte_t digest[16];

	md5_init(&state);
	md5_append(&state, (const md5_byte_t *)test[i], (int) strlen(test[i]));
	md5_finish(&state, digest);
	printf("MD5 (\"%s\") = ", test[i]);
	for (int di = 0; di < 16; ++di) {
	    printf("%02x", digest[di]);
	}
	printf("\n");
	MD5Digest d;
	d.update((const md5_byte_t *)test[i], strlen(test[i]));
	
	printf("MD5*(\"%s\") = ", test[i]);
	for (int di = 0; di < 16; ++di) {
	    printf("%02x", d.digest()[di]);
	}
	printf("\n");
    }
    return 0;
}
Ejemplo n.º 7
0
int alipay_precreatebak(char* precr, int* len)
{
	char encrypt[1024];
	md5_state_t state;
	md5_byte_t digest[16];
	char hex_output[16*2 + 1];
	int di;
	//without goods_detail
	//sprintf(encrypt,"_input_charset=%s&out_trade_no=%s&partner=%s&product_code=%s&service=%s&subject=%s&total_fee=%s%s",_input_charset, out_trade_no,partner,product_code,service,subject,total_fee,key);
	//with goods_detail
	//sprintf(encrypt,"_input_charset=%s&goods_detail=%s&out_trade_no=%s&partner=%s&product_code=%s&service=%s&subject=%s&total_fee=%s%s",_input_charset, goods_detail, out_trade_no,partner,product_code,service,subject,total_fee,key);
	//with royalty
	sprintf(encrypt,"_input_charset=%s&goods_detail=%s&out_trade_no=%s&partner=%s&product_code=%s&royalty_parameters=%s&service=%s&subject=%s&total_fee=%s%s",_input_charset, goods_detail, out_trade_no,partner,product_code,royalty_parameters,service,subject,total_fee,key);
	printf("\nMD5 input:encrypt=\n%s", encrypt);

	md5_init(&state);
	md5_append(&state, (const md5_byte_t *)encrypt, strlen(encrypt));
	md5_finish(&state, digest);
	for (di = 0; di < 16; ++di)
	    sprintf(hex_output + di * 2, "%02x", digest[di]);
	printf("\nencrypt output:\n");
	puts(hex_output);

	printf("\nalipay.acquire.precreate:\n");
	char https[1024*3];
	char encrypt1wokey[1024*3];
	//without goods_detail
	//sprintf(encrypt1wokey,"_input_charset=%s&out_trade_no=%s&partner=%s&product_code=%s&service=%s&subject=%s&total_fee=%s",_input_charset,out_trade_no,partner,product_code,service,subject,total_fee);
	//with goods_detail
	//sprintf(encrypt1wokey,"_input_charset=%s&goods_detail=%s&out_trade_no=%s&partner=%s&product_code=%s&service=%s&subject=%s&total_fee=%s",_input_charset,goods_detail,out_trade_no,partner,product_code,service,subject,total_fee);
	sprintf(encrypt1wokey,"_input_charset=%s&goods_detail=%s&out_trade_no=%s&partner=%s&product_code=%s&royalty_parameters=%s&service=%s&subject=%s&total_fee=%s",_input_charset,goods_detail,out_trade_no,partner,product_code,royalty_parameters,service,subject,total_fee);
	*len = sprintf(https,"https://mapi.alipay.com/gateway.do?%s&sign_type=MD5&sign=%s",encrypt1wokey,hex_output);
	puts(https);
	memset(precr, 0, *len+1);
	memcpy(precr, https, *len);
	return *len;
}
Ejemplo n.º 8
0
char* calculateMD5(const void* token, int len, char* wdigest) {

    //algo for md5 digest
    char dig [18];
    md5_state_t state;
    md5_byte_t digest[16];
    int di;
    char* ret = NULL;

    md5_init  (&state);
    md5_append(&state, (const md5_byte_t *)token, len);
    md5_finish(&state, digest);
    for (di = 0; di < 16; ++di) {
        sprintf(dig + di, "%c", digest[di]);
    }
    if (wdigest == NULL) {
        ret = new char[16];
        memcpy(ret, dig, 16);
        return ret;
    } else {
        memcpy(wdigest, dig, 16);
        return NULL;
    }
}
Ejemplo n.º 9
0
uint64_t CalcOldStyleID(unsigned arg_num_axes, unsigned arg_num_balls,
                        unsigned arg_num_hats, unsigned arg_num_buttons)
{
  uint8 digest[16];
  int tohash[4];
  md5_context hashie;
  uint64_t ret = 0;

 tohash[0] = arg_num_axes;
 tohash[1] = arg_num_balls;
 tohash[2] = arg_num_hats;
 tohash[3] = arg_num_buttons;

 md5_starts(&hashie);
 md5_update(&hashie, (uint8 *)tohash, sizeof(tohash));
 md5_finish(&hashie, digest);

 int x;
 for(x = 0; x < 16; x++)
 {
   ret ^= (uint64_t)digest[x] << ((x & 7) * 8);
 }
 return ret;
}
Ejemplo n.º 10
0
  void Toolbox::ComputeMD5(std::string& result,
                           const void* data,
                           size_t length)
  {
    md5_state_s state;
    md5_init(&state);

    if (length > 0)
    {
      md5_append(&state, 
                 reinterpret_cast<const md5_byte_t*>(data), 
                 static_cast<int>(length));
    }

    md5_byte_t actualHash[16];
    md5_finish(&state, actualHash);

    result.resize(32);
    for (unsigned int i = 0; i < 16; i++)
    {
      result[2 * i] = GetHexadecimalCharacter(actualHash[i] / 16);
      result[2 * i + 1] = GetHexadecimalCharacter(actualHash[i] % 16);
    }
  }
Ejemplo n.º 11
0
/* Encrypt `src' of length `len' and store the result in `dest'.  If the
 * resulting string would be longer than `size', return -1 and leave `dest'
 * unchanged; else return 0.
 */
static int myencrypt(const char *src, int len, char *dest, int size)
{

#ifdef ENCRYPT_MD5

    md5_state_t context;
    char digest[33];
    char dest2[16];
    int i;

    if (size < 32)
        return -1;

    memset(&context, 0, sizeof(context));
    memset(&digest, 0, sizeof(digest));

    md5_init(&context);
    md5_append(&context, (unsigned const char *) src, (size_t) len);
    md5_finish(&context, (unsigned char *) digest);

    for (i = 0; i < 32; i += 2)
        dest2[i / 2] = XTOI(digest[i]) << 4 | XTOI(digest[i + 1]);

    /* convert to hex, skipping last 8 bytes (constant) -- jilles */
    strcpy(dest, "$ircservices$");
    for (i = 0; i <= 7; i++)
	sprintf(dest + 13 + 2 * i, "%02x", 255 & dest2[i]);
    return 0;

#else

    return -1;                  /* unknown encryption algorithm */

#endif

}
Ejemplo n.º 12
0
/* TODO: replace this with a faster hash function? */
char *etag_new(const char *p, size_t sz) {

	md5_byte_t buf[16];
	char *etag = calloc(34 + 1, 1);
	int i;

	if(!etag)
		return NULL;

	md5_state_t pms;

	md5_init(&pms);
	md5_append(&pms, (const md5_byte_t *)p, (int)sz);
	md5_finish(&pms, buf);

	for(i = 0; i < 16; ++i) {
		sprintf(etag + 1 + 2*i, "%.2x", (unsigned char)buf[i]);
	}

	etag[0] = '"';
	etag[33] = '"';

	return etag;
}
Ejemplo n.º 13
0
static void md5_finish_wrap( void *ctx, unsigned char *output )
{
    md5_finish( (md5_context *) ctx, output );
}
Ejemplo n.º 14
0
        bool run(const char *ns, BSONObj& cmdObj, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
            log(1) << " authenticate: " << cmdObj << endl;

            string user = cmdObj.getStringField("user");
            string key = cmdObj.getStringField("key");
            string received_nonce = cmdObj.getStringField("nonce");
            
            if( user.empty() || key.empty() || received_nonce.empty() ) { 
                log() << "field missing/wrong type in received authenticate command " 
                    << cc().database()->name
                    << endl;               
                errmsg = "auth fails";
                sleepmillis(10);
                return false;
            }
            
            stringstream digestBuilder;

            {
                bool reject = false;
                nonce *ln = lastNonce.release();
                if ( ln == 0 ) {
                    reject = true;
                } else {
                    digestBuilder << hex << *ln;
                    reject = digestBuilder.str() != received_nonce;
                }
                    
                if ( reject ) {
                    log() << "auth: bad nonce received or getnonce not called. could be a driver bug or a security attack. db:" << cc().database()->name << endl;
                    errmsg = "auth fails";
                    sleepmillis(30);
                    return false;
                }
            }

            static BSONObj userPattern = fromjson("{\"user\":1}");
            string systemUsers = cc().database()->name + ".system.users";
            OCCASIONALLY Helpers::ensureIndex(systemUsers.c_str(), userPattern, false, "user_1");

            BSONObj userObj;
            {
                BSONObjBuilder b;
                b << "user" << user;
                BSONObj query = b.done();
                if( !Helpers::findOne(systemUsers.c_str(), query, userObj) ) { 
                    log() << "auth: couldn't find user " << user << ", " << systemUsers << endl;
                    errmsg = "auth fails";
                    return false;
                }
            }
            
            md5digest d;
            {
                
                string pwd = userObj.getStringField("pwd");
                digestBuilder << user << pwd;
                string done = digestBuilder.str();
                
                md5_state_t st;
                md5_init(&st);
                md5_append(&st, (const md5_byte_t *) done.c_str(), done.size());
                md5_finish(&st, d);
            }
            
            string computed = digestToString( d );
            
            if ( key != computed ){
                log() << "auth: key mismatch " << user << ", ns:" << ns << endl;
                errmsg = "auth fails";
                return false;
            }

            AuthenticationInfo *ai = cc().getAuthenticationInfo();
            
            if ( userObj[ "readOnly" ].isBoolean() && userObj[ "readOnly" ].boolean() ) {
                if ( readLockSupported() ){
                    ai->authorizeReadOnly( cc().database()->name.c_str() );
                }
                else {
                    log() << "warning: old version of boost, read-only users not supported" << endl;
                    ai->authorize( cc().database()->name.c_str() );
                }
            } else {
                ai->authorize( cc().database()->name.c_str() );
            }
            return true;
        }
Ejemplo n.º 15
0
void setup_metadata(kbconfig *config)
{
    LOG(1, "Writing metadata.\n");

    fs_metadata *md = fs_metadata_open(config->name);
    fs_metadata_clear(md);
    fs_metadata_set(md, FS_MD_NAME, config->name);
    fs_metadata_set(md, FS_MD_HASHFUNC, FS_HASH);
    fs_metadata_set(md, FS_MD_STORE, "native");
    fs_metadata_set(md, FS_MD_MODEL_DATA, "true");
    if (config->model_files) {
        fs_metadata_set(md, FS_MD_MODEL_FILES, "true");
    } else {
        fs_metadata_set(md, FS_MD_MODEL_FILES, "false");
    }
    fs_metadata_set(md, FS_MD_CODE_VERSION, GIT_REV);
    for (int seg = 0; seg < config->segments; seg++) {
        if (primary_segment(config, seg))
	    fs_metadata_add_int(md, FS_MD_SEGMENT_P, seg);
        if (mirror_segment(config, seg))
	    fs_metadata_add_int(md, FS_MD_SEGMENT_M, seg);
    }

    /* Generate store UUID for skolemisation */
#if defined(USE_LINUX_UUID)
    uuid_t uu;
    uuid_string_t uus;
    uuid_generate(uu);
    uuid_unparse(uu, uus);
#elif defined(USE_BSD_UUID)
    uuid_t uu;
    char *uus = NULL;
    int status = -1;
    uuid_create(&uu, &status);
    if (status) { fs_error(LOG_ERR, "bad return from uuid_create"); exit(1); }
    uuid_to_string(&uu, &uus, &status);
    if (status || uus == NULL) { fs_error(LOG_ERR, "bad return from uuid_to_string"); exit(1); }
#elif defined(USE_OSSP_UUID)
    uuid_t *uu = NULL;
    char *uus = NULL;
    if (uuid_create(&uu)) { fs_error(LOG_ERR, "bad return from uuid_create"); exit(1); }
    if (uuid_make(uu, UUID_MAKE_V1)) { fs_error(LOG_ERR, "bad return from uuid_make"); exit(1); }
    if (uuid_export(uu, UUID_FMT_STR, &uus, NULL) || uus == NULL) { fs_error(LOG_ERR, "bad return from uuid_export"); exit(1); }
#endif
    fs_metadata_add(md, FS_MD_UUID, uus);
#if defined(USE_OSSP_UUID)
    uuid_destroy(uu);
#endif

    unsigned char stage1[20], stage2[16];
    char hash[33] = "none";
    int now = 0;
    if (config->password) {
        md5_state_t md5;
        char *pw = g_strdup_printf("%s:%s", config->name, config->password);

        /* stage1 will contain the 4 byte Unix time_t value as a salt ... */
        now = time(NULL);
        memcpy(stage1, &now, sizeof(now));

        /* ... followed by the on-wire 16 byte MD5 auth string */
	md5_init(&md5);
        md5_append(&md5, (md5_byte_t *) pw, strlen(pw));
        md5_finish(&md5, stage1 + 4);

        /* now use MD5 on all 20 bytes and store both the salt and the hash */
	md5_init(&md5);
        md5_append(&md5, stage1, sizeof(stage1));
        md5_finish(&md5, stage2);

        sprintf(hash, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                stage2[0], stage2[1], stage2[2], stage2[3], stage2[4], stage2[5],
	        stage2[6], stage2[7], stage2[8], stage2[9], stage2[10], stage2[11],
                stage2[12], stage2[13], stage2[14], stage2[15]);

        g_free(pw);
    }

    fs_metadata_add_int(md, FS_MD_VERSION, FS_CURRENT_TABLE_VERSION);
    fs_metadata_add_int(md, FS_MD_SEGMENTS, config->segments);
    fs_metadata_add_int(md, FS_MD_SALT, now);
    fs_metadata_add_int(md, FS_MD_BNODE, 1);
    fs_metadata_add(md, FS_MD_HASH, hash);
    fs_metadata_flush(md);
    fs_metadata_close(md);

    fs_error(LOG_INFO, "created RDF metadata for KB %s", config->name);
}
Ejemplo n.º 16
0
m64p_error open_rom(const unsigned char* romimage, unsigned int size)
{
    md5_state_t state;
    md5_byte_t digest[16];
    romdatabase_entry* entry;
    char buffer[256];
    unsigned char imagetype;
    int i;

    /* check input requirements */
    if (g_rom != NULL)
    {
        DebugMessage(M64MSG_ERROR, "open_rom(): previous ROM image was not freed");
        return M64ERR_INTERNAL;
    }
    if (romimage == NULL || !is_valid_rom(romimage))
    {
        DebugMessage(M64MSG_ERROR, "open_rom(): not a valid ROM image");
        return M64ERR_INPUT_INVALID;
    }

    /* Clear Byte-swapped flag, since ROM is now deleted. */
    g_MemHasBeenBSwapped = 0;
    /* allocate new buffer for ROM and copy into this buffer */
    g_rom_size = size;
    g_rom = (unsigned char *) malloc(size);
    if (g_rom == NULL)
        return M64ERR_NO_MEMORY;
    swap_copy_rom(g_rom, romimage, size, &imagetype);

    memcpy(&ROM_HEADER, g_rom, sizeof(m64p_rom_header));

    /* Calculate MD5 hash  */
    md5_init(&state);
    md5_append(&state, (const md5_byte_t*)g_rom, g_rom_size);
    md5_finish(&state, digest);
    for ( i = 0; i < 16; ++i )
        sprintf(buffer+i*2, "%02X", digest[i]);
    buffer[32] = '\0';
    strcpy(ROM_SETTINGS.MD5, buffer);

    /* add some useful properties to ROM_PARAMS */
    ROM_PARAMS.systemtype = rom_country_code_to_system_type(ROM_HEADER.Country_code);
    ROM_PARAMS.countperop = COUNT_PER_OP_DEFAULT;
    ROM_PARAMS.vitiming = ALTERNATE_VI_TIMING_DEFAULT;
    ROM_PARAMS.countperscanline = DEFAULT_COUNT_PER_SCANLINE;
    ROM_PARAMS.cheats = NULL;

    memcpy(ROM_PARAMS.headername, ROM_HEADER.Name, 20);
    ROM_PARAMS.headername[20] = '\0';
    trim(ROM_PARAMS.headername); /* Remove trailing whitespace from ROM name. */

    /* Look up this ROM in the .ini file and fill in goodname, etc */
    if ((entry=ini_search_by_md5(digest)) != NULL ||
        (entry=ini_search_by_crc(sl(ROM_HEADER.CRC1),sl(ROM_HEADER.CRC2))) != NULL)
    {
        strncpy(ROM_SETTINGS.goodname, entry->goodname, 255);
        ROM_SETTINGS.goodname[255] = '\0';
        ROM_SETTINGS.savetype = entry->savetype;
        ROM_SETTINGS.status = entry->status;
        ROM_SETTINGS.players = entry->players;
        ROM_SETTINGS.rumble = entry->rumble;
        ROM_PARAMS.countperop = entry->countperop;
        ROM_PARAMS.vitiming = entry->alternate_vi_timing;
        ROM_PARAMS.countperscanline = entry->count_per_scanline;
        ROM_PARAMS.cheats = entry->cheats;
    }
    else
    {
        strcpy(ROM_SETTINGS.goodname, ROM_PARAMS.headername);
        strcat(ROM_SETTINGS.goodname, " (unknown rom)");
        ROM_SETTINGS.savetype = NONE;
        ROM_SETTINGS.status = 0;
        ROM_SETTINGS.players = 0;
        ROM_SETTINGS.rumble = 0;
        ROM_PARAMS.countperop = COUNT_PER_OP_DEFAULT;
        ROM_PARAMS.vitiming = ALTERNATE_VI_TIMING_DEFAULT;
        ROM_PARAMS.countperscanline = DEFAULT_COUNT_PER_SCANLINE;
        ROM_PARAMS.cheats = NULL;
    }

    /* print out a bunch of info about the ROM */
    DebugMessage(M64MSG_INFO, "Goodname: %s", ROM_SETTINGS.goodname);
    DebugMessage(M64MSG_INFO, "Name: %s", ROM_HEADER.Name);
    imagestring(imagetype, buffer);
    DebugMessage(M64MSG_INFO, "MD5: %s", ROM_SETTINGS.MD5);
    DebugMessage(M64MSG_INFO, "CRC: %08" PRIX32 " %08" PRIX32, sl(ROM_HEADER.CRC1), sl(ROM_HEADER.CRC2));
    DebugMessage(M64MSG_INFO, "Imagetype: %s", buffer);
    DebugMessage(M64MSG_INFO, "Rom size: %d bytes (or %d Mb or %d Megabits)", g_rom_size, g_rom_size/1024/1024, g_rom_size/1024/1024*8);
    DebugMessage(M64MSG_VERBOSE, "ClockRate = %" PRIX32, sl(ROM_HEADER.ClockRate));
    DebugMessage(M64MSG_INFO, "Version: %" PRIX32, sl(ROM_HEADER.Release));
    if(sl(ROM_HEADER.Manufacturer_ID) == 'N')
        DebugMessage(M64MSG_INFO, "Manufacturer: Nintendo");
    else
        DebugMessage(M64MSG_INFO, "Manufacturer: %" PRIX32, sl(ROM_HEADER.Manufacturer_ID));
    DebugMessage(M64MSG_VERBOSE, "Cartridge_ID: %" PRIX16, ROM_HEADER.Cartridge_ID);
    countrycodestring(ROM_HEADER.Country_code, buffer);
    DebugMessage(M64MSG_INFO, "Country: %s", buffer);
    DebugMessage(M64MSG_VERBOSE, "PC = %" PRIX32, sl(ROM_HEADER.PC));
    DebugMessage(M64MSG_VERBOSE, "Save type: %d", ROM_SETTINGS.savetype);

    //Prepare Hack for GOLDENEYE
    isGoldeneyeRom = 0;
    if(strcmp(ROM_PARAMS.headername, "GOLDENEYE") == 0)
       isGoldeneyeRom = 1;

    return M64ERR_SUCCESS;
}
Ejemplo n.º 17
0
struct xt_node *xml_generate( irc_t *irc )
{
	char *pass_buf = NULL;
	account_t *acc;
	md5_byte_t pass_md5[21];
	md5_state_t md5_state;
	GSList *l;
	struct xt_node *root, *cur;
	
	/* Generate a salted md5sum of the password. Use 5 bytes for the salt
	   (to prevent dictionary lookups of passwords) to end up with a 21-
	   byte password hash, more convenient for base64 encoding. */
	random_bytes( pass_md5 + 16, 5 );
	md5_init( &md5_state );
	md5_append( &md5_state, (md5_byte_t*) irc->password, strlen( irc->password ) );
	md5_append( &md5_state, pass_md5 + 16, 5 ); /* Add the salt. */
	md5_finish( &md5_state, pass_md5 );
	/* Save the hash in base64-encoded form. */
	pass_buf = base64_encode( pass_md5, 21 );
	
	root = cur = xt_new_node( "user", NULL, NULL );
	xt_add_attr( cur, "nick", irc->user->nick );
	xt_add_attr( cur, "password", pass_buf );
	xt_add_attr( cur, "version", XML_FORMAT_VERSION );
	
	g_free( pass_buf );
	
	xml_generate_settings( cur, &irc->b->set );
	
	for( acc = irc->b->accounts; acc; acc = acc->next )
	{
		unsigned char *pass_cr;
		char *pass_b64;
		int pass_len;
		
		pass_len = arc_encode( acc->pass, strlen( acc->pass ), (unsigned char**) &pass_cr, irc->password, 12 );
		pass_b64 = base64_encode( pass_cr, pass_len );
		g_free( pass_cr );
		
		cur = xt_new_node( "account", NULL, NULL );
		xt_add_attr( cur, "protocol", acc->prpl->name );
		xt_add_attr( cur, "handle", acc->user );
		xt_add_attr( cur, "password", pass_b64 );
		xt_add_attr( cur, "autoconnect", acc->auto_connect ? "true" : "false" );
		xt_add_attr( cur, "tag", acc->tag );
		if( acc->server && acc->server[0] )
			xt_add_attr( cur, "server", acc->server );
		
		g_free( pass_b64 );
		
		/* This probably looks pretty strange. g_hash_table_foreach
		   is quite a PITA already (but it can't get much better in
		   C without using #define, I'm afraid), and it
		   doesn't seem to be possible to abort the foreach on write
		   errors, so instead let's use the _find function and
		   return TRUE on write errors. Which means, if we found
		   something, there was an error. :-) */
		g_hash_table_find( acc->nicks, xml_generate_nick, cur );
		
		xml_generate_settings( cur, &acc->set );
		
		xt_add_child( root, cur );
	}
	
	for( l = irc->channels; l; l = l->next )
	{
		irc_channel_t *ic = l->data;
		
		if( ic->flags & IRC_CHANNEL_TEMP )
			continue;
		
		cur = xt_new_node( "channel", NULL, NULL );
		xt_add_attr( cur, "name", ic->name );
		xt_add_attr( cur, "type", set_getstr( &ic->set, "type" ) );
		
		xml_generate_settings( cur, &ic->set );
		
		xt_add_child( root, cur );
	}
	
	return root;
}
Ejemplo n.º 18
0
static gboolean
is_duplicate_rel_time(guint8* fd, guint32 len, const nstime_t *current) {
  int i;
  md5_state_t ms;

  cur_dup_entry++;
  if (cur_dup_entry >= dup_window)
    cur_dup_entry = 0;

  /* Calculate our digest */
  md5_init(&ms);
  md5_append(&ms, fd, len);
  md5_finish(&ms, fd_hash[cur_dup_entry].digest);

  fd_hash[cur_dup_entry].len = len;
  fd_hash[cur_dup_entry].time.secs = current->secs;
  fd_hash[cur_dup_entry].time.nsecs = current->nsecs;

  /*
   * Look for relative time related duplicates.
   * This is hopefully a reasonably efficient mechanism for
   * finding duplicates by rel time in the fd_hash[] cache.
   * We check starting from the most recently added hash
   * entries and work backwards towards older packets.
   * This approach allows the dup test to be terminated
   * when the relative time of a cached entry is found to
   * be beyond the dup time window.
   *
   * Of course this assumes that the input trace file is
   * "well-formed" in the sense that the packet timestamps are
   * in strict chronologically increasing order (which is NOT
   * always the case!!).
   *
   * The fd_hash[] table was deliberatly created large (1,000,000).
   * Looking for time related duplicates in large trace files with
   * non-fractional dup time window values can potentially take
   * a long time to complete.
   */

  for (i = cur_dup_entry - 1;; i--) {
    nstime_t delta;
    int cmp;

    if (i < 0) {
      i = dup_window - 1;
    }

    if (i == cur_dup_entry) {
      /*
       * We've decremented back to where we started.
       * Check no more!
       */
      break;
    }

    if (nstime_is_unset(&(fd_hash[i].time))) {
      /*
       * We've decremented to an unused fd_hash[] entry.
       * Check no more!
       */
      break;
    }

    nstime_delta(&delta, current, &fd_hash[i].time);

    if(delta.secs < 0 || delta.nsecs < 0)
    {
      /*
       * A negative delta implies that the current packet
       * has an absolute timestamp less than the cached packet
       * that it is being compared to.  This is NOT a normal
       * situation since trace files usually have packets in
       * chronological order (oldest to newest).
       *
       * There are several possible ways to deal with this:
       * 1. 'continue' dup checking with the next cached frame.
       * 2. 'break' from looking for a duplicate of the current frame.
       * 3. Take the absolute value of the delta and see if that
       * falls within the specifed dup time window.
       *
       * Currently this code does option 1.  But it would pretty
       * easy to add yet-another-editcap-option to select one of
       * the other behaviors for dealing with out-of-sequence
       * packets.
       */
      continue;
    }

    cmp = nstime_cmp(&delta, &relative_time_window);

    if(cmp > 0) {
      /*
       * The delta time indicates that we are now looking at
       * cached packets beyond the specified dup time window.
       * Check no more!
       */
      break;
    } else if (fd_hash[i].len == fd_hash[cur_dup_entry].len &&
          memcmp(fd_hash[i].digest, fd_hash[cur_dup_entry].digest, 16) == 0) {
      return TRUE;
    }
  }

  return FALSE;
}
Ejemplo n.º 19
0
int
FCEUD_NetworkConnect(void)
{
    struct sockaddr_in sockin;
    struct hostent *phostentb;
    unsigned long hadr;
    int TSocket, tcpopt, error;
    int netdivisor;

    // get any required configuration variables
    int port, localPlayers;
    std::string server, username, password, key;
	server = "192.168.0.12";
	username = "xb";
	password = "";
	key = "";
	port = 4046;
	localPlayers = 2;

    // only initialize if remote server is specified
    if(!server.size()) {
        return 0;
    }

	XNetStartupParams xnsp;
	memset(&xnsp, 0, sizeof(xnsp));
	xnsp.cfgSizeOfStruct = sizeof(XNetStartupParams);
	xnsp.cfgFlags = XNET_STARTUP_BYPASS_SECURITY;

	xnsp.cfgSockDefaultRecvBufsizeInK = 16; // default = 16
	xnsp.cfgSockDefaultSendBufsizeInK = 16; // default = 16

	INT iResult = XNetStartup( &xnsp );

	WORD wVersionRequested;
	WSADATA wsaData;
	 
	wVersionRequested = MAKEWORD( 2, 2 );
	 
	WSAStartup( wVersionRequested, &wsaData );

    TSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(TSocket < 0) {
		DWORD err = GetLastError();

		char* s = "Error creating stream socket.";
        puts(s);
        FCEU_DispMessage(s,0);
        FCEUD_NetworkClose();
        return 0;
    }

    // try to setup TCP_NODELAY to avoid network jitters
    tcpopt = 1;
    error = setsockopt(TSocket, SOL_TCP, TCP_NODELAY, (char*)&tcpopt, sizeof(int));
    if(error) {
        puts("Nodelay fail");
    }

    memset(&sockin, 0, sizeof(sockin));
    sockin.sin_family = AF_INET;

    hadr = inet_addr(server.c_str());
    if(hadr != INADDR_NONE) {
        sockin.sin_addr.s_addr = hadr;
    } else {
#if 0 //marche pas
        puts("*** Looking up host name...");
        //phostentb = gethostbyname(server.c_str());

        if(!phostentb) {
            puts("Error getting host network information.");
            FCEU_DispMessage("Error getting host info",0);
            closesocket(TSocket);
            FCEUD_NetworkClose();
            return(0);
        }
        memcpy(&sockin.sin_addr, phostentb->h_addr, phostentb->h_length);
#endif
    }

    sockin.sin_port = htons(port);

    puts("*** Connecting to remote host...");
    error = connect(TSocket, (struct sockaddr *)&sockin, sizeof(sockin));
    if(error < 0) {
        puts("Error connecting to remote host.");
        FCEU_DispMessage("Error connecting to server",0);
        closesocket(TSocket);
        FCEUD_NetworkClose();
        return 0;
    }

    s_Socket = TSocket;

    puts("*** Sending initialization data to server...");
    uint8 *sendbuf;
    uint8 buf[5];
    uint32 sblen;

    sblen = 4 + 16 + 16 + 64 + 1 + username.size();
    sendbuf = (uint8 *)malloc(sblen);
    memset(sendbuf, 0, sblen);

    // XXX soules - should use htons instead of en32() from above!
    //uint32 data = htons(sblen - 4);
    //memcpy(sendbuf, &data, sizeof(data));
    en32(sendbuf, sblen - 4);

    if(key.size()) {
        struct md5_context md5;
        uint8 md5out[16];

        md5_starts(&md5);
        md5_update(&md5, (uint8*)&GameInfo->MD5.data, 16);
        md5_update(&md5, (uint8 *)key.c_str(), key.size());
        md5_finish(&md5, md5out);
        memcpy(sendbuf + 4, md5out, 16);
    } else {
        memcpy(sendbuf + 4, (uint8*)&GameInfo->MD5.data, 16);
    }

    if(password.size()) {
        struct md5_context md5;
        uint8 md5out[16];

        md5_starts(&md5);
        md5_update(&md5, (uint8 *)password.c_str(), password.size());
        md5_finish(&md5, md5out);
        memcpy(sendbuf + 4 + 16, md5out, 16);
    }

    memset(sendbuf + 4 + 16 + 16, 0, 64);

    sendbuf[4 + 16 + 16 + 64] = (uint8)localPlayers;

    if(username.size()) {
        memcpy(sendbuf + 4 + 16 + 16 + 64 + 1,
               username.c_str(), username.size());
    }

    send(s_Socket, (char*)sendbuf, sblen, 0);
    free(sendbuf);

    recv(s_Socket, (char*)buf, 1, 0);
    netdivisor = buf[0];

    puts("*** Connection established.");
    FCEU_DispMessage("Connection established.",0);

    FCEUDnetplay = 1;
    FCEUI_NetplayStart(localPlayers, netdivisor);

    return 1;
}
Ejemplo n.º 20
0
int ssl_derive_keys(ssl_context * ssl)
{
	size_t i;
	md5_context md5;
	sha1_context sha1;
	uint8_t tmp[64];
	uint8_t padding[16];
	uint8_t sha1sum[20];
	uint8_t keyblk[256];
	uint8_t *key1;
	uint8_t *key2;

	SSL_DEBUG_MSG(2, ("=> derive keys"));

	/*
	 * SSLv3:
	 *   master =
	 *     MD5( premaster + SHA1( 'A'   + premaster + randbytes ) ) +
	 *     MD5( premaster + SHA1( 'BB'  + premaster + randbytes ) ) +
	 *     MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )
	 *
	 * TLSv1:
	 *   master = PRF( premaster, "master secret", randbytes )[0..47]
	 */
	if (ssl->resume == 0) {
		size_t len = ssl->pmslen;

		SSL_DEBUG_BUF(3, "premaster secret", ssl->premaster, len);

		if (ssl->minor_ver == SSL_MINOR_VERSION_0) {
			for (i = 0; i < 3; i++) {
				memset(padding, 'A' + i, 1 + i);

				sha1_starts(&sha1);
				sha1_update(&sha1, padding, 1 + i);
				sha1_update(&sha1, ssl->premaster, len);
				sha1_update(&sha1, ssl->randbytes, 64);
				sha1_finish(&sha1, sha1sum);

				md5_starts(&md5);
				md5_update(&md5, ssl->premaster, len);
				md5_update(&md5, sha1sum, 20);
				md5_finish(&md5, ssl->session->master + i * 16);
			}
		} else
			tls1_prf(ssl->premaster, len, "master secret",
				 ssl->randbytes, 64, ssl->session->master, 48);

		memset(ssl->premaster, 0, sizeof(ssl->premaster));
	} else
		SSL_DEBUG_MSG(3, ("no premaster (session resumed)"));

	/*
	 * Swap the client and server random values.
	 */
	memcpy(tmp, ssl->randbytes, 64);
	memcpy(ssl->randbytes, tmp + 32, 32);
	memcpy(ssl->randbytes + 32, tmp, 32);
	memset(tmp, 0, sizeof(tmp));

	/*
	 *  SSLv3:
	 *    key block =
	 *      MD5( master + SHA1( 'A'    + master + randbytes ) ) +
	 *      MD5( master + SHA1( 'BB'   + master + randbytes ) ) +
	 *      MD5( master + SHA1( 'CCC'  + master + randbytes ) ) +
	 *      MD5( master + SHA1( 'DDDD' + master + randbytes ) ) +
	 *      ...
	 *
	 *  TLSv1:
	 *    key block = PRF( master, "key expansion", randbytes )
	 */
	if (ssl->minor_ver == SSL_MINOR_VERSION_0) {
		for (i = 0; i < 16; i++) {
			memset(padding, 'A' + i, 1 + i);

			sha1_starts(&sha1);
			sha1_update(&sha1, padding, 1 + i);
			sha1_update(&sha1, ssl->session->master, 48);
			sha1_update(&sha1, ssl->randbytes, 64);
			sha1_finish(&sha1, sha1sum);

			md5_starts(&md5);
			md5_update(&md5, ssl->session->master, 48);
			md5_update(&md5, sha1sum, 20);
			md5_finish(&md5, keyblk + i * 16);
		}

		memset(&md5, 0, sizeof(md5));
		memset(&sha1, 0, sizeof(sha1));

		memset(padding, 0, sizeof(padding));
		memset(sha1sum, 0, sizeof(sha1sum));
	} else
		tls1_prf(ssl->session->master, 48, "key expansion",
			 ssl->randbytes, 64, keyblk, 256);

	SSL_DEBUG_MSG(3, ("cipher = %s", ssl_get_cipher(ssl)));
	SSL_DEBUG_BUF(3, "master secret", ssl->session->master, 48);
	SSL_DEBUG_BUF(4, "random bytes", ssl->randbytes, 64);
	SSL_DEBUG_BUF(4, "key block", keyblk, 256);

	memset(ssl->randbytes, 0, sizeof(ssl->randbytes));

	/*
	 * Determine the appropriate key, IV and MAC length.
	 */
	switch (ssl->session->cipher) {
#if defined(TROPICSSL_ARC4)
	case TLS_RSA_WITH_RC4_128_MD5:
		ssl->keylen = 16;
		ssl->minlen = 16;
		ssl->ivlen = 0;
		ssl->maclen = 16;
		break;

	case TLS_RSA_WITH_RC4_128_SHA:
		ssl->keylen = 16;
		ssl->minlen = 20;
		ssl->ivlen = 0;
		ssl->maclen = 20;
		break;
#endif

#if defined(TROPICSSL_DES)
	case TLS_RSA_WITH_3DES_EDE_CBC_SHA:
	case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
		ssl->keylen = 24;
		ssl->minlen = 24;
		ssl->ivlen = 8;
		ssl->maclen = 20;
		break;
#endif

#if defined(TROPICSSL_AES)
	case TLS_RSA_WITH_AES_128_CBC_SHA:
		ssl->keylen = 16;
		ssl->minlen = 32;
		ssl->ivlen = 16;
		ssl->maclen = 20;
		break;

	case TLS_RSA_WITH_AES_256_CBC_SHA:
	case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
		ssl->keylen = 32;
		ssl->minlen = 32;
		ssl->ivlen = 16;
		ssl->maclen = 20;
		break;
#endif

#if defined(TROPICSSL_CAMELLIA)
	case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA:
		ssl->keylen = 16;
		ssl->minlen = 32;
		ssl->ivlen = 16;
		ssl->maclen = 20;
		break;

	case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA:
	case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA:
		ssl->keylen = 32;
		ssl->minlen = 32;
		ssl->ivlen = 16;
		ssl->maclen = 20;
		break;
#endif

	default:
		SSL_DEBUG_MSG(1, ("cipher %s is not available",
				  ssl_get_cipher(ssl)));
		return (TROPICSSL_ERR_SSL_FEATURE_UNAVAILABLE);
	}

	SSL_DEBUG_MSG(3, ("keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
			  ssl->keylen, ssl->minlen, ssl->ivlen, ssl->maclen));

	/*
	 * Finally setup the cipher contexts, IVs and MAC secrets.
	 */
	if (ssl->endpoint == SSL_IS_CLIENT) {
		key1 = keyblk + ssl->maclen * 2;
		key2 = keyblk + ssl->maclen * 2 + ssl->keylen;

		memcpy(ssl->mac_enc, keyblk, ssl->maclen);
		memcpy(ssl->mac_dec, keyblk + ssl->maclen, ssl->maclen);

		memcpy(ssl->iv_enc, key2 + ssl->keylen, ssl->ivlen);
		memcpy(ssl->iv_dec, key2 + ssl->keylen + ssl->ivlen,
		       ssl->ivlen);
	} else {
		key1 = keyblk + ssl->maclen * 2 + ssl->keylen;
		key2 = keyblk + ssl->maclen * 2;

		memcpy(ssl->mac_dec, keyblk, ssl->maclen);
		memcpy(ssl->mac_enc, keyblk + ssl->maclen, ssl->maclen);

		memcpy(ssl->iv_dec, key1 + ssl->keylen, ssl->ivlen);
		memcpy(ssl->iv_enc, key1 + ssl->keylen + ssl->ivlen,
		       ssl->ivlen);
	}

	switch (ssl->session->cipher) {
#if defined(TROPICSSL_ARC4)
	case TLS_RSA_WITH_RC4_128_MD5:
	case TLS_RSA_WITH_RC4_128_SHA:
		arc4_setup((arc4_context *) ssl->ctx_enc, key1, ssl->keylen);
		arc4_setup((arc4_context *) ssl->ctx_dec, key2, ssl->keylen);
		break;
#endif

#if defined(TROPICSSL_DES)
	case TLS_RSA_WITH_3DES_EDE_CBC_SHA:
	case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
		des3_set3key_enc((des3_context *) ssl->ctx_enc, key1);
		des3_set3key_dec((des3_context *) ssl->ctx_dec, key2);
		break;
#endif

#if defined(TROPICSSL_AES)
	case TLS_RSA_WITH_AES_128_CBC_SHA:
		aes_setkey_enc((aes_context *) ssl->ctx_enc, key1, 128);
		aes_setkey_dec((aes_context *) ssl->ctx_dec, key2, 128);
		break;

	case TLS_RSA_WITH_AES_256_CBC_SHA:
	case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
		aes_setkey_enc((aes_context *) ssl->ctx_enc, key1, 256);
		aes_setkey_dec((aes_context *) ssl->ctx_dec, key2, 256);
		break;
#endif

#if defined(TROPICSSL_CAMELLIA)
	case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA:
		camellia_setkey_enc((camellia_context *) ssl->ctx_enc, key1,
				    128);
		camellia_setkey_dec((camellia_context *) ssl->ctx_dec, key2,
				    128);
		break;

	case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA:
	case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA:
		camellia_setkey_enc((camellia_context *) ssl->ctx_enc, key1,
				    256);
		camellia_setkey_dec((camellia_context *) ssl->ctx_dec, key2,
				    256);
		break;
#endif

	default:
		return (TROPICSSL_ERR_SSL_FEATURE_UNAVAILABLE);
	}

	memset(keyblk, 0, sizeof(keyblk));

	SSL_DEBUG_MSG(2, ("<= derive keys"));

	return (0);
}
Ejemplo n.º 21
0
    Status CmdAuthenticate::_authenticateCR(const UserName& user, const BSONObj& cmdObj) {

        if (user == internalSecurity.user->getName() &&
            serverGlobalParams.clusterAuthMode == "x509") {
            return Status(ErrorCodes::AuthenticationFailed,
                          "Mechanism x509 is required for internal cluster authentication");
        }

        if (!_areNonceAuthenticateCommandsEnabled) {
            // SERVER-8461, MONGODB-CR must be enabled for authenticating the internal user, so that
            // cluster members may communicate with each other.
            if (user != internalSecurity.user->getName()) {
                return Status(ErrorCodes::BadValue, _nonceAuthenticateCommandsDisabledMessage);
            }
        }

        string key = cmdObj.getStringField("key");
        string received_nonce = cmdObj.getStringField("nonce");

        if( user.getUser().empty() || key.empty() || received_nonce.empty() ) {
            sleepmillis(10);
            return Status(ErrorCodes::ProtocolError,
                          "field missing/wrong type in received authenticate command");
        }

        stringstream digestBuilder;

        {
            ClientBasic *client = ClientBasic::getCurrent();
            boost::scoped_ptr<AuthenticationSession> session;
            client->swapAuthenticationSession(session);
            if (!session || session->getType() != AuthenticationSession::SESSION_TYPE_MONGO) {
                sleepmillis(30);
                return Status(ErrorCodes::ProtocolError, "No pending nonce");
            }
            else {
                nonce64 nonce = static_cast<MongoAuthenticationSession*>(session.get())->getNonce();
                digestBuilder << hex << nonce;
                if (digestBuilder.str() != received_nonce) {
                    sleepmillis(30);
                    return Status(ErrorCodes::AuthenticationFailed, "Received wrong nonce.");
                }
            }
        }

        User* userObj;
        Status status = getGlobalAuthorizationManager()->acquireUser(user, &userObj);
        if (!status.isOK()) {
            // Failure to find the privilege document indicates no-such-user, a fact that we do not
            // wish to reveal to the client.  So, we return AuthenticationFailed rather than passing
            // through the returned status.
            return Status(ErrorCodes::AuthenticationFailed, status.toString());
        }
        string pwd = userObj->getCredentials().password;
        getGlobalAuthorizationManager()->releaseUser(userObj);

        md5digest d;
        {
            digestBuilder << user.getUser() << pwd;
            string done = digestBuilder.str();

            md5_state_t st;
            md5_init(&st);
            md5_append(&st, (const md5_byte_t *) done.c_str(), done.size());
            md5_finish(&st, d);
        }

        string computed = digestToString( d );

        if ( key != computed ) {
            return Status(ErrorCodes::AuthenticationFailed, "key mismatch");
        }

        AuthorizationSession* authorizationSession =
            ClientBasic::getCurrent()->getAuthorizationSession();
        status = authorizationSession->addAndAuthorizeUser(user);
        if (!status.isOK()) {
            return status;
        }

        return Status::OK();
    }
Ejemplo n.º 22
0
/* internal variant of get_file_md5 that operates on a locked file */
static int gmx_fio_int_get_file_md5(t_fileio *fio, gmx_off_t offset,
                                    unsigned char digest[])
{
    /*1MB: large size important to catch almost identical files */
#define CPT_CHK_LEN  1048576
    md5_state_t   state;
    unsigned char buf[CPT_CHK_LEN];
    gmx_off_t     read_len;
    gmx_off_t     seek_offset;
    int           ret = -1;

    seek_offset = offset - CPT_CHK_LEN;
    if (seek_offset < 0)
    {
        seek_offset = 0;
    }
    read_len = offset - seek_offset;


    if (fio->fp && fio->bReadWrite)
    {
        ret = gmx_fseek(fio->fp, seek_offset, SEEK_SET);
        if (ret)
        {
            gmx_fseek(fio->fp, 0, SEEK_END);
        }
    }
    if (ret) /*either no fp, not readwrite, or fseek not successful */
    {
        return -1;
    }

    /* the read puts the file position back to offset */
    if ((gmx_off_t)fread(buf, 1, read_len, fio->fp) != read_len)
    {
        /* not fatal: md5sum check to prevent overwriting files
         * works (less safe) without
         * */
        if (ferror(fio->fp))
        {
            fprintf(stderr, "\nTrying to get md5sum: %s: %s\n", fio->fn,
                    strerror(errno));
        }
        else if (feof(fio->fp))
        {
            /*
             * For long runs that checkpoint frequently but write e.g. logs
             * infrequently we don't want to issue lots of warnings before we
             * have written anything to the log.
             */
            if (0)
            {
                fprintf(stderr, "\nTrying to get md5sum: EOF: %s\n", fio->fn);
            }
        }
        else
        {
            fprintf(
                    stderr,
                    "\nTrying to get md5sum: Unknown reason for short read: %s\n",
                    fio->fn);
        }

        gmx_fseek(fio->fp, 0, SEEK_END);

        ret = -1;
    }
    gmx_fseek(fio->fp, 0, SEEK_END); /*is already at end, but under windows
                                        it gives problems otherwise*/

    if (debug)
    {
        fprintf(debug, "chksum %s readlen %ld\n", fio->fn, (long int)read_len);
    }

    if (!ret)
    {
        md5_init(&state);
        md5_append(&state, buf, read_len);
        md5_finish(&state, digest);
        return read_len;
    }
    else
    {
        return ret;
    }
}
Ejemplo n.º 23
0
static void
dissect_frame(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree)
{
	proto_item	*volatile ti = NULL;
	nstime_t	ts;
	int		cap_len = 0, frame_len = 0;
	proto_tree	*volatile tree;
        proto_item  *item;
	guint32 frame_number;

	frame_number=pinfo->fd->num; /* dummy so that the buildbot crashdumps
					will show the packetnumber where the
					crash occurred.
				     */
	tree=parent_tree;

	pinfo->current_proto = "Frame";

	if (pinfo->pseudo_header != NULL) {
		switch (pinfo->fd->lnk_t) {

		case WTAP_ENCAP_WFLEET_HDLC:
		case WTAP_ENCAP_CHDLC_WITH_PHDR:
		case WTAP_ENCAP_PPP_WITH_PHDR:
		case WTAP_ENCAP_SDLC:
		case WTAP_ENCAP_BLUETOOTH_H4:
		case WTAP_ENCAP_BLUETOOTH_H4_WITH_PHDR:
			pinfo->p2p_dir = pinfo->pseudo_header->p2p.sent ?
			    P2P_DIR_SENT : P2P_DIR_RECV;
			break;

		case WTAP_ENCAP_BLUETOOTH_HCI:
			pinfo->p2p_dir = pinfo->pseudo_header->bthci.sent;
			break;

		case WTAP_ENCAP_LAPB:
		case WTAP_ENCAP_FRELAY_WITH_PHDR:
			pinfo->p2p_dir =
			    (pinfo->pseudo_header->x25.flags & FROM_DCE) ?
			    P2P_DIR_RECV : P2P_DIR_SENT;
			break;

		case WTAP_ENCAP_ISDN:
			pinfo->p2p_dir = pinfo->pseudo_header->isdn.uton ?
			    P2P_DIR_SENT : P2P_DIR_RECV;
			break;

		case WTAP_ENCAP_LINUX_LAPD:
			pinfo->p2p_dir = (pinfo->pseudo_header->lapd.pkttype == 3 ||
				pinfo->pseudo_header->lapd.pkttype == 4) ?
				P2P_DIR_SENT : P2P_DIR_RECV;
			break;

		case WTAP_ENCAP_MTP2_WITH_PHDR:
			pinfo->p2p_dir = pinfo->pseudo_header->mtp2.sent ?
			    P2P_DIR_SENT : P2P_DIR_RECV;
			pinfo->link_number  = pinfo->pseudo_header->mtp2.link_number;
			pinfo->annex_a_used = pinfo->pseudo_header->mtp2.annex_a_used;
			break;

		case WTAP_ENCAP_GSM_UM:
			pinfo->p2p_dir = pinfo->pseudo_header->gsm_um.uplink ?
			    P2P_DIR_SENT : P2P_DIR_RECV;
			break;

		}
	}

	/* if FRAME is not referenced from any filters we dont need to worry about
	   generating any tree items.  */
	if(!proto_field_is_referenced(tree, proto_frame)) {
        tree=NULL;
        if(pinfo->fd->abs_ts.nsecs < 0 || pinfo->fd->abs_ts.nsecs >= 1000000000)
            expert_add_info_format(pinfo, NULL, PI_MALFORMED, PI_WARN,
                "Arrival Time: Fractional second out of range (0-1000000000)");
    } else {
	    proto_tree	*fh_tree;

	  /* Put in frame header information. */
	  cap_len = tvb_length(tvb);
	  frame_len = tvb_reported_length(tvb);

	  ti = proto_tree_add_protocol_format(tree, proto_frame, tvb, 0, -1,
	    "Frame %u (%u bytes on wire, %u bytes captured)", pinfo->fd->num, frame_len, cap_len);

	  fh_tree = proto_item_add_subtree(ti, ett_frame);

	  ts = pinfo->fd->abs_ts;

	  proto_tree_add_time(fh_tree, hf_frame_arrival_time, tvb,
		0, 0, &ts);
	  if(ts.nsecs < 0 || ts.nsecs >= 1000000000) {
	    item = proto_tree_add_none_format(fh_tree, hf_frame_time_invalid, tvb,
	  	  0, 0, "Arrival Time: Fractional second %09ld is invalid, the valid range is 0-1000000000", (long) ts.nsecs);
	    PROTO_ITEM_SET_GENERATED(item);
	    expert_add_info_format(pinfo, item, PI_MALFORMED, PI_WARN, "Arrival Time: Fractional second out of range (0-1000000000)");
	  }

	  ts = pinfo->fd->del_cap_ts;

	  item = proto_tree_add_time(fh_tree, hf_frame_time_delta, tvb,
		0, 0, &ts);
	  PROTO_ITEM_SET_GENERATED(item);

	  ts = pinfo->fd->del_dis_ts;

	  item = proto_tree_add_time(fh_tree, hf_frame_time_delta_displayed, tvb,
		0, 0, &ts);
	  PROTO_ITEM_SET_GENERATED(item);

	  ts = pinfo->fd->rel_ts;

	  item = proto_tree_add_time(fh_tree, hf_frame_time_relative, tvb,
		0, 0, &ts);
	  PROTO_ITEM_SET_GENERATED(item);

	  if(pinfo->fd->flags.ref_time){
		ti = proto_tree_add_item(fh_tree, hf_frame_time_reference, tvb, 0, 0, FALSE);
		PROTO_ITEM_SET_GENERATED(ti);
	  }

	  proto_tree_add_uint(fh_tree, hf_frame_number, tvb,
		0, 0, pinfo->fd->num);

	  proto_tree_add_uint_format(fh_tree, hf_frame_len, tvb,
		0, 0, frame_len, "Frame Length: %d byte%s", frame_len,
		plurality(frame_len, "", "s"));

	  proto_tree_add_uint_format(fh_tree, hf_frame_capture_len, tvb,
		0, 0, cap_len, "Capture Length: %d byte%s", cap_len,
		plurality(cap_len, "", "s"));

	  if (generate_md5_hash) {
		  const guint8 *cp;
		  md5_state_t md_ctx;
		  md5_byte_t digest[16];
		  gchar *digest_string;

		  cp = tvb_get_ptr(tvb, 0, cap_len);

		  md5_init(&md_ctx);
		  md5_append(&md_ctx, cp, cap_len);
		  md5_finish(&md_ctx, digest);

		  digest_string = bytestring_to_str(digest, 16, '\0');
		  ti = proto_tree_add_string(fh_tree, hf_frame_md5_hash, tvb, 0, 0, digest_string);
		  PROTO_ITEM_SET_GENERATED(ti);
	  }

	  ti = proto_tree_add_boolean(fh_tree, hf_frame_marked, tvb, 0, 0,pinfo->fd->flags.marked);
	  PROTO_ITEM_SET_GENERATED(ti);

	  /* we are going to be using proto_item_append_string() on
	   * hf_frame_protocols, and we must therefore disable the
	   * TRY_TO_FAKE_THIS_ITEM() optimisation for the tree by
	   * setting it as visible.
	   *
	   * See proto.h for details.
	   */
	  proto_tree_set_visible(fh_tree, TRUE);

	  ti = proto_tree_add_string(fh_tree, hf_frame_protocols, tvb,
	  	0, 0, "");
	  PROTO_ITEM_SET_GENERATED(ti);
	  pinfo->layer_names = g_string_new("");

	  /* Check for existences of P2P pseudo header */
	  if (pinfo->p2p_dir != P2P_DIR_UNKNOWN) {
		  proto_tree_add_int(fh_tree, hf_frame_p2p_dir, tvb,
				  0, 0, pinfo->p2p_dir);
	  }

	  /* Check for existences of MTP2 link number */
	  if ((pinfo->pseudo_header != NULL ) && (pinfo->fd->lnk_t == WTAP_ENCAP_MTP2_WITH_PHDR)) {
		  proto_tree_add_uint(fh_tree, hf_link_number, tvb,
				  0, 0, pinfo->link_number);
	  }

	  if (show_file_off) {
		  proto_tree_add_int64_format(fh_tree, hf_frame_file_off, tvb,
				  0, 0, pinfo->fd->file_off,
				  "File Offset: %" G_GINT64_MODIFIER "d (0x%" G_GINT64_MODIFIER "x)",
				  pinfo->fd->file_off, pinfo->fd->file_off);
	  }

	  if(pinfo->fd->color_filter != NULL) {
	      color_filter_t *color_filter = pinfo->fd->color_filter;
	      item = proto_tree_add_string(fh_tree, hf_frame_color_filter_name, tvb,
		    0, 0, color_filter->filter_name);
	      PROTO_ITEM_SET_GENERATED(item);
	      item = proto_tree_add_string(fh_tree, hf_frame_color_filter_text, tvb,
		    0, 0, color_filter->filter_text);
	      PROTO_ITEM_SET_GENERATED(item);
	  }
    }

    /* Portable Exception Handling to trap Wireshark specific exceptions like BoundsError exceptions */
	TRY {
#ifdef _MSC_VER
    /* Win32: Visual-C Structured Exception Handling (SEH) to trap hardware exceptions like memory access violations */
    /* (a running debugger will be called before the except part below) */
    __try {
#endif
	if ((force_docsis_encap) && (docsis_handle)) {
	    call_dissector(docsis_handle, tvb, pinfo, parent_tree);
	} else {
            if (!dissector_try_port(wtap_encap_dissector_table, pinfo->fd->lnk_t,
                tvb, pinfo, parent_tree)) {

				col_set_str(pinfo->cinfo, COL_PROTOCOL, "UNKNOWN");
				col_add_fstr(pinfo->cinfo, COL_INFO, "WTAP_ENCAP = %u",
				    pinfo->fd->lnk_t);
			call_dissector(data_handle,tvb, pinfo, parent_tree);
		}
	}
#ifdef _MSC_VER
    } __except(TRUE /* handle all exceptions */) {
        switch(GetExceptionCode()) {
        case(STATUS_ACCESS_VIOLATION):
		    show_exception(tvb, pinfo, parent_tree, DissectorError,
                "STATUS_ACCESS_VIOLATION: dissector accessed an invalid memory address");
            break;
        case(STATUS_INTEGER_DIVIDE_BY_ZERO):
		    show_exception(tvb, pinfo, parent_tree, DissectorError,
                "STATUS_INTEGER_DIVIDE_BY_ZERO: dissector tried an integer division by zero");
            break;
        case(STATUS_STACK_OVERFLOW):
		    show_exception(tvb, pinfo, parent_tree, DissectorError,
                "STATUS_STACK_OVERFLOW: dissector overflowed the stack (e.g. endless loop)");
            /* XXX - this will have probably corrupted the stack, which makes problems later in the exception code */
            break;
        /* XXX - add other hardware exception codes as required */
        default:
		    show_exception(tvb, pinfo, parent_tree, DissectorError,
                g_strdup_printf("dissector caused an unknown exception: 0x%x", GetExceptionCode()));
        }
    }
#endif
	}
	CATCH(OutOfMemoryError) {
		RETHROW;
	}
	CATCH_ALL {
		show_exception(tvb, pinfo, parent_tree, EXCEPT_CODE, GET_MESSAGE);
	}
	ENDTRY;

	if (tree && pinfo->layer_names) {
		proto_item_append_string(ti, pinfo->layer_names->str);
		g_string_free(pinfo->layer_names, TRUE);
		pinfo->layer_names = NULL;
	}

	/*  Call postdissectors if we have any (while trying to avoid another
	 *  TRY/CATCH)
	 */
	if (have_postdissector()) {
	    TRY {
#ifdef _MSC_VER
	    /* Win32: Visual-C Structured Exception Handling (SEH) to trap hardware exceptions like memory access violations */
	    /* (a running debugger will be called before the except part below) */
	    __try {
#endif
		call_all_postdissectors(tvb, pinfo, parent_tree);
#ifdef _MSC_VER
	    } __except(TRUE /* handle all exceptions */) {
		switch(GetExceptionCode()) {
		case(STATUS_ACCESS_VIOLATION):
			    show_exception(tvb, pinfo, parent_tree, DissectorError,
			"STATUS_ACCESS_VIOLATION: dissector accessed an invalid memory address");
		    break;
		case(STATUS_INTEGER_DIVIDE_BY_ZERO):
			    show_exception(tvb, pinfo, parent_tree, DissectorError,
			"STATUS_INTEGER_DIVIDE_BY_ZERO: dissector tried an integer division by zero");
		    break;
		case(STATUS_STACK_OVERFLOW):
			    show_exception(tvb, pinfo, parent_tree, DissectorError,
			"STATUS_STACK_OVERFLOW: dissector overflowed the stack (e.g. endless loop)");
		    /* XXX - this will have probably corrupted the stack, which makes problems later in the exception code */
		    break;
		/* XXX - add other hardware exception codes as required */
		default:
			    show_exception(tvb, pinfo, parent_tree, DissectorError,
			g_strdup_printf("dissector caused an unknown exception: 0x%x", GetExceptionCode()));
		}
	    }
#endif
	    }
	    CATCH(OutOfMemoryError) {
		    RETHROW;
	    }
	    CATCH_ALL {
		    show_exception(tvb, pinfo, parent_tree, EXCEPT_CODE, GET_MESSAGE);
	    }
	    ENDTRY;
	}

	tap_queue_packet(frame_tap, pinfo, NULL);


	if (frame_end_routines) {
		g_slist_foreach(frame_end_routines, &call_frame_end_routine, NULL);
		g_slist_free(frame_end_routines);
		frame_end_routines = NULL;
	}
}
Ejemplo n.º 24
0
 void Hasher::finish( HashDigest out ) {
     md5_finish( &_md5State , out );
 }
Ejemplo n.º 25
0
static storage_status_t xml_save( irc_t *irc, int overwrite )
{
	char path[512], *path2, *pass_buf = NULL;
	set_t *set;
	account_t *acc;
	int fd;
	md5_byte_t pass_md5[21];
	md5_state_t md5_state;
	GSList *l;
	
	path2 = g_strdup( irc->user->nick );
	nick_lc( path2 );
	g_snprintf( path, sizeof( path ) - 2, "%s%s%s", global.conf->configdir, path2, ".xml" );
	g_free( path2 );
	
	if( !overwrite && g_access( path, F_OK ) == 0 )
		return STORAGE_ALREADY_EXISTS;
	
	strcat( path, ".XXXXXX" );
	if( ( fd = mkstemp( path ) ) < 0 )
	{
		irc_rootmsg( irc, "Error while opening configuration file." );
		return STORAGE_OTHER_ERROR;
	}
	
	/* Generate a salted md5sum of the password. Use 5 bytes for the salt
	   (to prevent dictionary lookups of passwords) to end up with a 21-
	   byte password hash, more convenient for base64 encoding. */
	random_bytes( pass_md5 + 16, 5 );
	md5_init( &md5_state );
	md5_append( &md5_state, (md5_byte_t*) irc->password, strlen( irc->password ) );
	md5_append( &md5_state, pass_md5 + 16, 5 ); /* Add the salt. */
	md5_finish( &md5_state, pass_md5 );
	/* Save the hash in base64-encoded form. */
	pass_buf = base64_encode( pass_md5, 21 );
	
	if( !xml_printf( fd, 0, "<user nick=\"%s\" password=\"%s\" version=\"%d\">\n", irc->user->nick, pass_buf, XML_FORMAT_VERSION ) )
		goto write_error;
	
	g_free( pass_buf );
	
	for( set = irc->b->set; set; set = set->next )
		if( set->value && !( set->flags & SET_NOSAVE ) )
			if( !xml_printf( fd, 1, "<setting name=\"%s\">%s</setting>\n", set->key, set->value ) )
				goto write_error;
	
	for( acc = irc->b->accounts; acc; acc = acc->next )
	{
		unsigned char *pass_cr;
		char *pass_b64;
		int pass_len;
		
		pass_len = arc_encode( acc->pass, strlen( acc->pass ), (unsigned char**) &pass_cr, irc->password, 12 );
		pass_b64 = base64_encode( pass_cr, pass_len );
		g_free( pass_cr );
		
		if( !xml_printf( fd, 1, "<account protocol=\"%s\" handle=\"%s\" password=\"%s\" "
		                        "autoconnect=\"%d\" tag=\"%s\"", acc->prpl->name, acc->user,
		                        pass_b64, acc->auto_connect, acc->tag ) )
		{
			g_free( pass_b64 );
			goto write_error;
		}
		g_free( pass_b64 );
		
		if( acc->server && acc->server[0] && !xml_printf( fd, 0, " server=\"%s\"", acc->server ) )
			goto write_error;
		if( !xml_printf( fd, 0, ">\n" ) )
			goto write_error;
		
		for( set = acc->set; set; set = set->next )
			if( set->value && !( set->flags & ACC_SET_NOSAVE ) )
				if( !xml_printf( fd, 2, "<setting name=\"%s\">%s</setting>\n", set->key, set->value ) )
					goto write_error;
		
		/* This probably looks pretty strange. g_hash_table_foreach
		   is quite a PITA already (but it can't get much better in
		   C without using #define, I'm afraid), and since it
		   doesn't seem to be possible to abort the foreach on write
		   errors, so instead let's use the _find function and
		   return TRUE on write errors. Which means, if we found
		   something, there was an error. :-) */
		if( g_hash_table_find( acc->nicks, xml_save_nick, & fd ) )
			goto write_error;
		
		if( !xml_printf( fd, 1, "</account>\n" ) )
			goto write_error;
	}
	
	for( l = irc->channels; l; l = l->next )
	{
		irc_channel_t *ic = l->data;
		
		if( ic->flags & IRC_CHANNEL_TEMP )
			continue;
		
		if( !xml_printf( fd, 1, "<channel name=\"%s\" type=\"%s\">\n",
		                 ic->name, set_getstr( &ic->set, "type" ) ) )
			goto write_error;
		
		for( set = ic->set; set; set = set->next )
			if( set->value && strcmp( set->key, "type" ) != 0 )
				if( !xml_printf( fd, 2, "<setting name=\"%s\">%s</setting>\n", set->key, set->value ) )
					goto write_error;
		
		if( !xml_printf( fd, 1, "</channel>\n" ) )
			goto write_error;
	}
	
	if( !xml_printf( fd, 0, "</user>\n" ) )
		goto write_error;
	
	fsync( fd );
	close( fd );
	
	path2 = g_strndup( path, strlen( path ) - 7 );
	if( rename( path, path2 ) != 0 )
	{
		irc_rootmsg( irc, "Error while renaming temporary configuration file." );
		
		g_free( path2 );
		unlink( path );
		
		return STORAGE_OTHER_ERROR;
	}
	
	g_free( path2 );
	
	return STORAGE_OK;

write_error:
	g_free( pass_buf );
	
	irc_rootmsg( irc, "Write error. Disk full?" );
	close( fd );
	
	return STORAGE_OTHER_ERROR;
}
Ejemplo n.º 26
0
Archivo: sasl.c Proyecto: mrdon/bitlbee
xt_status sasl_pkt_challenge( struct xt_node *node, gpointer data )
{
	struct im_connection *ic = data;
	struct jabber_data *jd = ic->proto_data;
	struct xt_node *reply_pkt = NULL;
	char *nonce = NULL, *realm = NULL, *cnonce = NULL;
	unsigned char cnonce_bin[30];
	char *digest_uri = NULL;
	char *dec = NULL;
	char *s = NULL, *reply = NULL;
	xt_status ret = XT_ABORT;
	
	if( node->text_len == 0 )
		goto error;
	
	dec = frombase64( node->text );
	
	if( jd->flags & JFLAG_SASL_FB )
	{
		/* New-style Facebook OAauth2 support. Instead of sending a refresh
		   token, they just send an access token that should never expire. */
		GSList *p_in = NULL, *p_out = NULL;
		char time[33];
		
		oauth_params_parse( &p_in, dec );
		oauth_params_add( &p_out, "nonce", oauth_params_get( &p_in, "nonce" ) );
		oauth_params_add( &p_out, "method", oauth_params_get( &p_in, "method" ) );
		oauth_params_free( &p_in );
		
		g_snprintf( time, sizeof( time ), "%lld", (long long) ( gettime() * 1000 ) );
		oauth_params_add( &p_out, "call_id", time );
		oauth_params_add( &p_out, "api_key", oauth2_service_facebook.consumer_key );
		oauth_params_add( &p_out, "v", "1.0" );
		oauth_params_add( &p_out, "format", "XML" );
		oauth_params_add( &p_out, "access_token", jd->oauth2_access_token );
		
		reply = oauth_params_string( p_out );
		oauth_params_free( &p_out );
	}
	else if( !( s = sasl_get_part( dec, "rspauth" ) ) )
	{
		/* See RFC 2831 for for information. */
		md5_state_t A1, A2, H;
		md5_byte_t A1r[16], A2r[16], Hr[16];
		char A1h[33], A2h[33], Hh[33];
		int i;
		
		nonce = sasl_get_part( dec, "nonce" );
		realm = sasl_get_part( dec, "realm" );
		
		if( !nonce )
			goto error;
		
		/* Jabber.Org considers the realm part optional and doesn't
		   specify one. Oh well, actually they're right, but still,
		   don't know if this is right... */
		if( !realm )
			realm = g_strdup( jd->server );
		
		random_bytes( cnonce_bin, sizeof( cnonce_bin ) );
		cnonce = base64_encode( cnonce_bin, sizeof( cnonce_bin ) );
		digest_uri = g_strdup_printf( "%s/%s", "xmpp", jd->server );
		
		/* Generate the MD5 hash of username:realm:password,
		   I decided to call it H. */
		md5_init( &H );
		s = g_strdup_printf( "%s:%s:%s", jd->username, realm, ic->acc->pass );
		md5_append( &H, (unsigned char *) s, strlen( s ) );
		g_free( s );
		md5_finish( &H, Hr );
		
		/* Now generate the hex. MD5 hash of H:nonce:cnonce, called A1. */
		md5_init( &A1 );
		s = g_strdup_printf( ":%s:%s", nonce, cnonce );
		md5_append( &A1, Hr, 16 );
		md5_append( &A1, (unsigned char *) s, strlen( s ) );
		g_free( s );
		md5_finish( &A1, A1r );
		for( i = 0; i < 16; i ++ )
			sprintf( A1h + i * 2, "%02x", A1r[i] );
		
		/* A2... */
		md5_init( &A2 );
		s = g_strdup_printf( "%s:%s", "AUTHENTICATE", digest_uri );
		md5_append( &A2, (unsigned char *) s, strlen( s ) );
		g_free( s );
		md5_finish( &A2, A2r );
		for( i = 0; i < 16; i ++ )
			sprintf( A2h + i * 2, "%02x", A2r[i] );
		
		/* Final result: A1:nonce:00000001:cnonce:auth:A2. Let's reuse H for it. */
		md5_init( &H );
		s = g_strdup_printf( "%s:%s:%s:%s:%s:%s", A1h, nonce, "00000001", cnonce, "auth", A2h );
		md5_append( &H, (unsigned char *) s, strlen( s ) );
		g_free( s );
		md5_finish( &H, Hr );
		for( i = 0; i < 16; i ++ )
			sprintf( Hh + i * 2, "%02x", Hr[i] );
		
		/* Now build the SASL response string: */
		reply = g_strdup_printf( "username=\"%s\",realm=\"%s\",nonce=\"%s\",cnonce=\"%s\","
		                         "nc=%08x,qop=auth,digest-uri=\"%s\",response=%s,charset=%s",
		                         jd->username, realm, nonce, cnonce, 1, digest_uri, Hh, "utf-8" );
	}
	else
	{
		/* We found rspauth, but don't really care... */
		g_free( s );
	}
	
	s = reply ? tobase64( reply ) : NULL;
	reply_pkt = xt_new_node( "response", s, NULL );
	xt_add_attr( reply_pkt, "xmlns", XMLNS_SASL );
	
	if( !jabber_write_packet( ic, reply_pkt ) )
		goto silent_error;
	
	ret = XT_HANDLED;
	goto silent_error;

error:
	imcb_error( ic, "Incorrect SASL challenge received" );
	imc_logout( ic, FALSE );

silent_error:
	g_free( digest_uri );
	g_free( cnonce );
	g_free( nonce );
	g_free( reply );
	g_free( realm );
	g_free( dec );
	g_free( s );
	xt_free_node( reply_pkt );
	
	return ret;
}
Ejemplo n.º 27
0
static gchar *
sasl_md5_prepare_response (LmSASL *sasl, GHashTable *challenge)
{
	GString     *response;
	const gchar *realm, *nonce;
	gchar       *a1, *a1h, *a2, *a2h, *kd, *kdh;
	gchar       *cnonce = NULL;
	gchar       *tmp;
	md5_byte_t   digest_md5[16];
	md5_state_t  md5_calc;
	gsize        len;

	response = g_string_new ("");

	if (sasl->username == NULL || sasl->password == NULL) {
		g_log (LM_LOG_DOMAIN, LM_LOG_LEVEL_SASL,
		       "%s: no username or password provided", G_STRFUNC);
		if (sasl->handler) {
			sasl->handler (sasl, sasl->connection, 
				       FALSE, "no username/password provided");
		}
		goto error;
	}

	nonce = g_hash_table_lookup (challenge, "nonce");
	if (nonce == NULL || nonce == '\0') {
		g_log (LM_LOG_DOMAIN, LM_LOG_LEVEL_SASL,
		       "%s: server didn't provide a nonce in the challenge", 
		       G_STRFUNC);
		if (sasl->handler) {
			sasl->handler (sasl, sasl->connection,
				       FALSE, "server error");
		}
		goto error;
	}

	cnonce = sasl_digest_md5_generate_cnonce ();

	/* FIXME challenge can contain multiple realms */
	realm = g_hash_table_lookup (challenge, "realm");
	if (realm == NULL) {
		realm = sasl->server;
	}

	/* FIXME properly escape values */
	g_string_append_printf (response, "username=\"%s\"", sasl->username);
	g_string_append_printf (response, ",realm=\"%s\"", realm);
	g_string_append_printf (response, ",digest-uri=\"xmpp/%s\"", realm);
	g_string_append_printf (response, ",nonce=\"%s\",nc=00000001", nonce);
	g_string_append_printf (response, ",cnonce=\"%s\"", cnonce);
	/* FIXME should check if auth is in the cop challenge val */
	g_string_append_printf (response, ",qop=auth,charset=utf-8");

	tmp = g_strdup_printf ("%s:%s:%s", 
			       sasl->username, realm, sasl->password);
	md5_init (&md5_calc);
	md5_append (&md5_calc, (const md5_byte_t *)tmp, strlen(tmp));
	md5_finish (&md5_calc, digest_md5);
	g_free (tmp);

	a1 = g_strdup_printf ("0123456789012345:%s:%s", nonce, cnonce);
	len = strlen (a1);
	memcpy (a1, digest_md5, 16);
	a1h = sasl_md5_hex_hash (a1, len);

	a2 = g_strdup_printf ("AUTHENTICATE:xmpp/%s", realm);
	a2h = sasl_md5_hex_hash (a2, strlen(a2));

	kd = g_strdup_printf ("%s:%s:00000001:%s:auth:%s",
			      a1h, nonce, cnonce, a2h);
	kdh = sasl_md5_hex_hash (kd, strlen(kd));
	g_string_append_printf (response, ",response=%s", kdh);

	g_free (kd);
	g_free (kdh);
	g_free (a2);
	g_free (a2h);

	/* Calculate the response we expect from the server */
	a2 = g_strdup_printf (":xmpp/%s", realm);
	a2h = sasl_md5_hex_hash (a2, strlen(a2));

	kd = g_strdup_printf ("%s:%s:00000001:%s:auth:%s", a1h, nonce, cnonce, a2h);
	g_free (sasl->digest_md5_rspauth);
	sasl->digest_md5_rspauth = sasl_md5_hex_hash (kd, strlen(kd));

	g_free (a1);
	g_free (a1h);
	g_free (a2);
	g_free (a2h);
	g_free (kd);

out:
	g_free (cnonce);
	if (response) {
		return g_string_free (response, FALSE);
	} else {
		return NULL;
	}

error:
	g_string_free (response, TRUE);
	response = NULL;
	goto out;
}
Ejemplo n.º 28
0
char* digest_authentication_encode(const char *line, const char *user, const char *passwd, 
		const char *method, const char *path, int count, const char *cnonce)
{
	char *realm = NULL, *opaque = NULL, *nonce = NULL, *qop = NULL;
	char nc[9];
	sprintf(nc, "%08x", count);

	const char *ptr = line;
	param_token name, value;

	while (extract_param(&ptr, &name, &value, ',')) {
		int namelen = name.e - name.b;
		int valuelen = value.e - value.b;
		
		if (strncasecmp(name.b, "realm" , namelen) == 0) {
			strncpy(realm  = calloc(valuelen + 1, 1), value.b, valuelen);
			realm[valuelen] = '\0';
		}
		else if (strncasecmp(name.b, "opaque", namelen) == 0) {
			strncpy(opaque = calloc(valuelen + 1, 1), value.b, valuelen);
			opaque[valuelen] = '\0';
		}
		else if (strncasecmp(name.b, "nonce" , namelen) == 0) {
			strncpy(nonce  = calloc(valuelen + 1, 1), value.b, valuelen);
			nonce[valuelen] = '\0';
		}
		else if (strncasecmp(name.b, "qop"   , namelen) == 0) {
			strncpy(qop    = calloc(valuelen + 1, 1), value.b, valuelen);
			qop[valuelen] = '\0';
		}
	}

	if (!realm || !nonce || !user || !passwd || !path || !method) {
		free(realm);
		free(opaque);
		free(nonce);
		free(qop);
		return NULL;
	}

	if (qop && strncasecmp(qop, "auth", 5) != 0) {
		/* FIXME: currently don't support auth-int, only "auth" is supported */
		free(realm);
		free(opaque);
		free(nonce);
		free(qop);
		return NULL;
	}

	/* calculate the digest value */
	md5_state_t ctx;
	md5_byte_t hash[MD5_HASHLEN];
	char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
	char response[MD5_HASHLEN * 2 + 1];

	/* A1 = username-value ":" realm-value ":" passwd */
	md5_init(&ctx);
	md5_append(&ctx, (md5_byte_t*)user, strlen(user));
	md5_append(&ctx, (md5_byte_t*)":", 1);
	md5_append(&ctx, (md5_byte_t*)realm, strlen(realm));
	md5_append(&ctx, (md5_byte_t*)":", 1);
	md5_append(&ctx, (md5_byte_t*)passwd, strlen(passwd));
	md5_finish(&ctx, hash);
	dump_hash(a1buf, hash);

	/* A2 = Method ":" digest-uri-value */
	md5_init(&ctx);
	md5_append(&ctx, (md5_byte_t*)method, strlen(method));
	md5_append(&ctx, (md5_byte_t*)":", 1);
	md5_append(&ctx, (md5_byte_t*)path, strlen(path));
	md5_finish(&ctx, hash);
	dump_hash(a2buf, hash);

	/* qop set: request-digest = H(A1) ":" nonce-value ":" nc-value ":" cnonce-value ":" qop-value ":" H(A2) */
	/* not set: request-digest = H(A1) ":" nonce-value ":" H(A2) */
	md5_init(&ctx);
	md5_append(&ctx, (md5_byte_t*)a1buf, strlen(a1buf));
	md5_append(&ctx, (md5_byte_t*)":", 1);
	md5_append(&ctx, (md5_byte_t*)nonce, strlen(nonce));
	md5_append(&ctx, (md5_byte_t*)":", 1);
	if (qop) {
		md5_append(&ctx, (md5_byte_t*)nc, strlen(nc));
		md5_append(&ctx, (md5_byte_t*)":", 1);
		md5_append(&ctx, (md5_byte_t*)cnonce, strlen(cnonce));
		md5_append(&ctx, (md5_byte_t*)":", 1);
		md5_append(&ctx, (md5_byte_t*)qop, strlen(qop));
		md5_append(&ctx, (md5_byte_t*)":", 1);
	}
	md5_append(&ctx, (md5_byte_t*)a2buf, strlen(a2buf));
	md5_finish(&ctx, hash);
	dump_hash(response, hash);

	/* prepare the final string */
	int len = 256;
	len += strlen(user);
	len += strlen(realm);
	len += strlen(nonce);
	len += strlen(path);
	len += strlen(response);

	if (qop) {
		len += strlen(qop);
		len += strlen(nc);
		len += strlen(cnonce);
	}

	if (opaque) {
		len += strlen(opaque);
	}

	char *res = (char*)malloc(len);
	if (!qop) {
		sprintf(res, "username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"", 
				user, realm, nonce, path, response);
	} else {
		sprintf(res, "username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\", qop=%s, nc=%s, cnonce=\"%s\"",
				user, realm, nonce, path, response, qop, nc, cnonce);
	}

	if (opaque) {
		char *p = res + strlen(res);
		strcat (p, ", opaque=\"");
		strcat (p, opaque);
		strcat (p, "\"");
	}

	free(realm);
	free(opaque);
	free(nonce);
	free(qop);
	return res;
}
Ejemplo n.º 29
0
static GdkPixbuf* _vfs_thumbnail_load( const char* file_path, const char* uri,
                                                                          int size, time_t mtime )
{
#if GLIB_CHECK_VERSION(2, 16, 0)
    GChecksum *cs;
#else
    md5_state_t md5_state;
    md5_byte_t md5[ 16 ];
#endif
    char file_name[ 40 ];
    char* thumbnail_file;
    char mtime_str[ 32 ];
    const char* thumb_mtime;
    int i, w, h;
    struct stat statbuf;
    GdkPixbuf* thumbnail, *result = NULL;

    if ( !gdk_pixbuf_get_file_info( file_path, &w, &h ) )
        return NULL;   /* image format cannot be recognized */

    /* If the image itself is very small, we should load it directly */
    if ( w <= 128 && h <= 128 )
    {
        if( w <= size && h <= size )
            return gdk_pixbuf_new_from_file( file_path, NULL );
        return gdk_pixbuf_new_from_file_at_size( file_path, size, size, NULL );
    }

#if GLIB_CHECK_VERSION(2, 16, 0)
    cs = g_checksum_new(G_CHECKSUM_MD5);
    g_checksum_update(cs, uri, strlen(uri));
    memcpy( file_name, g_checksum_get_string(cs), 32 );
    g_checksum_free(cs);
#else
    md5_init( &md5_state );
    md5_append( &md5_state, ( md5_byte_t * ) uri, strlen( uri ) );
    md5_finish( &md5_state, md5 );

    for ( i = 0; i < 16; ++i )
        sprintf( ( file_name + i * 2 ), "%02x", md5[ i ] );
#endif
    strcpy( ( file_name + 32 ), ".png" );

    thumbnail_file = g_build_filename( g_get_home_dir(),
                                       ".thumbnails/normal",
                                       file_name, NULL );

    if( G_UNLIKELY( 0 == mtime ) )
    {
        if( stat( file_path, &statbuf ) != -1 )
            mtime = statbuf.st_mtime;
    }

    /* load existing thumbnail */
    thumbnail = gdk_pixbuf_new_from_file( thumbnail_file, NULL );
    if ( !thumbnail ||
            !( thumb_mtime = gdk_pixbuf_get_option( thumbnail, "tEXt::Thumb::MTime" ) ) ||
            atol( thumb_mtime ) != mtime )
    {
        if( thumbnail )
            g_object_unref( thumbnail );
        /* create new thumbnail */
        thumbnail = gdk_pixbuf_new_from_file_at_size( file_path, 128, 128, NULL );
        if ( thumbnail )
        {
            sprintf( mtime_str, "%lu", mtime );
            gdk_pixbuf_save( thumbnail, thumbnail_file, "png", NULL,
                             "tEXt::Thumb::URI", uri, "tEXt::Thumb::MTime", mtime_str, NULL );
            chmod( thumbnail_file, 0600 );  /* only the owner can read it. */
        }
    }

    if ( thumbnail )
    {
        w = gdk_pixbuf_get_width( thumbnail );
        h = gdk_pixbuf_get_height( thumbnail );

        if ( w > h )
        {
            h = h * size / w;
            w = size;
        }
        else if ( h > w )
        {
            w = w * size / h;
            h = size;
        }
        else
        {
            w = h = size;
        }
        result = gdk_pixbuf_scale_simple(
                     thumbnail,
                     w, h, GDK_INTERP_BILINEAR );
        gdk_pixbuf_unref( thumbnail );
    }
    g_free( thumbnail_file );
    return result;
}
Ejemplo n.º 30
0
int FCEUD_NetworkConnect(void)
{
 WSADATA WSAData;
 SOCKADDR_IN sockin;    /* I want to play with fighting robots. */  /* clack clack clack razzzzzzzzzz */
 SOCKET TSocket;
 int netdivisor;

 if(WSAStartup(MAKEWORD(1,1),&WSAData))
 {
  NetStatAdd("*** Error initializing WIndows Sockets.");
  return(0);
 }
 wsainit=1;

 if( (TSocket=socket(AF_INET,SOCK_STREAM,0))==INVALID_SOCKET)
 {
  WSE("Error creating stream socket.");
  FCEUD_NetworkClose();
  return(0);
 }

 memset(&sockin,0,sizeof(sockin));
 sockin.sin_family=AF_INET;

 {
  struct hostent *phostentb;
  unsigned long hadr;
  int sockin_len;
  
  sockin.sin_port=0;
  sockin.sin_addr.s_addr=INADDR_ANY;
  sockin_len=sizeof(sockin);

  hadr=inet_addr(netplayhost);

  if(hadr!=INADDR_NONE)
   sockin.sin_addr.s_addr=hadr;
  else
  {
   NetStatAdd("*** Looking up host name...");
   if(!(phostentb=gethostbyname((const char *)netplayhost)))
   {
    WSE("Error getting host network information.");
    closesocket(TSocket);
    FCEUD_NetworkClose();
    return(0);
   }
   memcpy((char *)&sockin.sin_addr,((PHOSTENT)phostentb)->h_addr,((PHOSTENT)phostentb)->h_length);
  }

  sockin.sin_port=htons(remotetport);
  NetStatAdd("*** Connecting to remote host...");
  if(connect(TSocket,(PSOCKADDR)&sockin,sizeof(sockin))==SOCKET_ERROR)
  {
    WSE("Error connecting to remote host.");
    closesocket(TSocket);
    FCEUD_NetworkClose();
    return(0);
  }
  Socket=TSocket;
  NetStatAdd("*** Sending initialization data to server...");

  {
   uint8 *sendbuf;
   uint8 buf[1];
   uint32 sblen;

   sblen = 4 + 16 + 16 + 64 + 1 + (netplaynick?strlen(netplaynick):0);
   sendbuf = (uint8*)malloc(sblen); //mbg merge 7/17/06 added cast
   memset(sendbuf, 0, sblen);
                           
   en32(sendbuf, sblen - 4);
                           
   if(netgamekey)
   {
    struct md5_context md5;
    uint8 md5out[16];

    md5_starts(&md5);
    md5_update(&md5, (uint8*)&GameInfo->MD5.data, 16);
    md5_update(&md5, (uint8*)netgamekey, strlen(netgamekey)); //mbg merge 7/17/06 added cast
    md5_finish(&md5, md5out);
    memcpy(sendbuf + 4, md5out, 16);
   }
   else
    memcpy(sendbuf + 4, &GameInfo->MD5, 16);

   if(netpassword)
   {
    struct md5_context md5;
    uint8 md5out[16];
   
    md5_starts(&md5);
    md5_update(&md5, (uint8*)netpassword, strlen(netpassword));  //mbg merge 7/17/06 added cast
    md5_finish(&md5, md5out);
    memcpy(sendbuf + 4 + 16, md5out, 16);
   }
                        
   memset(sendbuf + 4 + 16 + 16, 0, 64);
   sendbuf[4 + 16 + 16 + 64] = netlocalplayers;

   if(netplaynick)
    memcpy(sendbuf + 4 + 16 + 16 + 64 + 1,netplaynick,strlen(netplaynick));

   send(Socket, (char*)sendbuf, sblen, 0); //mbg merge 7/17/06 added cast
   free(sendbuf);

   recv_tcpwrap(buf, 1);
   netdivisor = buf[0];
  }
 }


 FCEUI_NetplayStart(netlocalplayers,netdivisor);
 NetStatAdd("*** Connection established.");

 FCEUDnetplay = 1;
 char tcpopt = 1; //mbg merge 7/17/06 changed to char
 if(setsockopt(TSocket, IPPROTO_TCP, TCP_NODELAY, &tcpopt, sizeof(int)))
  puts("Nodelay fail");

 return(1);
}