Example #1
0
void CLeaderboard::SaveAndListAsync( const std::string& tableName,
	const CScore& score, bool highest, 
	bool allowDuplicates, const std::string& mode,
	int perPage,const CustomData& customFilter )
{
	char IdString[50];
	sprintf_s(IdString,49,"%d",gPlaytomic->GameId());
	std::string url = kLeaderboardUrl1 + gPlaytomic->GetGameGuid() + kLeaderboardUrlSaveAndList +
		IdString + kLeaderboardUrl3;

	CPostPtr postData(new CPost);
	postData->AddText("url", gPlaytomic->GetSourceUrl().c_str());
	postData->AddText("table", tableName.c_str());
	postData->AddText("highest", highest ? "y": "n");
	postData->AddText("name", score.GetName().c_str());
	char buff[300];
	sprintf_s(buff,299,"%d", score.GetPoints());
	postData->AddText("points", buff);

	sprintf_s(buff,299,"%s%d",gPlaytomic->GetSourceUrl().c_str(), score.GetPoints());
	postData->AddText("auth", MD5(buff).hexdigest().c_str());

	CustomData customData = score.GetCustomData();
	sprintf_s(buff,299,"%d", customData.size());
	postData->AddText("numfields", buff);

	int fieldNumber = 0;
	CustomData::iterator it = customData.begin();
	for(;it != customData.end(); it++)
	{
		sprintf_s(buff,299,"%d", fieldNumber);
		std::string ckey("ckey");
		ckey += buff;
		std::string cdata("cdata");
		cdata += buff;
		std::string value = it->second;
		fieldNumber++;

		postData->AddText(ckey.c_str(), it->first.c_str() );
		postData->AddText(cdata.c_str(), it->second.c_str());
	}

	//list fields
	postData->AddText("mode", mode.c_str());
	sprintf_s(buff, 299,"%d", perPage);
	postData->AddText("perpage", buff);
	sprintf_s(buff, 299,"%d", customFilter.size());
	postData->AddText("numfilters", buff);


	if(customFilter.size() > 0)
	{
		int fieldNumber = 0;
		CustomData::const_iterator it = customFilter.begin();
		for(;it != customFilter.end(); it++)
		{
			sprintf_s(buff,299,"%d", fieldNumber);
			std::string ckey("ckey");
			ckey += buff;
			std::string cdata("cdata");
			cdata += buff;
			std::string value = it->second;
			fieldNumber++;

			postData->AddText(ckey.c_str(), it->first.c_str() );
			postData->AddText(cdata.c_str(), it->second.c_str());
		}		
	}

	gConnectionInterface->PerformAsyncRequest(url.c_str(), fastdelegate::MakeDelegate(this, &CLeaderboard::SaveAndListComple),postData);

	
}
Example #2
0
	HttpAuthResult HttpAuthenticate(
		const char * challenge, size_t len,
		const SocketAddress& server,
		const std::string& method, const std::string& uri,
		const std::string& username, const CryptString& password,
		HttpAuthContext *& context, std::string& response, std::string& auth_method)
	{
#if TEST_DIGEST
		challenge = DIGEST_CHALLENGE;
		len = strlen(challenge);
#endif

		HttpAttributeList args;
		HttpParseAttributes(challenge, len, args);
		HttpHasNthAttribute(args, 0, &auth_method, NULL);

		if (context && (context->auth_method != auth_method))
			return HAR_IGNORE;

		// BASIC
		if (_stricmp(auth_method.c_str(), "basic") == 0) {
			if (context)
				return HAR_CREDENTIALS; // Bad credentials
			if (username.empty())
				return HAR_CREDENTIALS; // Missing credentials

			context = new HttpAuthContext(auth_method);

			// TODO: convert sensitive to a secure buffer that gets securely deleted
			//std::string decoded = username + ":" + password;
			size_t len = username.size() + password.GetLength() + 2;
			char * sensitive = new char[len];
			size_t pos = strcpyn(sensitive, len, username.data(), username.size());
			pos += strcpyn(sensitive + pos, len - pos, ":");
			password.CopyTo(sensitive + pos, true);

			response = auth_method;
			response.append(" ");
			// TODO: create a sensitive-source version of Base64::encode
			response.append(Base64::Encode(sensitive));
			memset(sensitive, 0, len);
			delete[] sensitive;
			return HAR_RESPONSE;
		}

		// DIGEST
		if (_stricmp(auth_method.c_str(), "digest") == 0) {
			if (context)
				return HAR_CREDENTIALS; // Bad credentials
			if (username.empty())
				return HAR_CREDENTIALS; // Missing credentials

			context = new HttpAuthContext(auth_method);

			std::string cnonce, ncount;
#if TEST_DIGEST
			method = DIGEST_METHOD;
			uri    = DIGEST_URI;
			cnonce = DIGEST_CNONCE;
#else
			char buffer[256];
			sprintf(buffer, "%d", static_cast<int>(LIB_MAN->time()));
			cnonce = MD5(buffer);
#endif
			ncount = "00000001";

			std::string realm, nonce, qop, opaque;
			HttpHasAttribute(args, "realm", &realm);
			HttpHasAttribute(args, "nonce", &nonce);
			bool has_qop = HttpHasAttribute(args, "qop", &qop);
			bool has_opaque = HttpHasAttribute(args, "opaque", &opaque);

			// TODO: convert sensitive to be secure buffer
			//std::string A1 = username + ":" + realm + ":" + password;
			size_t len = username.size() + realm.size() + password.GetLength() + 3;
			char * sensitive = new char[len];  // A1
			size_t pos = strcpyn(sensitive, len, username.data(), username.size());
			pos += strcpyn(sensitive + pos, len - pos, ":");
			pos += strcpyn(sensitive + pos, len - pos, realm.c_str());
			pos += strcpyn(sensitive + pos, len - pos, ":");
			password.CopyTo(sensitive + pos, true);

			std::string A2 = method + ":" + uri;
			std::string middle;
			if (has_qop) {
				qop = "auth";
				middle = nonce + ":" + ncount + ":" + cnonce + ":" + qop;
			}
			else {
				middle = nonce;
			}
			std::string HA1 = MD5(sensitive);
			memset(sensitive, 0, len);
			delete[] sensitive;
			std::string HA2 = MD5(A2);
			std::string dig_response = MD5(HA1 + ":" + middle + ":" + HA2);

#if TEST_DIGEST
			ASSERT(strcmp(dig_response.c_str(), DIGEST_RESPONSE) == 0);
#endif

			std::stringstream ss;
			ss << auth_method;
			ss << " username="******", realm=" << quote(realm);
			ss << ", nonce=" << quote(nonce);
			ss << ", uri=" << quote(uri);
			if (has_qop) {
				ss << ", qop=" << qop;
				ss << ", nc=" << ncount;
				ss << ", cnonce=" << quote(cnonce);
			}
			ss << ", response=\"" << dig_response << "\"";
			if (has_opaque) {
				ss << ", opaque=" << quote(opaque);
			}
			response = ss.str();
			return HAR_RESPONSE;
		}
		return HAR_IGNORE;
	}
Example #3
0
void hphp_compiler_init() {
  g_hphp_compiler_parse(nullptr, 0, MD5(), nullptr, Native::s_noNativeFuncs,
                        nullptr, false);
}
Example #4
0
/* Calculates the currently valid nonce value and copies it to result. Please note that nonce (may be NULL), opaque and result needs to be at least (MD5_DIGEST_LENGTH * 2) + 1 large. */
void calculate_nonce(char *nonce, char *result, char *opaque)
{
	struct s_nonce *noncelist, *prev, *foundnonce = NULL, *foundopaque = NULL, *foundexpired = NULL;
	int32_t bucket = opaque[0] % AUTHNONCEHASHBUCKETS;
	time_t now = time((time_t)0);
	cs_writelock(&nonce_lock[bucket]);
	for(noncelist = nonce_first[bucket], prev = NULL; noncelist; prev = noncelist, noncelist = noncelist->next)
	{
		if(now > noncelist->expirationdate)
		{
			if(prev) { prev->next = NULL; }
			else
			{
				nonce_first[bucket] = NULL;
			}
			foundexpired = noncelist;
			break;
		}
		if(nonce && !memcmp(noncelist->nonce, nonce, (MD5_DIGEST_LENGTH * 2) + 1))
		{
			memcpy(result, noncelist->nonce, (MD5_DIGEST_LENGTH * 2) + 1);
			foundnonce = noncelist;
			if(!noncelist->firstuse) { noncelist->firstuse = now; }
			else if(now - foundnonce->firstuse > AUTHNONCEVALIDSECS)
			{
				if(prev) { prev->next = noncelist->next; }
				else
				{
					nonce_first[bucket] = noncelist->next;
				}
			}
			break;
		}
		else if(!noncelist->firstuse && !memcmp(noncelist->opaque, opaque, (MD5_DIGEST_LENGTH * 2) + 1))
		{
			foundopaque = noncelist;
		}
	}
	if(foundnonce && now - foundnonce->firstuse > AUTHNONCEVALIDSECS)
	{
		free(foundnonce);
		foundnonce = NULL;
	}
	if(!foundnonce && foundopaque)
		{ memcpy(result, foundopaque->nonce, (MD5_DIGEST_LENGTH * 2) + 1); }
	if(!foundnonce && !foundopaque)
	{
		char noncetmp[128], randstr[16];
		unsigned char md5tmp[MD5_DIGEST_LENGTH];
		get_random_bytes((uint8_t *)randstr, sizeof(randstr) - 1);
		randstr[sizeof(randstr) - 1] = '\0';
		snprintf(noncetmp, sizeof(noncetmp), "%d:%s:%s", (int32_t)now, randstr, noncekey);
		char_to_hex(MD5((unsigned char *)noncetmp, strlen(noncetmp), md5tmp), MD5_DIGEST_LENGTH, (unsigned char *)result);
		if(cs_malloc(&noncelist, sizeof(struct s_nonce)))
		{
			noncelist->expirationdate = now + AUTHNONCEEXPIRATION;
			memcpy(noncelist->nonce, result, (MD5_DIGEST_LENGTH * 2) + 1);
			memcpy(noncelist->opaque, opaque, (MD5_DIGEST_LENGTH * 2) + 1);
			noncelist->next = nonce_first[bucket];
			nonce_first[bucket] = noncelist;
		}
	}
	cs_writeunlock(&nonce_lock[bucket]);
	while(foundexpired)
	{
		prev = foundexpired;
		foundexpired = foundexpired->next;
		free(prev);
	}
}
Example #5
0
 type MD5(const type& input) {
     type hash;
     MD5(input, hash);
     return hash;
 }
Example #6
0
int main(int argc, char** argv) {
    int i, retval;

    const char *usage = 
      "\nUsage: %s -app <app-name> [OPTIONS]\n"
      "Start validator for application <app-name>\n\n"
      "Optional arguments:\n"
      "  --one_pass_N_WU N       Validate at most N WUs, then exit\n"
      "  --one_pass              Make one pass through WU table, then exit\n"
      "  --mod n i               Process only WUs with (id mod n) == i\n"
      "  --max_claimed_credit X  If a result claims more credit than this, mark it as invalid\n"
      "  --max_granted_credit X  Grant no more than this amount of credit to a result\n"
      "  --grant_claimed_credit  Grant the claimed credit, regardless of what other results for this workunit claimed\n"
      "  --update_credited_job   Add record to credited_job table after granting credit\n"
      "  --credit_from_wu        Credit is specified in WU XML\n"
      "  --sleep_interval n      Set sleep-interval to n\n"
      "  -d n, --debug_level n   Set log verbosity level, 1-4\n"
      "  -h | --help             Show this\n"
      "  -v | --version          Show version information\n";

    if ((argc > 1) && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
        printf (usage, argv[0] );
        exit(0);
    }

    check_stop_daemons();

    for (i=1; i<argc; i++) {
        if (is_arg(argv[i], "one_pass_N_WU")) {
            one_pass_N_WU = atoi(argv[++i]);
            one_pass = true;
        } else if (is_arg(argv[i], "sleep_interval")) {
            sleep_interval = atoi(argv[++i]);
        } else if (is_arg(argv[i], "one_pass")) {
            one_pass = true;
        } else if (is_arg(argv[i], "app")) {
            strcpy(app_name, argv[++i]);
        } else if (is_arg(argv[i], "d") || is_arg(argv[i], "debug_level")) {
            debug_level = atoi(argv[++i]);
            log_messages.set_debug_level(debug_level);
            if (debug_level == 4) g_print_queries = true;
        } else if (is_arg(argv[i], "mod")) {
            wu_id_modulus = atoi(argv[++i]);
            wu_id_remainder = atoi(argv[++i]);
        } else if (is_arg(argv[i], "max_granted_credit")) {
            max_granted_credit = atof(argv[++i]);
        } else if (is_arg(argv[i], "max_claimed_credit")) {
            max_claimed_credit = atof(argv[++i]);
        } else if (is_arg(argv[i], "grant_claimed_credit")) {
            grant_claimed_credit = true;
        } else if (is_arg(argv[i], "update_credited_job")) {
            update_credited_job = true;
        } else if (is_arg(argv[i], "credit_from_wu")) {
            credit_from_wu = true;
        } else if (is_arg(argv[i], "v") || is_arg(argv[i], "version")) {
            printf("%s\n", SVN_VERSION);
            exit(0);
        } else if(!strcmp(argv[i], "-testmd5")) {
			unsigned char hash[16];
			char text[5] = "test";
			MD5((unsigned char*)&text, 4, (unsigned char *)&hash);
			string hex = HexToStr((const unsigned char *)&hash, 16);
			printf("test = %s", hex.c_str());		
		} else {
            fprintf(stderr,
                "Invalid option '%s'\nTry `%s --help` for more information\n",
                argv[i], argv[0]
            );
            log_messages.printf(MSG_CRITICAL, "unrecognized arg: %s\n", argv[i]);
            exit(1);
        }
    }

    if (app_name[0] == 0) {
        log_messages.printf(MSG_CRITICAL,
            "must use '--app' to specify an application\n"
        );
        printf (usage, argv[0] );
        exit(1);      
    }

    retval = config.parse_file();
    if (retval) {
        log_messages.printf(MSG_CRITICAL,
            "Can't parse config.xml: %s\n", boincerror(retval)
        );
        exit(1);
    }

    log_messages.printf(MSG_NORMAL,
        "Starting validator, debug level %d\n", log_messages.debug_level
    );
    if (wu_id_modulus) {
        log_messages.printf(MSG_NORMAL,
            "Modulus %d, remainder %d\n", wu_id_modulus, wu_id_remainder
        );
    }

    install_stop_signal_handler();

    main_loop();
}
Example #7
0
void handle_connection(int sock) {
    //TODO: fill me
    unsigned char buf[1024];
    // clear 0x1301000027
    int l = read(sock, buf, 5);
    printf("readlen: %d\n", l);
    // get loginmsg
    unsigned long buflen = 1024;
    read_message(sock, buf, &buflen);
    int i;
    if (buflen <= 0)
        return;
    if (buf[0] != 0x01)
        return;
    char *usr = (char*) malloc(buflen);
    for (i = 1; i < buflen; i++)
        usr[i - 1] = buf[i];
    usr[buflen] = 0;

    srand(time(0));
    char challange[34];
    challange[0] = 0x01;
    for (i = 1; i < 33; i++)
        challange[i] = (char) (rand() % 90) + 33;
    challange[33] = 0x00;
    send_message(sock, challange, 33);
    // challange send. wait for passord
    buflen = 1024;
    read_message(sock, buf, &buflen);

    char *md5pw = (char*) malloc(MD5_DIGEST_LENGTH * 2 + 1);

    for (i = 0; i < pwcount; i++) {
        int p;
        char *usrn = (char*) malloc(strlen(pwlist[i]));
        int j;
        for (j = 0; pwlist[i][j] != 0; j++) {
            usrn[j] = pwlist[i][j];
            if (pwlist[i][j] == ':') {
                usrn[j] = 0;
                break;
            }
        }
        printf("is user %s == %s?\n", usr, usrn);
        if (strcmp(usrn, usr) == 0) {
            printf("yes!\n");
            int k = 0;
            for (j = strlen(usr) + 1; pwlist[i][j] != 0; j++) {
                md5pw[k] = pwlist[i][j];
                k++;
            }
            md5pw[k] = 0;
            free(usrn);
            break;
        }
        free(usrn);
    }

    printf("found pw: %s\n", md5pw);

    char *challange_md5pw = (char*) malloc(strlen(challange) + strlen(md5pw));
    strcpy(challange_md5pw, challange);
    strcat(challange_md5pw, md5pw);
    ++challange_md5pw; // skip first char!

    unsigned char md5challange[MD5_DIGEST_LENGTH * 2];
    //unsigned char *md5challange_check = (char*) malloc(strlen(md5challange) + strlen(md5pw));
    MD5(challange_md5pw, strlen(challange_md5pw), md5challange);

    printf("md5: ");
    for (i = 0; i <= MD5_DIGEST_LENGTH; i++)
        printf("%d ", md5challange[i]);
    printf("\n");

    //FIXME: calc md5 of challange + md5pw
    //FIXME: check against recved challange
    //unsigned char md5challange[MD5_DIGEST_LENGTH];
    //unsigned char *md5challange_check = (char*) malloc(strlen(md5challange) + strlen(md5pw));

    //MD5(md5pw);

    buf[0] = 0x02;
    buf[1] = 'p';
    buf[2] = 'a';
    buf[3] = 's';
    buf[4] = 's';
    send_message(sock, buf, 5);

    free(usr);
}
Example #8
0
void
doYahooStep1(
        char       *buffer,
        const char *target,
        const char *username,
        const char *password,
        char       *cookie,
        size_t     *cookieSize
    )
{
    char    *request;
    char    *p, *q;
    char    src[MAX_NAMELEN];
    char    done[MAX_WEBPAGENAME];
    char    challenge[MAX_KEYLENGTH];
    char    u[MAX_USERIDLEN];
    char    passwd[BUFSIZ * 2];
    char    url[BUFSIZ * 2];
    int     tries     = 1;
    BOOL    escapeURL = TRUE;

    dputs( "doYahooStep1(): 実行開始\n" );

    // Yahoo! Japan にログイン
    request  = (char *)malloc( RCV_BUFFER_SIZE );
    if ( !request ) 
        return;

    src[0]       = NUL;
    done[0]      = NUL;
    challenge[0] = NUL;
    u[0]         = NUL;
    passwd[0]    = NUL;

    p = strstr( buffer, "name=\".tries\" value=\"" );
    if ( p ) {
        p += 21;
        q = strchr( p, '"' );
        if ( q ) {
            char    buf[BUFSIZ];

            strncpy( buf, p, q - p );
            buf[q - p] = NUL;
            tries = atol( buf );
        }
    }

    p = strstr( buffer, "name=\".src\" value=\"" );
    if ( p ) {
        p += 19;
        q = strchr( p, '"' );
        if ( q ) {
            strncpy( src, p, q - p );
            src[q - p] = NUL;
        }
    }
    p = strstr( buffer, "name=\".done\" value=\"" );
    if ( p ) {
        p += 20;
        q = strchr( p, '"' );
        if ( q ) {
            strncpy( done, p, q - p );
            done[q - p] = NUL;
        }
    }
    p = strstr( buffer, "name=\".challenge\" value=\"" );
    if ( p ) {
        p += 25;
        q = strchr( p, '"' );
        if ( q ) {
            strncpy( challenge, p, q - p );
            challenge[q - p] = NUL;
        }
    }
    p = strstr( buffer, "name=\".u\" value=\"" );
    if ( p ) {
        p += 17;
        q = strchr( p, '"' );
        if ( q ) {
            strncpy( u, p, q - p );
            u[q - p] = NUL;
        }
    }

    sprintf( passwd, "%s%s", ToLower(MD5(password)), challenge );
    strcpy( passwd, ToLower( MD5( passwd ) ) );

    strcpy( done, translateURL( done ) );
    p = strstr( done, "appdata" );
    if ( p ) {
        char    *r;
        p += 7;
        while ( ((q = strstr( p, "%3A" )) != NULL) ||
                ((q = strstr( p, "%2F" )) != NULL) ||
                ((q = strstr( p, "%2E" )) != NULL)    ) {
            r = p + strlen( p );
            while ( r > q ) {
                *(r + 2) = *r;
                r--;
            }
            *++q = '2';
            *++q = '5';
        }
    }

    strcpy( url, "http://login.yahoo.co.jp/config/login?" );
    sprintf( request,
             ".tries=%d&"
             ".src=%s&"
             ".md5=&"
             ".hash=&"
             ".js=1&"
             ".last=&"
             "promo=&"
             ".intl=jp&"
             ".bypass=&"
             ".partner=&"
             ".u=%s&"
             ".v=0&"
             ".challenge=%s&"
             ".yplus=&"
             ".emailCode=&"
             "pkg=&"
             "stepid=&"
             ".ev=&"
             "hasMsgr=0&"
             ".chkP=Y&"
             ".done=%s&"
             ".pd=&"
             ".protoctl=&"
             "login=%s&"
             "passwd=%s&"
             ".persistent=y&"
             ".hash=1&"
             ".md5=1",
             tries,
             src,
             u,
             challenge,
             done,
             username,
             passwd );
    strcat( url, request );

    if ( !strcmp( src, "ba_newsing" ) )
        escapeURL = FALSE;

    _httpGetIC( url, buffer, FALSE, escapeURL );
    if ( *buffer )
        doYahooStep1a( buffer, request, target,
                       username, password, cookie, cookieSize );

    free( request );
}
Example #9
0
	/* parsing lists {{{*/
	if(service)
	{
		xmlNodePtr memberships = findNode(service->children, "Memberships", 1);
		xmlNodePtr ms;
		xmlNodePtr role;
		xmlNodePtr members, member;
		xmlNodePtr pname;
		xmlNodePtr type;
		xmlNodePtr lastchange;
		xmlChar *content;
		int flag = 0;
		lastchange = findNode(service->children, "LastChange", 1);
		content = xmlNodeGetContent(lastchange);
		cl->lastchange = strdup((char*)content);
		DMSG(stderr, "Contact: lastchange = %s\n", cl->lastchange);
		if(!memberships)
		{
			fprintf(stderr, "NULL membership\n");
			count = 0;
			goto cleanup;
		}
		for(ms=memberships->children;ms;ms=ms->next)
		{
			int ctype = 1;
			if(!ms->children) continue;
			role = findNode(ms->children, "MemberRole", 1);
			if(!role)
			{
				fprintf(stderr, "Null role\n");
				count = 0;
				goto cleanup;
			}
			members = findNode(role, "Members", 1);
			if(!members) continue;

			if(xmlStrEqual(role->children->content, (xmlChar*)"Allow"))
				flag = 3;
			else if(xmlStrEqual(role->children->content, (xmlChar*)"Block"))
				flag = 4;
			else
				continue;

			for(member=members->children;member;member=member->next)
			{
				Contact *c;
				type = findNode(member->children, "Type", 1);
				content = xmlNodeGetContent(type);
				if(!content)
				{
					fprintf(stderr, "NULL Type\n");
					continue;
				}
				if(xmlStrEqual(content, (xmlChar*)"Passport"))
				{
					pname = findNode(member->children, "PassportName", 1);
					ctype = 1;
				}
				else if(xmlStrEqual(content, (xmlChar*)"Email"))
				{
					pname = findNode(member->children, "Email", 1);
					ctype = 32;
				}
				else
					continue;

				xmlFree(content);
				if(!pname) 
				{
					fprintf(stderr, "NULL PassportName or Email\n");
					continue;
				}
				content = xmlNodeGetContent(pname);
				if(content)
				{
					char name[32];
					char domain[32];
					if(sscanf((char*)content, "%[^@]@%s", name, domain) != 2)
					{
						fprintf(stderr, "parse contact: malformed email: %s\n", content);
						continue;
					}
					c = contact_new((char*)content);
					c->name = strdup(name);
					c->type = ctype;
					c->status = NA;
					c->inlist |= flag;
					c->domain = NULL; /* should be filled during sort */
					cl_append_contact(cl, c, name, domain);
					xmlFree(content);
					count++;
				}
			}
		}
	}/*}}}*/
	DMSG(stderr, "parsed contact count: %d\n", count);

cleanup:
	cl->flag &= ~CL_INITLIST;
	return count;

}/*}}}*/
int _cl_do_soapreq_ab(CL *cl)/*{{{*/
{
	TCPClient *client;
	char *req = NULL;
	char *header;
	char buf[512];
	int ret, len;
	char *ptr = NULL;
	client = tcpclient_new("contacts.msn.com", 80);
	ret = _cl_load_soapreq_ab(cl, cl->ablastchange, &req, TRUE);
	if(ret)
	{
		tcpclient_connect(client);
		header = (char*)xmalloc(strlen(ab_request_header) + 32);
		DMSG(stderr, "sending ab request\n");
		len = sprintf(header, "%s%d\r\n\r\n", ab_request_header, ret);
		if(tcpclient_send(client, header, len) <= 0) goto cleanup;
		if(tcpclient_send(client, req, ret) <= 0) goto cleanup;

		len = tcpclient_recv_header(client, &ptr); /* header */
		if(ptr)
		{
			HTTPHeader *header;
			xmlDocPtr doc;
			xmlParserCtxtPtr ctxt;
			FILE *fp;

			DMSG(stderr, "AB response header:\n%s", ptr);
			header = http_parse_header(ptr);
			len = header->content_length;
			DMSG(stderr, "Length: %d\n", len);
			http_header_destroy(header);
			memset(buf, 0, sizeof(buf));
			fp = fopen("addressbook.xml", "w");
			fprintf(fp, buf);
			len -= (ret = tcpclient_recv(client, buf, sizeof(buf)-1));
			ctxt = xmlCreatePushParserCtxt(NULL, NULL, buf, ret, "addressbook.xml");
			fprintf(fp, buf);
			if(ctxt == NULL)
			{
				fprintf(stderr, "failed to create parser context");
				return 0;
			}

			while(len > 0)
			{
				memset(buf, 0, sizeof(buf));
				len -= (ret=tcpclient_recv(client, buf, sizeof(buf)-1));
				fprintf(fp, buf);
				xmlParseChunk(ctxt, buf, ret, 0);
			}
			fclose(fp);
			xmlParseChunk(ctxt, buf, 0, 1);
			tcpclient_destroy(client);
			client = NULL;
			doc = ctxt->myDoc;
			len = ctxt->wellFormed;
			xmlFreeParserCtxt(ctxt);
			//count += _cl_parse_contacts(cl, doc);
			xmlFreeDoc(doc);
			xmlCleanupParser();
			DMSG(stderr, "addressbook xml parsing done: %s\n", len?"good":"malformed");
			xfree(ptr);
		}
		else
		{
			DMSG(stderr, "ab: no header found\n\r");
		}
	}
	else
	{
		fprintf(stderr, "failed to load abreq\n");
	}
cleanup:
	xfree(header);
	return 0;
}/*}}}*/
int cl_load_contacts(CL *cl, const char* file)/*{{{*/
{
	int ret;
	xmlDocPtr doc;
	xmlNodePtr root;
	xmlNodePtr contact;
	xmlNodePtr node;
	xmlChar *content;

	doc = xmlReadFile(file, NULL, 0);
	if (doc == NULL)
	{
		fprintf(stderr, "Failed to parse %s\n", file);
		return 0;
	}
	ret = 0;
	root = xmlDocGetRootElement(doc);
	contact = findNode(root->children, "contact", 3);
#define READSTR(dst,elem)  node = findNode(contact->children, elem, 1); \
	content = xmlNodeGetContent(node); \
	dst = strdup((char*)content); \
	xmlFree(content)

#define READINT(dst, elem) node = findNode(contact->children, elem, 1); \
		content = xmlNodeGetContent(node); \
		dst = atoi((char*)content); \
		xmlFree(content)
	for(;contact;contact=contact->next)
	{
		Contact *c;
		node = findNode(contact->children, "nick", 1);
		content = xmlNodeGetContent(node);
		c = contact_new((char*)content);
		xmlFree(content);
		READSTR(c->name, "name");
		READSTR(c->PSM, "PSM");
		READINT(c->inlist, "inlist");
		READINT(c->type, "type");
		c->status = NA;

		node = findNode(contact->children, "domain", 1);
		content = xmlNodeGetContent(node);
		c->domain = NULL; /* should be filled during sort */
		cl_append_contact(cl, c, c->name, (char*)content);
		xmlFree(content);
		ret++;
	}
	node = findNode(root->children, "lastchange", 3);
	if(node)
	{
		content = xmlNodeGetContent(node);
		cl->lastchange = strdup((char*)content);
		xmlFree(content);
	}
	xmlFreeDoc(doc);
	return ret;
}/*}}}*/
void cl_save(CL *cl, const char *filename)/*{{{*/
{
	Contact *c;
	FILE *fp = fopen(filename, "w");
	if(!fp) return;
	fprintf(fp, "<?xml version=\"1.0\" encoding=\"utf-8\"?>");
	fprintf(fp, "<contactinfo>");
	fprintf(fp, "<contacts>");
	for(c=cl->list;c;c=c->g_next)
	{
		fprintf(fp, "<contact>");
		fprintf(fp, "<name>%s</name>", c->name);
		fprintf(fp, "<nick>%s</nick>", c->nick);
		fprintf(fp, "<PSM>%s</PSM>", c->PSM?c->PSM:"");
		fprintf(fp, "<domain>%s</domain>", c->domain);
		fprintf(fp, "<inlist>%d</inlist>", c->inlist);
		fprintf(fp, "<type>%d</type>", c->type);
		fprintf(fp, "</contact>");
	}
	fprintf(fp, "</contacts>");
	if(cl->lastchange)
		fprintf(fp,"<lastchange>%s</lastchange>", cl->lastchange);
	if(cl->ablastchange)
		fprintf(fp,"<ablastchange>%s</ablastchange>", cl->ablastchange);
	fprintf(fp, "</contactinfo>");
	fflush(fp);
	fclose(fp);
}/*}}}*/
int _cl_do_soapreq_ms(CL *cl)/*{{{*/
{
	SSLClient *client;
	int ret;
	int len;
	int count = 0;
	char *req = NULL;
	char *header;
	char contactfile[64];
	FILE *fp;

	header = (char*)xmalloc(strlen(ms_request_header) + 32);

	client = sslclient_new(DEFAULTSERVER, 443);
	if(!sslclient_connect(client))
		return 0;
	/* connected */
	
	MD5((unsigned char*)cl->account->username, strlen(cl->account->username), (unsigned char*)contactfile);
	sprintf(contactfile, "%x%x.xml", (unsigned char)contactfile[0], (unsigned char)contactfile[1]);
	if((fp=fopen(contactfile, "r")))
	{
		DMSG(stderr, "loading cached contacts...\n");
		if((count = cl_load_contacts(cl, contactfile)))
			ret = _cl_load_soapreq_ms(cl, cl->lastchange, &req, FALSE);
		else
			ret = _cl_load_soapreq_ms(cl, cl->lastchange, &req, TRUE);
		DMSG(stderr, "%d contacts loaded from cache...\n", count);

		fclose(fp);
	}
	else
		ret = _cl_load_soapreq_ms(cl, cl->lastchange, &req, TRUE);
	if(ret)
	{
		char buf[512] = {0};
		char *ptr = NULL;
		xmlDocPtr doc;
		xmlParserCtxtPtr ctxt;
		FILE *fp;

		DMSG(stderr, "sending cl request\n");
		/* send request */
		len = sprintf(header, ms_request_header, ret);
		if(sslclient_send(client, header, len) <= 0) goto cleanup;
		if(sslclient_send(client, req, ret) <= 0) goto cleanup;

		DMSG(stderr, "getting cl response\n");
		/* get response */
		DMSG(stderr, "HEADER:\n");
		len = sslclient_recv_header(client, &ptr); /* header */
		if(ptr)
		{
			HTTPHeader *header;
			DMSG(stderr, ptr);
			header = http_parse_header(ptr);
			len = header->content_length;
			DMSG(stderr, "content length: %d\n", len);
			http_header_destroy(header);
			xfree(ptr);
		}
		else
		{
			DMSG(stderr, "no header found\n\r");
		}

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

		fp = fopen("contacts.xml", "w");
		len -= (ret = sslclient_recv(client, buf, sizeof(buf)-1));
		ctxt = xmlCreatePushParserCtxt(NULL, NULL, buf, ret, "contacts.xml");
		DMSG(stderr, "RESPONSE:\n");
		fprintf(fp, buf);
		if(ctxt == NULL)
		{
			fprintf(stderr, "failed to create parser context");
			return 0;
		}

		while(len > 0)
		{
			memset(buf, 0, sizeof(buf));
			len -= (ret=sslclient_recv(client, buf, sizeof(buf)-1));
			fprintf(fp, buf);
			xmlParseChunk(ctxt, buf, ret, 0);
		}
		fclose(fp);
		xmlParseChunk(ctxt, buf, 0, 1);
		sslclient_destroy(client, FALSE);
		client = NULL;
		doc = ctxt->myDoc;
		len = ctxt->wellFormed;
		xmlFreeParserCtxt(ctxt);
		count += _cl_parse_contacts(cl, doc);
		xmlFreeDoc(doc);
		xmlCleanupParser();
		DMSG(stderr, "contact xml parsing done: %s\n", len?"good":"malformed");
	}
	_cl_sort_contacts(cl);
	cl_save(cl, contactfile);
cleanup:
	xfree(req);
	xfree(header);
	return count;
}/*}}}*/
Example #10
0
int main(int argc, char**argv)
{
    int bg = 0, n, opt, port = 0, accountok = 0;
    struct sockaddr_in servaddr;
    socklen_t len;
    unsigned char mbuf[1000];
    unsigned char md5tmp[MD5_DIGEST_LENGTH];

    while ((opt = getopt(argc, argv, "bva:p:")) != -1) {
        switch (opt) {
        case 'b':
            bg = 1;
            break;
        case 'a': {
            char *ptr = strtok(optarg, ":");
            cs_strncpy((char *)&cl_user, ptr, sizeof(cl_user));
            ptr = strtok(NULL, ":");
            if(ptr) {
                cs_strncpy((char *)&cl_passwd, ptr, sizeof(cl_passwd));
                accountok = 1;
            }
            break;
        }
        case 'p':
            port = atoi(optarg);
            break;
        case 'v':
            debuglog = 1;
            break;
        default:
            show_usage(argv[0]);
            exit(0);
        }
    }
    if(port == 0 || accountok == 0) {
        show_usage(argv[0]);
        exit(0);
    }


    if (bg && do_daemon(1, 0))
    {
        fprintf(stderr, "Couldn't start as a daemon\n");
        exit(0);
    }

    get_random_bytes_init();

    cl_sockfd = socket(AF_INET,SOCK_DGRAM,0);

    bzero(&servaddr,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(port);
    bind(cl_sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));

    aes_set_key(&cl_aes_keys, (char *) MD5(cl_passwd, strlen((char *)cl_passwd), md5tmp));

    for (;;) {
        len = sizeof(cl_socket);
        n = recvfrom(cl_sockfd,mbuf,sizeof(mbuf),0,(struct sockaddr *)&cl_socket,&len);

        camd35_recv(mbuf, n);

        if(mbuf[0] == 0 || mbuf[0] == 3) {
            camd35_process_ecm(mbuf, n);
        } else {
            cs_log("unknown/not implemented camd35 command! (%d) n=%d", mbuf[0], n);
        }
    }
}
Example #11
0
BOOL
doYahooStep1b(
        char       *buffer,
        char       *request,
        const char *username,
        const char *password
    )
{
    char    *p, *q;
    char    src[MAX_NAMELEN];
    char    done[MAX_WEBPAGENAME];
    char    challenge[MAX_KEYLENGTH];
    char    u[MAX_USERIDLEN];
    char    passwd[BUFSIZ * 2];
    char    url[MAX_WEBPAGENAME];
    int     tries     = 2;
    BOOL    usePost   = FALSE;
    BOOL    ret       = FALSE;
    BOOL    escapeURL = TRUE;

    dputs( "doYahooStep1b(): 実行開始\n" );

    // パスワードの再確認
    src[0]       = NUL;
    done[0]      = NUL;
    challenge[0] = NUL;
    u[0]         = NUL;
    passwd[0]    = NUL;

    if ( strstr( buffer, "name=\"login_form\">" ) )
        usePost = TRUE;

    p = strstr( buffer, "name=\".tries\" value=\"" );
    if ( p ) {
        p += 21;
        q = strchr( p, '"' );
        if ( q ) {
            char    buf[BUFSIZ];

            strncpy( buf, p, q - p );
            buf[q - p] = NUL;
            tries = atol( buf );
        }
    }

    p = strstr( buffer, "name=\".src\" value=\"" );
    if ( p ) {
        p += 19;
        q = strchr( p, '"' );
        if ( q ) {
            strncpy( src, p, q - p );
            src[q - p] = NUL;
        }
    }
    p = strstr( buffer, "name=\".done\" value=\"" );
    if ( p ) {
        p += 20;
        q = strchr( p, '"' );
        if ( q ) {
            strncpy( done, p, q - p );
            done[q - p] = NUL;
        }
    }
    p = strstr( buffer, "name=\".challenge\" value=\"" );
    if ( p ) {
        p += 25;
        q = strchr( p, '"' );
        if ( q ) {
            strncpy( challenge, p, q - p );
            challenge[q - p] = NUL;
        }
    }
    p = strstr( buffer, "name=\".u\" value=\"" );
    if ( p ) {
        p += 17;
        q = strchr( p, '"' );
        if ( q ) {
            strncpy( u, p, q - p );
            u[q - p] = NUL;
        }
    }

    sprintf( passwd, "%s%s", ToLower(MD5(password)), challenge );
    strcpy( passwd, ToLower( MD5( passwd ) ) );

    if ( !strcmp( src, "ba_newsing" ) )
        escapeURL = FALSE;

    if ( escapeURL ) {
        strcpy( done, translateURL( done ) );
        p = strstr( done, "appdata" );
        if ( p ) {
            char    *r;
            p += 7;
            while ( ((q = strstr( p, "%3A" )) != NULL) ||
                    ((q = strstr( p, "%2F" )) != NULL) ||
                    ((q = strstr( p, "%2E" )) != NULL)    ) {
                r = p + strlen( p );
                while ( r > q ) {
                    *(r + 2) = *r;
                    r--;
                }
                *++q = '2';
                *++q = '5';
            }
        }
    }

    if ( strstr( buffer, "name=\"promo\" value=\"" ) ) {
        strcpy( url,
            usePost ? "https://login.yahoo.co.jp/config/login?"
                    : "http://login.yahoo.co.jp/config/login?" );
        sprintf( request,
                 ".tries=%d&"
                 ".src=%s&"
                 ".md5=&"
                 ".hash=&"
                 ".js=1&"
                 ".last=&"
                 "promo=&"
                 ".intl=jp&"
                 ".bypass=&"
                 ".partner=&"
                 ".u=%s&"
                 ".v=0&"
                 ".challenge=%s&"
                 ".yplus=&"
                 ".emailCode=&"
                 "pkg=&"
                 "stepid=&"
                 ".ev=&"
                 "hasMsgr=0&"
                 ".chkP=Y&"
                 ".done=%s&"
                 ".pd=&"
                 ".protoctl=&"
                 "login=%s&"
                 "passwd=%s&"
                 ".persistent=y&"
                 ".hash=1&"
                 ".md5=1",
                 tries,
                 src,
                 u,
                 challenge,
                 done,
                 username,
                 passwd );
    }
    else {
        strcpy( url, 
                usePost ? "https://login.yahoo.co.jp/config/login_verify2?"
                        : "http://login.yahoo.co.jp/config/login_verify2?" );
        sprintf( request,
                 usePost ? ".src=%s&"
                           ".tries=%d&"
                           ".done=%s&"
                           ".md5=&"
                           ".hash=&"
                           ".js=&"
                           ".partner=&"
                           ".slogin=%s&"
                           ".intl=jp&"
                           ".fUpdate=&"
                           ".prelog=&"
                           ".bid=&"
                           ".aucid=&"
                           ".challenge=%s&"
                           ".yplus=&"
                           ".chldID=&"
                           "pkg=&"
                           "hasMsgr=0&"
                           ".pd=&"
                           ".protoctl=&"
                           ".u=%s&"
                           "passwd=%s"
                         : ".src=%s&"
                           ".tries=%d&"
                           ".done=%s&"
                           ".md5=&"
                           ".hash=&"
                           ".js=1&"
                           ".partner=&"
                           ".slogin=%s&"
                           ".intl=jp&"
                           ".fUpdate=&"
                           ".prelog=&"
                           ".bid=&"
                           ".aucid=&"
                           ".challenge=%s&"
                           ".yplus=&"
                           ".chldID=&"
                           "pkg=&"
                           "hasMsgr=0&"
                           ".pd=&"
                           ".protoctl=&"
                           ".u=%s&"
                           "passwd=%s&"
                           ".hash=1&"
                           ".md5=1",
                 src,
                 tries,
                 done,
                 username,
                 challenge,
                 u,
                 usePost ? password : passwd );
    }
    if ( usePost ) {
        p = strstr( buffer, "<form method=\"post\" action=\"" );
        if ( p ) {
            p += 28;
            q = strchr( p, '"' );
            if ( q ) {
                strncpy( url, p, q - p );
                url[q - p] = NUL;
            }
        }

#ifdef  _DEBUG
        {
            FILE    *fp = fopen( "./bbauthPost.html", "w" );
            fputs( buffer, fp );
            fclose( fp );
        }
#endif

        _httpPostIC( url, request, buffer, escapeURL );

#ifdef  _DEBUG
        {
            FILE    *fp = fopen( "./bbauthPost2.html", "w" );
            fputs( buffer, fp );
            fclose( fp );
        }
#endif
    }
    else {
        strcat( url, request );
        _httpGetIC( url, buffer, FALSE, escapeURL );
    }
    if ( *buffer ) {
        if ( strstr( buffer, "<input type=\"submit\" class=\"fakebutton\"" ) )
            ret = TRUE;
    }

    return ( ret );
}
Example #12
0
void f_hash(void)
{
    const char *algo;
        const char *data;
        char *res;
        
        algo = (sp - 1)->u.string;
        data = sp->u.string;
        
        /* MD2 Digest */
        if (strcasecmp(algo, (const char *)"md2") == 0)
        {
            unsigned char md[MD2_DIGEST_LENGTH];
                MD2((unsigned char *)data, strlen(data), md);
                res = hexdump(md, MD2_DIGEST_LENGTH);
        }
    
        /* MD4 Digest */
        else if (strcasecmp(algo, (const char *)"md4") == 0)
        {
            unsigned char md[MD4_DIGEST_LENGTH];
                MD4((unsigned char *)data, strlen(data), md);      
                res = hexdump(md, MD4_DIGEST_LENGTH);      
        }
    
        /* MD5 Digest */
        else if (strcasecmp(algo, (const char *)"md5") == 0)
        {
            unsigned char md[MD5_DIGEST_LENGTH];
                MD5((unsigned char *)data, strlen(data), md);      
                res = hexdump(md, MD5_DIGEST_LENGTH);      
        }
    
        /* MDC2 Digest */
        else if (strcasecmp(algo, (const char *)"mdc2") == 0)
        {
            unsigned char md[MDC2_DIGEST_LENGTH];
                MDC2((unsigned char *)data, strlen(data), md);      
                res = hexdump(md, MDC2_DIGEST_LENGTH);      
        }
    
        /* RIPEMD160 Digest */
        else if (strcasecmp(algo, (const char *)"ripemd160") == 0)
        {
            unsigned char md[RIPEMD160_DIGEST_LENGTH];
                RIPEMD160((unsigned char *)data, strlen(data), md);      
                res = hexdump(md, RIPEMD160_DIGEST_LENGTH);      
        }
    
        /* SHA1 Digest */
        else if (strcasecmp(algo, (const char *)"sha1") == 0)
        {
            unsigned char md[SHA_DIGEST_LENGTH];
                SHA1((unsigned char *)data, strlen(data), md);
                res = hexdump(md, SHA_DIGEST_LENGTH);
        }
    
        else
        {
            pop_stack();
                res = malloc(29 + strlen(algo));
                sprintf(res, "hash() unknown hash type: %s.\n", algo);
                error(res);
        }
    
        /* Pop the arguments off the stack and push the result */
        free_string_svalue(sp--);
        free_string_svalue(sp);
        
        sp->subtype = STRING_MALLOC;
        sp->u.string = res;
}
Example #13
0
void cs_reinit_clients(struct s_auth *new_accounts)
{
	struct s_auth *account;
	unsigned char md5tmp[MD5_DIGEST_LENGTH];

	struct s_client *cl;
	for(cl = first_client->next; cl; cl = cl->next)
	{
		if((cl->typ == 'c' || cl->typ == 'm') && cl->account)
		{
			for(account = new_accounts; (account) ; account = account->next)
			{
				if(!strcmp(cl->account->usr, account->usr))
					{ break; }
			}
			if(account && !account->disabled && cl->pcrc == crc32(0L, MD5((uchar *)ESTR(account->pwd), strlen(ESTR(account->pwd)), md5tmp), MD5_DIGEST_LENGTH))
			{
				cl->account = account;
				if(cl->typ == 'c')
				{
					cl->grp = account->grp;
					cl->aureader_list   = account->aureader_list;
					cl->autoau = account->autoau;
					cl->expirationdate = account->expirationdate;
					cl->allowedtimeframe[0] = account->allowedtimeframe[0];
					cl->allowedtimeframe[1] = account->allowedtimeframe[1];
					cl->ncd_keepalive = account->ncd_keepalive;
					cl->c35_suppresscmd08 = account->c35_suppresscmd08;
					cl->tosleep = (60 * account->tosleep);
					cl->c35_sleepsend = account->c35_sleepsend;
					cl->monlvl = account->monlvl;
					cl->disabled    = account->disabled;
					cl->fchid   = account->fchid;  // CHID filters
					cl->cltab   = account->cltab;  // Class
					// newcamd module doesn't like ident reloading
					if(!cl->ncd_server)
						{ cl->ftab = account->ftab; }   // Ident

					cl->sidtabs.ok = account->sidtabs.ok;   // services
					cl->sidtabs.no = account->sidtabs.no;   // services
					cl->failban = account->failban;

					memcpy(&cl->ctab, &account->ctab, sizeof(cl->ctab));
					memcpy(&cl->ttab, &account->ttab, sizeof(cl->ttab));

					webif_client_reset_lastresponsetime(cl);
					if(account->uniq)
						{ cs_fake_client(cl, account->usr, (account->uniq == 1 || account->uniq == 2) ? account->uniq + 2 : account->uniq, cl->ip); }
					ac_init_client(cl, account);
				}
			}
			else
			{
				if(get_module(cl)->type & MOD_CONN_NET)
				{
					cs_debug_mask(D_TRACE, "client '%s', thread=%8lX not found in db (or password changed)", cl->account->usr, (unsigned long)cl->thread);
					kill_thread(cl);
				}
				else
				{
					cl->account = first_client->account;
				}
			}
		}
		else
		{
			cl->account = NULL;
		}
	}
}
Example #14
0
int32_t cs_auth_client(struct s_client *client, struct s_auth *account, const char *e_txt)
{
	int32_t rc = 0;
	unsigned char md5tmp[MD5_DIGEST_LENGTH];
	char buf[32];
	char *t_crypt = "encrypted";
	char *t_plain = "plain";
	char *t_grant = " granted";
	char *t_reject = " rejected";
	char *t_msg[] = { buf, "invalid access", "invalid ip", "unknown reason", "protocol not allowed" };
	struct s_module *module = get_module(client);

	memset(&client->grp, 0xff, sizeof(uint64_t));
	//client->grp=0xffffffffffffff;
	if((intptr_t)account != 0 && (intptr_t)account != -1 && account->disabled)
	{
		cs_add_violation(client, account->usr);
		cs_log("%s %s-client %s%s (%s%sdisabled account)",
			   client->crypted ? t_crypt : t_plain,
			   module->desc,
			   IP_ISSET(client->ip) ? cs_inet_ntoa(client->ip) : "",
			   IP_ISSET(client->ip) ? t_reject : t_reject + 1,
			   e_txt ? e_txt : "",
			   e_txt ? " " : "");
		return 1;
	}

	// check whether client comes in over allowed protocol
	if((intptr_t)account != 0 && (intptr_t)account != -1 && (intptr_t)account->allowedprotocols &&
			(((intptr_t)account->allowedprotocols & module->listenertype) != module->listenertype))
	{
		cs_add_violation(client, account->usr);
		cs_log("%s %s-client %s%s (%s%sprotocol not allowed)",
			   client->crypted ? t_crypt : t_plain,
			   module->desc,
			   IP_ISSET(client->ip) ? cs_inet_ntoa(client->ip) : "",
			   IP_ISSET(client->ip) ? t_reject : t_reject + 1,
			   e_txt ? e_txt : "",
			   e_txt ? " " : "");
		return 1;
	}

	client->account = first_client->account;
	switch((intptr_t)account)
	{

	case 0:   // reject access
	{
		rc = 1;
		cs_add_violation(client, NULL);
		cs_log("%s %s-client %s%s (%s)",
			   client->crypted ? t_crypt : t_plain,
			   module->desc,
			   IP_ISSET(client->ip) ? cs_inet_ntoa(client->ip) : "",
			   IP_ISSET(client->ip) ? t_reject : t_reject + 1,
			   e_txt ? e_txt : t_msg[rc]);
		break;
	}

	default:   // grant/check access
	{
		if(IP_ISSET(client->ip) && account->dyndns)
		{
			if(!IP_EQUAL(client->ip, account->dynip))
				{ cs_user_resolve(account); }
			if(!IP_EQUAL(client->ip, account->dynip))
			{
				cs_add_violation(client, account->usr);
				rc = 2;
			}
		}
		client->monlvl = account->monlvl;
		client->account = account;
		if(!rc)
		{
			client->dup = 0;
			if(client->typ == 'c' || client->typ == 'm')
				{ client->pcrc = crc32(0L, MD5((uchar *)(ESTR(account->pwd)), strlen(ESTR(account->pwd)), md5tmp), MD5_DIGEST_LENGTH); }
			if(client->typ == 'c')
			{
				client->last_caid = NO_CAID_VALUE;
				client->last_srvid = NO_SRVID_VALUE;
				client->expirationdate = account->expirationdate;
				client->disabled = account->disabled;
				client->allowedtimeframe[0] = account->allowedtimeframe[0];
				client->allowedtimeframe[1] = account->allowedtimeframe[1];
				if(account->firstlogin == 0) { account->firstlogin = time((time_t *)0); }
				client->failban = account->failban;
				client->c35_suppresscmd08 = account->c35_suppresscmd08;
				client->ncd_keepalive = account->ncd_keepalive;
				client->grp = account->grp;
				client->aureader_list = account->aureader_list;
				client->autoau = account->autoau;
				client->tosleep = (60 * account->tosleep);
				client->c35_sleepsend = account->c35_sleepsend;
				memcpy(&client->ctab, &account->ctab, sizeof(client->ctab));
				if(account->uniq)
					{ cs_fake_client(client, account->usr, account->uniq, client->ip); }
				client->ftab  = account->ftab;   // IDENT filter
				client->cltab = account->cltab;  // CLASS filter
				client->fchid = account->fchid;  // CHID filter
				client->sidtabs.ok = account->sidtabs.ok;  // services
				client->sidtabs.no = account->sidtabs.no;  // services
				memcpy(&client->ttab, &account->ttab, sizeof(client->ttab));
				ac_init_client(client, account);
			}
		}
	}

	case -1:   // anonymous grant access
	{
		if(rc)
		{
			t_grant = t_reject;
		}
		else
		{
			if(client->typ == 'm')
			{
				snprintf(t_msg[0], sizeof(buf), "lvl=%d", client->monlvl);
			}
			else
			{
				int32_t rcount = ll_count(client->aureader_list);
				snprintf(buf, sizeof(buf), "au=");
				if(!rcount)
					{ snprintf(buf + 3, sizeof(buf) - 3, "off"); }
				else
				{
					if(client->autoau)
						{ snprintf(buf + 3, sizeof(buf) - 3, "auto (%d reader)", rcount); }
					else
						{ snprintf(buf + 3, sizeof(buf) - 3, "on (%d reader)", rcount); }
				}
			}
		}
		cs_log("%s %s-client %s%s (%s, %s)",
			   client->crypted ? t_crypt : t_plain,
			   e_txt ? e_txt : module->desc,
			   IP_ISSET(client->ip) ? cs_inet_ntoa(client->ip) : "",
			   IP_ISSET(client->ip) ? t_grant : t_grant + 1,
			   username(client), t_msg[rc]);
		break;
	}
	}
	return rc;
}
Example #15
0
BOOL RADIUS_MONITOR(char *server, int port, char *secret, char *uid, char *pwd, 
					int timeout, char *match, char *custpath, char *szReturn)
{
	int		i = 0, 
			j = 0;
	int		ulen = strlen(uid), 
			plen = strlen(pwd), 
			slen = strlen(secret);

	SOCKET	s;
	struct	hostent *hp = NULL;
	struct	sockaddr_in	serv;

	DWORD	dwBeginTime = 0, 
			dwEndTime = 0;

	u_char	request[1000] = {0};
	int		reqlen = 0;
	u_char	response[1000] = {0};

	srand((unsigned)time(NULL));

	s = socket(AF_INET, SOCK_DGRAM, 0);
	if(s == INVALID_SOCKET)
	{
		// Create Communication Error
		sprintf(szReturn, "error=%s", ::FuncGetStringFromIDS("<%IDS_Radius_1%>"));//<%IDS_Radius_1%>
		return FALSE;
	}

	hp = gethostbyname(server);
	if(hp == NULL)
	{
		// DNS Resolve Error
		sprintf(szReturn, "error=%s", ::FuncGetStringFromIDS("<%IDS_Radius_2%>"));//<%IDS_Radius_2%>
		return FALSE;
	}

	memcpy(&serv.sin_addr,hp->h_addr_list[0],hp->h_length);
    serv.sin_family = AF_INET;
    serv.sin_port = htons(port);

	// construct access-request packet
	request[reqlen++] = 0x01;				// Code
	request[reqlen++] = rand() % 0xFF;		// Identifier
	reqlen += 2;							// Length
	request[reqlen++] = rand() % 0xFF;		// Request Authenticator
	request[reqlen++] = rand() % 0xFF;
	request[reqlen++] = rand() % 0xFF;
	request[reqlen++] = rand() % 0xFF;
	request[reqlen++] = rand() % 0xFF;
	request[reqlen++] = rand() % 0xFF;
	request[reqlen++] = rand() % 0xFF;
	request[reqlen++] = rand() % 0xFF;
	request[reqlen++] = rand() % 0xFF;
	request[reqlen++] = rand() % 0xFF;
	request[reqlen++] = rand() % 0xFF;
	request[reqlen++] = rand() % 0xFF;
	request[reqlen++] = rand() % 0xFF;
	request[reqlen++] = rand() % 0xFF;
	request[reqlen++] = rand() % 0xFF;
	request[reqlen++] = rand() % 0xFF;

	request[reqlen++] = 0x01;				// Attribute Username
	request[reqlen++] = 0x02 + ulen;
	for(i = 0;i < ulen;i ++)
		request[reqlen++] = uid[i];

	request[reqlen++] = 0x02;				// Attribute Password (crypt)
	request[reqlen++] = 0x02 + (plen % 0x10 ? (plen / 0x10 + 1) * 0x10 : plen);

	/*******************************************************************
	 *  shared secret: S
	 *	pseudo-random 128-bit request authenticator: RA
	 *	password chuncks: P1, P2, P3 ...
	 *
	 *		B1 = MD5(S + RA)		C(1) = P1 xor B1
	 *		B2 = MD5(S + C(1))		C(2) = P2 xor B2
	 *		.						.
	 *		.						.
	 *		Bi = MD5(S + C(i - 1))	C(i) = Pi xor Bi
	 *
	 *	result: C(1) + C(2) + ... + C(i)
	 *
	 *	[RFC2058]
	 *******************************************************************/
	unsigned char output[16];
	unsigned char input[1024];
	unsigned char ilen;
	for(i = 0;i < plen;i += 16)
	{
		memset(input, 0, sizeof(input));
		ilen = 0;

		strcpy((char *)input, secret);
		ilen += slen;

		if(i == 0)
			for(j = 0;j < 16;j ++) input[ilen++] = request[4 + j];
		else
			for(j = 0;j < 16;j ++) input[ilen++] = output[j];

		MD5(output, input, ilen);

        int m = 0;
		for(m = 0, j = i;j < (plen - i < 16 ? plen : 16 + i);j ++, m++)
			output[m] ^= pwd[j];

		for(j = 0;j < 16;j ++)
			request[reqlen++] = output[j];
	}

	request[2] = reqlen / 0xFF;
	request[3] = reqlen % 0xFF;

	dwBeginTime = ::GetTickCount();

	// parse radius response
	int dw, n;
	n = sendto(s, (char *)request, reqlen, 0, (struct sockaddr *)&serv, sizeof(serv));
	if(n == SOCKET_ERROR) 
	{
		// Send Data Error
		sprintf(szReturn, "error=%s", ::FuncGetStringFromIDS("<%IDS_Radius_3%>"));//<%IDS_Radius_3%>
		return FALSE;
	}
	
w:	if(RESPONSE_WAIT(s, timeout) > 0)
	{
		dw = sizeof(serv);
		n = recvfrom(s, (char *)response, 1000, 0, (struct sockaddr *)&serv, &dw);
		if(n == SOCKET_ERROR) 
		{
			// Receive Data Error
			sprintf(szReturn, "error=%s", ::FuncGetStringFromIDS("<%IDS_Radius_4%>"));//<%IDS_Radius_4%>
			return FALSE;
		}

		if(n == 0)
		{
			// No Data Responsed From Server
			sprintf(szReturn, "error=%s", ::FuncGetStringFromIDS("<%IDS_Radius_5%>"));//<%IDS_Radius_5%>
			return FALSE;
		}

		if(response[1] != request[1]) goto w;

		if(response[0] == 0x02)
		{
			dwEndTime = ::GetTickCount();
			sprintf(szReturn, "roundTripTime=%ld$", dwEndTime - dwBeginTime);
			return TRUE;
		}
		else if(response[0] == 0x03)
		{
			if(response[20] == 0x12)
				// Request Refused
				sprintf(szReturn, "error=%s: %s$", ::FuncGetStringFromIDS("<%IDS_Radius_6%>"), response + 22);//<%IDS_Radius_6%>
			else
				// Request Refused
				sprintf(szReturn, "error=%s", ::FuncGetStringFromIDS("<%IDS_Radius_7%>"));//<%IDS_Radius_7%>

			return FALSE;
		}
		else
		{
			// Unknown Error
			sprintf(szReturn, "error=%s", ::FuncGetStringFromIDS("<%IDS_Radius_8%>"));//<%IDS_Radius_8%>
			return FALSE;
		}
	}
	else
	{
		// Request Timeout
		sprintf(szReturn, "error=%s", ::FuncGetStringFromIDS("<%IDS_Radius_9%>"));//<%IDS_Radius_9%>
		return FALSE;
	}

	return TRUE;
}
Example #16
0
void ProcessInit() {
  // Initialize compiler state
  VM::compile_file(0, 0, MD5(), 0);

  extern void initialize_repo();
  initialize_repo();

  // Install VM's ClassInfoHook
  ClassInfo::SetHook(&vm_class_info_hook);

  // ensure that nextTx64 and tx64 are set
  (void)VM::Transl::Translator::Get();

  Transl::TargetCache::requestInit();

  Unit* nativeFuncUnit = build_native_func_unit(hhbc_ext_funcs,
                                                hhbc_ext_funcs_count);
  SystemLib::s_nativeFuncUnit = nativeFuncUnit;

  // Search for systemlib.php in the following places:
  // 1) ${HHVM_LIB_PATH}/systemlib.php
  // 2) <dirname(realpath(hhvm))>/systemlib.php (requires proc filesystem)
  // 3) ${HPHP_LIB}/systemlib.php
  // 4) <HHVM_LIB_PATH_DEFAULT>/systemlib.php
  //
  // HHVM_LIB_PATH allows a manual override at runtime. If systemlib.php
  // exists next to the hhvm binary, that is likely to be the next best
  // version to use. The realpath()-based lookup will succeed as long as the
  // proc filesystem exists (e.g. on Linux and some FreeBSD configurations)
  // and no hard links are in use for the executable. Under certain build
  // situations, systemlib.php will not be generated next to hhvm binary, so
  // ${HPHP_LIB} is checked next. Failing all of those options, the
  // HHVM_LIB_PATH_DEFAULT-based lookup will always succeed, assuming that the
  // application was built and installed correctly.
  String currentDir = g_vmContext->getCwd();
  HPHP::Eval::PhpFile* file = NULL;

#define SYSTEMLIB_PHP "/systemlib.php"
#define LOOKUP_STR(s) do {                                                    \
  String systemlibPath = String(s) + SYSTEMLIB_PHP;                           \
  file = g_vmContext->lookupPhpFile(systemlibPath.get(), currentDir.data(),   \
                                    NULL);                                    \
} while (0)
#define LOOKUP_ENV(v) do {                                                    \
  if (!file) {                                                                \
    const char* s = getenv(#v);                                               \
    if (s && *s) {                                                            \
      LOOKUP_STR(s);                                                          \
    }                                                                         \
  }                                                                           \
} while (0)
#define LOOKUP_CPP(v) do {                                                    \
  if (!file) {                                                                \
    LOOKUP_STR(v);                                                            \
  }                                                                           \
} while (0)

  LOOKUP_ENV(HHVM_LIB_PATH);
  if (!file) {
    char hhvm_exe[PATH_MAX+1];
    char hhvm_path[PATH_MAX+1];
    ssize_t len = readlink("/proc/self/exe", hhvm_exe, sizeof(hhvm_exe));
    if (len >= 0) {
      hhvm_exe[len] = '\0';
      if (realpath(hhvm_exe, hhvm_path) != NULL) {
        char *hphp_lib = dirname(hhvm_path);
        LOOKUP_STR(hphp_lib);
      }
    }
  }
  LOOKUP_ENV(HPHP_LIB);
#ifdef HHVM_LIB_PATH_DEFAULT
  LOOKUP_CPP(HHVM_LIB_PATH_DEFAULT);
#endif
  if (!file) {
    // Die a horrible death.
    Logger::Error("Unable to find/load systemlib.php");
    _exit(1);
  }
#undef SYSTEMLIB_PHP
#undef LOOKUP_STR
#undef LOOKUP_ENV
#undef LOOKUP_CPP
  SystemLib::s_phpFile = file;
  file->incRef();
  SystemLib::s_unit = file->unit();

  // Load the systemlib unit to build the Class objects
  SystemLib::s_unit->merge();

  // load builtins
  SystemLib::s_nativeFuncUnit->merge();

#define INIT_SYSTEMLIB_CLASS_FIELD(cls)                                 \
  {                                                                     \
    Class *cls = *Unit::GetNamedEntity(s_##cls.get())->clsList();       \
    ASSERT(cls);                                                        \
    SystemLib::s_##cls##Class = cls;                                    \
  }

  // Stash a pointer to the VM Classes for stdclass, Exception,
  // pinitSentinel and resource
  INIT_SYSTEMLIB_CLASS_FIELD(stdclass);
  INIT_SYSTEMLIB_CLASS_FIELD(Exception);
  INIT_SYSTEMLIB_CLASS_FIELD(BadMethodCallException);
  INIT_SYSTEMLIB_CLASS_FIELD(Directory);
  INIT_SYSTEMLIB_CLASS_FIELD(RecursiveDirectoryIterator);
  INIT_SYSTEMLIB_CLASS_FIELD(SplFileInfo);
  INIT_SYSTEMLIB_CLASS_FIELD(SplFileObject);
  INIT_SYSTEMLIB_CLASS_FIELD(pinitSentinel);
  INIT_SYSTEMLIB_CLASS_FIELD(resource);
  INIT_SYSTEMLIB_CLASS_FIELD(DOMException);
  INIT_SYSTEMLIB_CLASS_FIELD(PDOException);
  INIT_SYSTEMLIB_CLASS_FIELD(SoapFault);

#undef INIT_SYSTEMLIB_CLASS_FIELD

  // We call a special bytecode emitter function to build the native
  // unit which will contain all of our cppext functions and classes.
  // Each function and method will have a bytecode body that will thunk
  // to the native implementation.
  Unit* nativeClassUnit = build_native_class_unit(hhbc_ext_classes,
                                                  hhbc_ext_class_count);
  SystemLib::s_nativeClassUnit = nativeClassUnit;

  // Load the nativelib unit to build the Class objects
  SystemLib::s_nativeClassUnit->merge();

  // Retrieve all of the class pointers
  for (long long i = 0LL; i < hhbc_ext_class_count; ++i) {
    const HhbcExtClassInfo* info = hhbc_ext_classes + i;
    const StringData* name = StringData::GetStaticString(info->m_name);
    const NamedEntity* ne = Unit::GetNamedEntity(name);
    Class* cls = Unit::lookupClass(ne);
    ASSERT(cls);
    const ObjectStaticCallbacks* osc =
      get_object_static_callbacks(info->m_name);
    ASSERT(osc != NULL);
    *(osc->os_cls_ptr) = cls;
  }

  Stack::ValidateStackSize();
  SystemLib::s_inited = true;

  // For debug build, run some quick unit tests at process start time
  if (debug) {
    VM::Transl::FixupMapUnitTest _;
  }
}
Example #17
0
//
// Send local file status: not exist or very small / md5 data of every chunck of file
//
// @return file_size
//
int SendLocalFileStatus(int socket)
{
	u_int32_t file_size;

	file_size = get_file_size(file_name);
	printf("File size = %u\n", file_size);

	if( file_size <= MAX_LINE)
	{
		// No such file, or file size is smaller than one chunck, then send "local file not exist!"
		if(FALSE == send(socket, no_file , strlen(no_file) + 1, 0))
		{
		    ErrorReport(CLIENT_SEND_DATA_ERR);
			return FALSE;
		}
	}
	else
	{		
		int i;
		int fd;
		char data_buf[MAX_LINE];
		int read_length = 0;
		int send_length = 0;

		int md5_num = file_size / MAX_LINE + 1;
		int md5_data_length = md5_num * 16;
		unsigned char *md5_data_buf = malloc(md5_data_length);
		bzero(md5_data_buf, md5_data_length);

		printf("md5_num = %d\n", md5_num);
		printf("md5_data_length = %d\n", md5_data_length);
		
		// Send the md5 number
		printf("Send md5_num to server.....\n");
		sprintf(data_buf, "%d", md5_num);
		send_length = send(socket, data_buf, 1, 0);
        if (FALSE == send_length)
        {
            ErrorReport(CLIENT_SEND_DATA_ERR);
            return FALSE;
        }
        bzero(data_buf, MAX_LINE);

        // Recv server's response
        read_length = recv(socket, data_buf, MAX_LINE, 0);
        if(FALSE == read_length)
        {
        	ErrorReport(RECEIVE_DATA_ERR);
        	return FALSE;
        }
        if(strcmp(data_buf, response_ok) != 0)
        {
        	ErrorReport(SERVER_RESPONSE_ERR);
        	return FALSE;
        }

        printf("Receive server response for md5 number --- Success\n");

		// Open the file
		fd = open(file_name, O_RDONLY);
		if(fd < 0)
		{
			ErrorReport(FILE_OPEN_ERR);
			return FALSE;
		}

		printf("Calculate MD5 data....");
		// Caculate MD5 data for each chunck 
	    for(i = 0; i <= file_size / MAX_LINE && read_length; i++)
	    {
	    	bzero(data_buf, MAX_LINE);
	        read_length = read(fd, data_buf, MAX_LINE);
	        if(FALSE == read_length)
	        {
	            ErrorReport(FILE_READ_ERR);
	            return FALSE;
	        }
	        MD5((unsigned char*)data_buf, read_length, md5_data_buf + i);
	    }

	    printf("Send MD5 data....");
	    // Send MD5 data to server
	    for(i = 0; i < md5_data_length; i += send_length)
        {
        	printf("Send MD5 data... Time %d\n", i);
	        send_length = send(socket, md5_data_buf + i, md5_data_length - i, 0);
	        if (FALSE == send_length)
	        {
	            ErrorReport(FILE_WRITE_ERR);
	            return FALSE;
	        }
        }  

	    close(fd);
	    free(md5_data_buf);
	}
	return file_size;
}
Example #18
0
//-------------------------------------------------------------------------------------
bool KBEEmailVerificationTableMysql::resetpassword(DBInterface * dbi, const std::string& name, 
												   const std::string& password, const std::string& code)
{
	std::string sqlstr = "select accountName, logtime from kbe_email_verification where code like \"";

	char* tbuf = new char[code.size() * 2 + 1];

	mysql_real_escape_string(static_cast<DBInterfaceMysql*>(dbi)->mysql(), 
		tbuf, code.c_str(), code.size());

	sqlstr += tbuf;

	sqlstr += "\" and type=";
	kbe_snprintf(tbuf, MAX_BUF, "%d", (int)KBEEmailVerificationTable::V_TYPE_RESETPASSWORD);
	sqlstr += tbuf;

	SAFE_RELEASE_ARRAY(tbuf);

	if(!dbi->query(sqlstr.c_str(), sqlstr.size(), false))
		return false;

	uint64 logtime = 1;
	
	std::string qname;

	MYSQL_RES * pResult = mysql_store_result(static_cast<DBInterfaceMysql*>(dbi)->mysql());
	if(pResult)
	{
		MYSQL_ROW arow;
		while((arow = mysql_fetch_row(pResult)) != NULL)
		{
			qname = arow[0];
			KBEngine::StringConv::str2value(logtime, arow[1]);
		}

		mysql_free_result(pResult);
	}

	if(logtime > 0 && time(NULL) - logtime > g_kbeSrvConfig.emailResetPasswordInfo_.deadline)
		return false;

	if(qname.size() == 0 || password.size() == 0)
	{
		return false;
	}

	if(qname != name)
	{
		WARNING_MSG(boost::format("KBEEmailVerificationTableMysql::resetpassword: code(%1%) username(%2%, %3%) not match.\n") 
			% code % name % qname);

		return false;
	}

	// 寻找dblog是否有此账号
	KBEAccountTable* pTable = static_cast<KBEAccountTable*>(EntityTables::getSingleton().findKBETable("kbe_accountinfos"));
	KBE_ASSERT(pTable);
	
	unsigned char md[16];
	MD5((unsigned char *)password.c_str(), password.length(), md);

	char tmp[3]={'\0'}, md5password[33] = {'\0'};
	for (int i = 0; i < 16; i++)
	{
		sprintf(tmp,"%2.2X", md[i]);
		strcat(md5password, tmp);
	}

	if(!pTable->updatePassword(dbi, name, md5password))
		return false;


	try
	{
		delAccount(dbi, (int8)V_TYPE_RESETPASSWORD, name);
	}
	catch (...)
	{
	}

	return true;
}
Example #19
0
File: crypt.c Project: vap0r/wraith
int md5cmp(const char *hash, const char *string) {
  int n = strcmp(hash, MD5(string));
  MD5(NULL);
  return n;
}
Example #20
0
void YellHttp_GenDigestAuthHdr(YellHttp_Ctx *ctx)
{
	int retval, i, invalidcreds = 0;
	char auth[512];
	char authout[512];
	char tempval[512];
	unsigned char HA1[16];
	unsigned char HA2[16];
	unsigned char HA3[16];
	char response[33];
	char HA1_text[33];
	char HA2_text[33];
	char request_data[512];
	char qop[32];
	char nc[17];
	char username[512];

	memset(auth, 0, 512);
	memset(authout, 0, 512);
	memset(tempval, 0, 512);
	memset(ctx->authorization_header, 0, 512);
	if(authcb)
	{
		if(ctx->auth_requirederrors > 1)invalidcreds = 1;
		retval = authcb(ctx, ctx->realm, auth, authcb_usrarg, 1, invalidcreds);
		if(retval==YELLHTTP_ENOCREDS)
		{
			printf("Invalid user/pass, no more users/passwords are available from the authentication callback.\n");
			ctx->authenticated = 2;
			return;
		}

		MD5(HA1, (unsigned char*)auth, strlen(auth));
		memset(request_data, 0, 512);
		if(strlen(ctx->request_type)>0)
		{
			strncpy(request_data, ctx->request_type, 8);
		}
		else
		{
			strncpy(request_data, "GET", 8);
		}
		strncat(request_data, ":", 512);
		strncat(request_data, ctx->uri, 511);
		MD5(HA2, (unsigned char*)request_data, strlen(request_data));
		memset(qop, 0, 32);
		strncpy(qop, "auth", 32);
		memset(nc, 0, 16);
		ctx->auth_nc = 1;
		snprintf(nc, 16, "%04x%04x", ((unsigned int)(ctx->auth_nc >> 32)), (unsigned int)ctx->auth_nc);
		memset(ctx->auth_cnonce, 0, 9);
		snprintf(ctx->auth_cnonce, 17, "%04x%04x", rand(), rand());
		memset(HA1_text, 0, 33);
		memset(HA2_text, 0, 33);
		for(i=0; i<16; i++)sprintf((char*)&HA1_text[i*2], "%02x", HA1[i]);
		for(i=0; i<16; i++)sprintf((char*)&HA2_text[i*2], "%02x", HA2[i]);
		snprintf(tempval, 512, "%s:%s:%s:%s:%s:%s", HA1_text, ctx->auth_nonce, nc, ctx->auth_cnonce, qop, HA2_text);
		MD5(HA3, (unsigned char*)tempval, strlen(tempval));
		memset(response, 0, 33);
		for(i=0; i<16; i++)sprintf((char*)&response[i*2], "%02x", HA3[i]);
		memset(username, 0, 512);
		for(i=0; i<strlen(auth) && auth[i]!=':'; i++)username[i] = auth[i];

		snprintf(ctx->authorization_header, 511, "Authorization: Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", algorithm=MD5, response=\"%s\", qop=%s, nc=%s, cnonce=\"%s\"\r\n", username, ctx->realm, ctx->auth_nonce, ctx->uri, response, qop, nc, ctx->auth_cnonce);
		ctx->authenticated = 1;
	}
	else
	{
Example #21
0
static int
handshake_00(struct libwebsocket_context *context, struct libwebsocket *wsi)
{
	unsigned long key1, key2;
	unsigned char sum[16];
	char *response;
	char *p;
	int n;

	/* Confirm we have all the necessary pieces */

	if (!wsi->utf8_token[WSI_TOKEN_ORIGIN].token_len ||
		!wsi->utf8_token[WSI_TOKEN_HOST].token_len ||
		!wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len ||
		!wsi->utf8_token[WSI_TOKEN_KEY1].token_len ||
			     !wsi->utf8_token[WSI_TOKEN_KEY2].token_len)
		/* completed header processing, but missing some bits */
		goto bail;

	/* allocate the per-connection user memory (if any) */

	if (wsi->protocol->per_session_data_size) {
		wsi->user_space = malloc(
				  wsi->protocol->per_session_data_size);
		if (wsi->user_space  == NULL) {
			LOG("Out of memory for "
						   "conn user space\n");
			goto bail;
		}
	} else
		wsi->user_space = NULL;

	/* create the response packet */

	/* make a buffer big enough for everything */

	response = malloc(256 +
		wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len +
		wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len +
		wsi->utf8_token[WSI_TOKEN_HOST].token_len +
		wsi->utf8_token[WSI_TOKEN_ORIGIN].token_len +
		wsi->utf8_token[WSI_TOKEN_GET_URI].token_len +
		wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
	if (!response) {
		LOG("Out of memory for response buffer\n");
		goto bail;
	}

	p = response;
	strcpy(p,   "HTTP/1.1 101 WebSocket Protocol Handshake\x0d\x0a"
					  "Upgrade: WebSocket\x0d\x0a");
	p += strlen("HTTP/1.1 101 WebSocket Protocol Handshake\x0d\x0a"
					  "Upgrade: WebSocket\x0d\x0a");
	strcpy(p,   "Connection: Upgrade\x0d\x0a"
		    "Sec-WebSocket-Origin: ");
	p += strlen("Connection: Upgrade\x0d\x0a"
		    "Sec-WebSocket-Origin: ");
	strcpy(p, wsi->utf8_token[WSI_TOKEN_ORIGIN].token);
	p += wsi->utf8_token[WSI_TOKEN_ORIGIN].token_len;
#ifdef LWS_OPENSSL_SUPPORT
	if (wsi->ssl) {
		strcpy(p,   "\x0d\x0aSec-WebSocket-Location: wss://");
		p += strlen("\x0d\x0aSec-WebSocket-Location: wss://");
	} else {
#endif
		strcpy(p,   "\x0d\x0aSec-WebSocket-Location: ws://");
		p += strlen("\x0d\x0aSec-WebSocket-Location: ws://");
#ifdef LWS_OPENSSL_SUPPORT
	}
#endif
	strcpy(p, wsi->utf8_token[WSI_TOKEN_HOST].token);
	p += wsi->utf8_token[WSI_TOKEN_HOST].token_len;
	strcpy(p, wsi->utf8_token[WSI_TOKEN_GET_URI].token);
	p += wsi->utf8_token[WSI_TOKEN_GET_URI].token_len;

	if (wsi->utf8_token[WSI_TOKEN_PROTOCOL].token) {
		strcpy(p,   "\x0d\x0aSec-WebSocket-Protocol: ");
		p += strlen("\x0d\x0aSec-WebSocket-Protocol: ");
		strcpy(p, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
		p += wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len;
	}

	strcpy(p,   "\x0d\x0a\x0d\x0a");
	p += strlen("\x0d\x0a\x0d\x0a");

	/* convert the two keys into 32-bit integers */

	if (interpret_key(wsi->utf8_token[WSI_TOKEN_KEY1].token, &key1))
		goto bail;
	if (interpret_key(wsi->utf8_token[WSI_TOKEN_KEY2].token, &key2))
		goto bail;

	/* lay them out in network byte order (MSB first */

	sum[0] = key1 >> 24;
	sum[1] = key1 >> 16;
	sum[2] = key1 >> 8;
	sum[3] = key1;
	sum[4] = key2 >> 24;
	sum[5] = key2 >> 16;
	sum[6] = key2 >> 8;
	sum[7] = key2;

	/* follow them with the challenge token we were sent */

	memcpy(&sum[8], wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 8);

	/*
	 * compute the md5sum of that 16-byte series and use as our
	 * payload after our headers
	 */

	MD5(sum, 16, (unsigned char *)p);
	p += 16;

	/* it's complete: go ahead and send it */

	debug("issuing response packet %d len\n", (int)(p - response));
#ifdef DEBUG
	fwrite(response, 1,  p - response, stderr);
#endif
	n = libwebsocket_write(wsi, (unsigned char *)response,
					  p - response, LWS_WRITE_HTTP);
	if (n < 0) {
		LOG("ERROR writing to socket");
		goto bail;
	}

	/* alright clean up and set ourselves into established state */

	free(response);
	wsi->state = WSI_STATE_ESTABLISHED;
	wsi->lws_rx_parse_state = LWS_RXPS_NEW;

	/* notify user code that we're ready to roll */

	if (wsi->protocol->callback)
		wsi->protocol->callback(wsi->protocol->owning_server,
				wsi, LWS_CALLBACK_ESTABLISHED,
					  wsi->user_space, NULL, 0);

	return 0;

bail:
	return -1;
}
Example #22
0
static int nr_ice_crypto_openssl_md5(UCHAR *buf, int bufl, UCHAR *result) {
  MD5(buf, bufl, result);
  return 0;
}
Example #23
0
/* Checks if authentication is correct. Returns -1 if not correct, 1 if correct and 2 if nonce isn't valid anymore.
   Note that authstring will be modified. */
int32_t check_auth(char *authstring, char *method, char *path, IN_ADDR_T addr, char *expectednonce, char *opaque)
{
	int32_t authok = 0, uriok = 0;
	char authnonce[(MD5_DIGEST_LENGTH * 2) + 1];
	memset(authnonce, 0, sizeof(authnonce));
	char *authnc = "";
	char *authcnonce = "";
	char *authresponse = "";
	char *uri = "";
	char *username = "";
	char *expectedPassword = cfg.http_pwd;
	char *pch = authstring + 22;
	char *pch2;
	char *saveptr1 = NULL;
	memset(opaque, 0, (MD5_DIGEST_LENGTH * 2) + 1);

	for(pch = strtok_r(pch, ",", &saveptr1); pch; pch = strtok_r(NULL, ",", &saveptr1))
	{
		pch2 = pch;
		while(pch2[0] == ' ' && pch2[0] != '\0') { ++pch2; }
		if(strncmp(pch2, "nonce", 5) == 0)
		{
			cs_strncpy(authnonce, parse_auth_value(pch2), sizeof(authnonce));
		}
		else if(strncmp(pch2, "nc", 2) == 0)
		{
			authnc = parse_auth_value(pch2);
		}
		else if(strncmp(pch2, "cnonce", 6) == 0)
		{
			authcnonce = parse_auth_value(pch2);
		}
		else if(strncmp(pch2, "response", 8) == 0)
		{
			authresponse = parse_auth_value(pch2);
		}
		else if(strncmp(pch2, "uri", 3) == 0)
		{
			uri = parse_auth_value(pch2);
		}
		else if(strncmp(pch2, "username", 8) == 0)
		{
			username = parse_auth_value(pch2);
		}
		else if(strncmp(pch2, "opaque", 6) == 0)
		{
			char *tmp = parse_auth_value(pch2);
			cs_strncpy(opaque, tmp, (MD5_DIGEST_LENGTH * 2) + 1);
		}
	}

	if(strncmp(uri, path, strlen(path)) == 0) { uriok = 1; }
	else
	{
		pch2 = uri;
		for(pch = uri; pch[0] != '\0'; ++pch)
		{
			if(pch[0] == '/') { pch2 = pch; }
			if(strncmp(pch2, path, strlen(path)) == 0) { uriok = 1; }
		}
	}
	if(uriok == 1 && streq(username, cfg.http_user))
	{
		char A1tmp[3 + strlen(username) + strlen(AUTHREALM) + strlen(expectedPassword)];
		char A1[(MD5_DIGEST_LENGTH * 2) + 1], A2[(MD5_DIGEST_LENGTH * 2) + 1], A3[(MD5_DIGEST_LENGTH * 2) + 1];
		unsigned char md5tmp[MD5_DIGEST_LENGTH];
		snprintf(A1tmp, sizeof(A1tmp), "%s:%s:%s", username, AUTHREALM, expectedPassword);
		char_to_hex(MD5((unsigned char *)A1tmp, strlen(A1tmp), md5tmp), MD5_DIGEST_LENGTH, (unsigned char *)A1);

		char A2tmp[2 + strlen(method) + strlen(uri)];
		snprintf(A2tmp, sizeof(A2tmp), "%s:%s", method, uri);
		char_to_hex(MD5((unsigned char *)A2tmp, strlen(A2tmp), md5tmp), MD5_DIGEST_LENGTH, (unsigned char *)A2);

		char A3tmp[10 + strlen(A1) + strlen(A2) + strlen(authnonce) + strlen(authnc) + strlen(authcnonce)];
		snprintf(A3tmp, sizeof(A3tmp), "%s:%s:%s:%s:auth:%s", A1, authnonce, authnc, authcnonce, A2);
		char_to_hex(MD5((unsigned char *)A3tmp, strlen(A3tmp), md5tmp), MD5_DIGEST_LENGTH, (unsigned char *)A3);

		if(strcmp(A3, authresponse) == 0)
		{
			if(strlen(opaque) != MD5_DIGEST_LENGTH * 2) { calculate_opaque(addr, opaque); }
			calculate_nonce(authnonce, expectednonce, opaque);
			if(strcmp(expectednonce, authnonce) == 0) { authok = 1; }
			else
			{
				authok = 2;
				cs_debug_mask(D_TRACE, "WebIf: Received stale header from %s (nonce=%s, expectednonce=%s, opaque=%s).", cs_inet_ntoa(addr), authnonce, expectednonce, opaque);
			}
		}
	}
	return authok;
}
Example #24
0
int CPCIDCalculator::CalculatePCID( char buf[16], char flag )
{

//test

	/*int nresult;
	LANA_ENUM   lenum;
	NCB m_ncb;
	ZeroMemory(&m_ncb, sizeof(m_ncb));
	m_ncb.ncb_command = NCBENUM;
	m_ncb.ncb_buffer = (UCHAR*)&lenum;
	m_ncb.ncb_length = sizeof(m_ncb);
	nresult = Netbios(&m_ncb);
	for(int i = 0; i < lenum.length; i++)
	{
		ZeroMemory(&m_ncb, sizeof(m_ncb));
		m_ncb.ncb_command = NCBRESET;
		m_ncb.ncb_lana_num = lenum.lana[i];
		nresult = Netbios(&m_ncb);
		ZeroMemory(&m_ncb, sizeof(m_ncb));
		m_ncb.ncb_command = NCBASTAT;
		m_ncb.ncb_lana_num = lenum.lana[i];
		strcpy((char *)m_ncb.ncb_callname, "* ");
		m_ncb.ncb_buffer = (UCHAR*)&Adapter;
		m_ncb.ncb_length = sizeof(Adapter);
		nresult = Netbios(&m_ncb);
		if(nresult == NRC_GOODRET)
		{
			char MacAddres[MAX_PATH] = {0};
			sprintf(MacAddres, "%d is:%02x-%02x-%02x-%02x-%02x-%02x", lenum.lana[i], Adapter.adapt.adapter_address[0], Adapter.adapt.adapter_address[1],
				Adapter.adapt.adapter_address[2], Adapter.adapt.adapter_address[3], Adapter.adapt.adapter_address[4], Adapter.adapt.adapter_address[5]);
			MessageBoxA(NULL, MacAddres, "", 0);
		}
	}*/

    MyMacAddress myAdress;
    if( myAdress.WMI_GetMacAddress(1, 1) > 0)
	{
		char MacAddres[MAX_PATH] = {0};
		//myAdress.GetMacReallyValue(MyMacAddress::MACAddress, MacAddres);
		//MessageBoxA(NULL, MacAddres, "", 0);
		myAdress.GetMacReallyValue(MyMacAddress::PermanentAddress, MacAddres);
		//MessageBoxA(NULL, MacAddres, "", 0);
	}
//test


	char tembuf[1024];
	int  total = 1024;
	int  used  = 0;

	ZeroMemory(tembuf, sizeof(tembuf));
	if( flag&PCID_DISK )
	{
		CPCIdentificationCode ide;
		used += ide.GetIdentificationCode( &tembuf[used], total-used );
	}
	if( flag&PCID_MAC )
	{
		MyMacAddress myAdress;
        if( myAdress.WMI_GetMacAddress(1, 1) > 0)
		{
            memcpy(&tembuf[used], MyMacAddress::PermanentAddress, MACADDRESS_BYTELEN);
            used += MACADDRESS_BYTELEN;
		}
		//CPCIdentificationCode ide;
		//used += ide.GetMac( &tembuf[used], total-used );
	}
	if( flag&PCID_CPU )
	{
		int arr[4];
		ZeroMemory( arr, sizeof(arr) );
		__cpuid( arr, 0 );
		memcpy_s( &tembuf[used], total-used, arr, sizeof(arr));
		used += sizeof(arr);

		ZeroMemory( arr, sizeof( arr ) );
		__cpuid( arr, 1 );
		//  防止数组第二位开头出错,出现 不同结果
		memcpy_s( &tembuf[used], total-used, arr, 4);
		memcpy_s( &tembuf[used + 4], total-used, arr + 2, sizeof(arr) - 8);
		//memcpy_s( &tembuf[used], total-used, arr, sizeof(arr));
		used += (sizeof(arr) - 4);

		ZeroMemory( arr, sizeof( arr ));
		__cpuid( arr, 3 );
		memcpy_s( &tembuf[used], total-used, arr, sizeof(arr) );
		used += sizeof(arr);

		ZeroMemory( arr, sizeof(arr) );
		__cpuid( arr, 4 );
		memcpy_s( &tembuf[used], total-used, arr, sizeof(arr) );
		used += sizeof(arr);
	}
	if( flag&PCID_BIOS )
	{
		CBiosInfo bios;
		if( bios.InitBiosInfo() )
		{
			string str = bios.GetSystemECAssetTagNmuber();
			str += bios.GetSystemECManufacturer();
			str += bios.GetSystemECSerialNumber();
			str += bios.GetSystemECType();
			str += bios.GetSystemECVersion();
			str += bios.GetSystemFamily();
			str += bios.GetSystemManufacturer();
			str += bios.GetSystemProductName();
			str += bios.GetSystemSerialNumber();
			str += bios.GetSystemSKUNumber();
			str += bios.GetSystemVersion();
			memcpy_s( &tembuf[used], total-used, str.c_str(), str.length() );
			used += str.length();
		}
	}
	unsigned long md5value[4] = {0};
	MD5(tembuf, used, md5value);
	//MD5 md5( tembuf, used );
	//md5.digest()
	memcpy_s( buf, 16, md5value, 16 );
	return true;

			//test

		//	char Title[128] = "ECAssetTagNmuber: ";
		//	FILE* fl = fopen("./test.txt", "w");
		//	if(fl)
		//	{
  //             strcat(Title, bios.GetSystemECAssetTagNmuber().c_str());
		//	   fwrite(Title, sizeof(char), 128, fl);
		//	   fwrite("\r\n", sizeof(char), 2, fl);
		//	   ZeroMemory(Title, 128);

		//	   strcat(Title, "ECManufacturer: ");
		//	   strcat(Title, bios.GetSystemECManufacturer().c_str());
		//	   fwrite(Title, sizeof(char), 128, fl);
		//	   fwrite("\r\n", sizeof(char), 2, fl);
		//	   ZeroMemory(Title, 128);

		//	   strcat(Title, "ECSerialNumber: ");
		//	   strcat(Title, bios.GetSystemECSerialNumber().c_str());
		//	   fwrite(Title, sizeof(char), 128, fl);
		//	   fwrite("\r\n", sizeof(char), 2, fl);
		//	   ZeroMemory(Title, 128);

		//	   strcat(Title, "ECType: ");
		//	   strcat(Title, bios.GetSystemECType().c_str());
		//	   fwrite(Title, sizeof(char), 128, fl);
		//	   fwrite("\r\n", sizeof(char), 2, fl);
		//	   ZeroMemory(Title, 128);

		//	   strcat(Title, "ECVersion: ");
		//	   strcat(Title, bios.GetSystemECVersion().c_str());
		//	   fwrite(Title, sizeof(char), 128, fl);
		//	   fwrite("\r\n", sizeof(char), 2, fl);
		//	   ZeroMemory(Title, 128);

		//	   strcat(Title, "SystemFamily: ");
		//	   strcat(Title, bios.GetSystemFamily().c_str());
		//	   fwrite(Title, sizeof(char), 128, fl);
		//	   fwrite("\r\n", sizeof(char), 2, fl);
		//	   ZeroMemory(Title, 128);

		//	   strcat(Title, "Manufacturer: ");
		//	   strcat(Title, bios.GetSystemManufacturer().c_str());
		//	   fwrite(Title, sizeof(char), 128, fl);
		//	   fwrite("\r\n", sizeof(char), 2, fl);
		//	   ZeroMemory(Title, 128);

		//	   strcat(Title, "ProductName: ");
		//	   strcat(Title, bios.GetSystemProductName().c_str());
		//	   fwrite(Title, sizeof(char), 128, fl);
		//	   fwrite("\r\n", sizeof(char), 2, fl);
		//	   ZeroMemory(Title, 128);

		//	   strcat(Title, "SerialNumber: ");
		//	   strcat(Title, bios.GetSystemSerialNumber().c_str());
		//	   fwrite(Title, sizeof(char), 128, fl);
		//	   fwrite("\r\n", sizeof(char), 2, fl);
		//	   ZeroMemory(Title, 128);

		//	   strcat(Title, "SKUNumber: ");
		//	   strcat(Title, bios.GetSystemSKUNumber().c_str());
		//	   fwrite(Title, sizeof(char), 128, fl);
		//	   fwrite("\r\n", sizeof(char), 2, fl);
		//	   ZeroMemory(Title, 128);

		//	   strcat(Title, "Version: ");
		//	   strcat(Title, bios.GetSystemVersion().c_str());
		//	   fwrite(Title, sizeof(char), 128, fl);
		//	   fwrite("\r\n", sizeof(char), 2, fl);
		//	   ZeroMemory(Title, 128);

		//	   strcat(Title, "ESKUNumber: ");
		//	   strcat(Title, bios.GetSystemSKUNumber().c_str());
		//	   fwrite(Title, sizeof(char), 128, fl);
		//	   fwrite("\r\n", sizeof(char), 2, fl);
		//	   ZeroMemory(Title, 128);


		//	   //strcat(Title, "PCMac");
		//	   char Buf[128];
		//	   int nReslut = GetPCMac( Buf, 128 );
		//	   sprintf_s(Title, 16, "%d PCMac: ", nReslut);
		//	   memcpy(&Title[16], Buf, 112);
  //             //strcat(Title, Buf);
		//	   fwrite(Title, sizeof(char), 128, fl);
  //             fwrite("\r\n", sizeof(char), 2, fl);
		//	   fclose(fl);

		//	}
		//	ShellExecuteA(NULL, "open", "./test.txt", NULL, NULL, SW_SHOW);
		//}
}
Example #25
0
int generateSign(char* inputFile, char* privKeyFile, char* signedFile)
{
		unsigned char* buf = (unsigned char*)malloc(MSG_BUF_LEN*sizeof(unsigned char));
		int* encoded_buf = (int*)malloc(MSG_BUF_LEN * sizeof(int));
		int size_encrypted, len_d_2 = 0;
		unsigned char md5hash[MD5_DIGEST_LENGTH];
		int i, index = MSG_BUF_LEN -1, numOctetsAdded=0, totalLength = 0, octet_string_len = 0, num_octets;
		int n = readFileInBuffer(inputFile, buf);
		num_octets = N_NUM_BITS/8;
		MD5(buf, n, md5hash);
		int protoLen = strlen(Md5OidValue)/2;
		#ifdef DEBUG3
			printf("MD5 HASH\n");
			for (i = 0; i < MD5_DIGEST_LENGTH; i++) 
			{
				printf("%02x ", md5hash[i]);
			}
			printf("\n");
		#endif
		
		//embed the md5 buffer
		embed_md5_buffer(encoded_buf, md5hash, &index, MD5_DIGEST_LENGTH);
		totalLength+= MD5_DIGEST_LENGTH;
		
		//append the length octet
		numOctetsAdded = appendLengthToBuffer( MD5_DIGEST_LENGTH , encoded_buf, &index);
		totalLength+=numOctetsAdded;
		//append the identifier octet
		appendIdentifierOctet(TAG_OCTET_STRING, PRIMITIVE, 0, encoded_buf, &index);
		totalLength++;
		
		//Add length octet - 0
		numOctetsAdded = appendLengthToBuffer( 0 , encoded_buf, &index);
		totalLength+=numOctetsAdded;
		len_d_2 += numOctetsAdded;
		
		//Add identifier octet
		appendIdentifierOctet(TAG_NULL, PRIMITIVE, UNIVERSAL, encoded_buf, &index);
		totalLength++;
		len_d_2++;
		
		//append the MD5 object identifier value
		addOID(encoded_buf, &index, Md5OidValue);
		totalLength+=protoLen;
		len_d_2+=protoLen;
		
		//add length of the identifier
		numOctetsAdded = appendLengthToBuffer( protoLen , encoded_buf, &index);
		totalLength+=numOctetsAdded;
		len_d_2+=numOctetsAdded;
		
		//add identifier octet
		appendIdentifierOctet(TAG_OID, PRIMITIVE, UNIVERSAL, encoded_buf, &index);
		totalLength++;
		len_d_2++;
		
		//add length octet
		numOctetsAdded = appendLengthToBuffer( len_d_2 , encoded_buf, &index);
		totalLength+=numOctetsAdded;
		
		//add identifier octet
		appendIdentifierOctet(TAG_SEQUENCE, CONSTRUCTED, UNIVERSAL, encoded_buf, &index);
		totalLength++;
		
		//add length octet
		appendLengthToBuffer( totalLength , encoded_buf, &index);
		
		//add identifier octet
		appendIdentifierOctet(TAG_SEQUENCE, CONSTRUCTED, UNIVERSAL, encoded_buf, &index);
		#ifdef DEBUG2
			displayBuffer(encoded_buf, index+1,  MSG_BUF_LEN);
		#endif
		
		octet_string_len = (MSG_BUF_LEN - index - 1)/8;

		unsigned char* octet_string = (unsigned char*)malloc(octet_string_len * sizeof(unsigned char));
		memset(octet_string, 0, octet_string_len);
		
		getOctetString(encoded_buf, octet_string, index+1, MSG_BUF_LEN);
		
		unsigned char* encrypted_buff = (unsigned char*)malloc(num_octets*sizeof(unsigned char));
		memset(encrypted_buff, 0, num_octets);
		
		encrypt_buff(octet_string, encrypted_buff, privKeyFile, PRIVATE_KEY, octet_string_len, &size_encrypted);
		writeEncryptedBuffer(signedFile, encrypted_buff, size_encrypted);
	
		//decrypt(signedFile, "decr", "pub.der", PUBLIC_KEY);
		//writeKeyBuffer(signedFile, encoded_buf, index+1, MSG_BUF_LEN);
}
WiiBanner* WiiSave::readBanner()
{
    Uint8* dec = new Uint8[0xf0c0];
    memset(dec, 0, 0xF0C0);
    Uint8* data = (Uint8*)m_reader->readBytes(0xF0C0);
    Uint8* oldData = m_reader->data();
    Uint64 oldPos = m_reader->position();
    Uint64 oldLen = m_reader->length();
    Uint64 gameId;
    Uint32 bannerSize;
    Uint8  permissions;
    Uint8  md5[16];
    Uint8  md5Calc[16];
    Uint8  tmpIV[26];
    memcpy(tmpIV, sd_iv, 16);

    aes_set_key(sd_key);
    aes_decrypt(tmpIV, data, dec, 0xF0C0);
    memset(md5, 0, 16);
    memset(md5Calc, 0, 16);
    // Read in the MD5 sum
    memcpy(md5, (dec + 0x0E), 0x10);
    // Write the blanker to the buffer
    memcpy((dec + 0x0E), md5_blanker, 0x10);
    MD5(md5Calc, dec, 0xF0C0);

    // Compare the Calculated MD5 to the one from the file.
    // This needs to be done incase the file is corrupted.
    if (memcmp(md5, md5Calc, 0x10))
    {
        std::cerr << "MD5 Mismatch" << std::endl;
        // Make sure to reset m_reader values back to the old ones.
        std::cerr << "MD5 provided:   ";
        for (int i = 0; i < 16; ++i)
            std::cerr << std::hex << (int)(md5[i]);
        std::cerr << std::endl;

        std::cerr << "MD5 Calculated: ";
        for (int i = 0; i < 16; ++i)
            std::cerr << std::hex << (int)(md5Calc[i]);
        std::cerr << std::endl;
        m_reader->setData(oldData, oldLen);
        m_reader->seek(oldPos, Stream::Beginning);
        return NULL;
    }
    // Set the binary reader buffer;
    m_reader->setData(dec, 0xF0C0);
    // Start reading the header
    gameId = m_reader->readUInt64();
    bannerSize = m_reader->readUInt32();
    permissions = m_reader->readByte();
/*    unk =*/ m_reader->readByte();
    m_reader->seek(0x10);
    // skip padding
    m_reader->seek(2);

    int magic;
    int flags;
    short animSpeed;
    std::string gameTitle;
    std::string subTitle;

    magic = m_reader->readUInt32();

    // Ensure that the header magic is valid.
    if (magic != 0x5749424E)
    {
        std::cerr << "Invalid Header Magic: 0x" << std::hex << magic << std::endl;
        // Make sure to reset m_reader values back to the old ones.
        m_reader->setData(oldData, oldLen);
        m_reader->seek(oldPos, Stream::Beginning);
        return NULL;
    }

    flags = m_reader->readUInt32();
    animSpeed = m_reader->readUInt16();
    m_reader->seek(22);

    gameTitle = m_reader->readUnicode();
    if (m_reader->position() != 0x0080)
        m_reader->seek(0x0080, Stream::Beginning);

    subTitle = m_reader->readUnicode();
    if (m_reader->position() != 0x00C0)
        m_reader->seek(0x00C0, Stream::Beginning);

    WiiBanner* banner = new WiiBanner;
    banner->setGameID(gameId);
    banner->setTitle(gameTitle);
    banner->setSubtitle(subTitle);
    banner->setBannerSize(bannerSize);
    WiiImage* bannerImage = readImage(192, 64);
    banner->setBannerImage(bannerImage);
    banner->setAnimationSpeed(animSpeed);
    banner->setPermissions(permissions);
    banner->setFlags(flags);


    if (banner->bannerSize() == 0x72a0)
    {
        WiiImage* icon = readImage(48, 48);
        if (icon)
            banner->addIcon(icon);
        else
            std::cerr << "Warning: Icon empty, skipping" << std::endl;
    }
    else
    {
        for(int i = 0; i < 8; i++)
        {
            WiiImage* icon = readImage(48, 48);
            if (icon)
                banner->addIcon(icon);
            else
                std::cerr << "Warning: Icon empty, skipping" << std::endl;
        }
    }

    m_reader->setData(oldData, oldLen);
    m_reader->seek(oldPos, Stream::Beginning);
    return banner;
}
Example #27
0
void do_emm(struct s_client * client, EMM_PACKET *ep)
{
	char *typtext[]={"unknown", "unique", "shared", "global"};
	char tmp[17];
	int32_t emmnok=0;

	struct s_reader *aureader = NULL;
	cs_ddump_mask(D_EMM, ep->emm, ep->emmlen, "emm:");

	int8_t cl_dvbapi = 0, assemble = 0;
#ifdef HAVE_DVBAPI
	cl_dvbapi = streq(cfg.dvbapi_usr, client->account->usr);
#endif
	if (client->account->emm_reassembly > 1 || (client->account->emm_reassembly && cl_dvbapi))
		assemble = 1;

	LL_ITER itr = ll_iter_create(client->aureader_list);
	while ((aureader = ll_iter_next(&itr))) {
		if (!aureader->enable)
			continue;

		uint16_t caid = b2i(2, ep->caid);
		uint32_t provid = b2i(4, ep->provid);

		if (aureader->audisabled) {
			rdr_debug_mask(aureader, D_EMM, "AU is disabled");
			/* we have to write the log for blocked EMM here because
			 this EMM never reach the reader module where the rest
			 of EMM log is done. */
			if (aureader->logemm & 0x10)  {
				rdr_log(aureader, "%s emmtype=%s, len=%d, idx=0, cnt=1: audisabled (0 ms)",
						client->account->usr,
						typtext[ep->type],
						ep->emm[2]);
			}
			continue;
		}

		if (!(aureader->grp & client->grp)) {
			rdr_debug_mask(aureader, D_EMM, "skip emm, group mismatch");
			continue;
		}

		//TODO: provider possibly not set yet, this is done in get_emm_type()
		if (!emm_reader_match(aureader, caid, provid))
			continue;

		struct s_cardsystem *cs = NULL;

		if (is_cascading_reader(aureader)) { // network reader (R_CAMD35 R_NEWCAMD R_CS378X R_CCCAM)
			if (!aureader->ph.c_send_emm) // no emm support
				continue;

			cs = get_cardsystem_by_caid(caid);
			if (!cs) {
				rdr_debug_mask(aureader, D_EMM, "unable to find cardsystem for caid %04X", caid);
				continue;
			}
		} else { // local reader
			if (aureader->csystem.active)
				cs=&aureader->csystem;
		}

		if (cs && cs->get_emm_type) {
			if (!cs->get_emm_type(ep, aureader)) {
				rdr_debug_mask(aureader, D_EMM, "emm skipped, get_emm_type() returns error");
				emmnok++;
				continue;
			}
		}

		if (cs && cs->get_emm_filter) {
			if (!do_simple_emm_filter(aureader, cs, ep)) {
				rdr_debug_mask(aureader, D_EMM, "emm skipped, emm_filter() returns invalid");
				emmnok++;
				continue;
			}
		}

		if (cs && cs->do_emm_reassembly) {
			if (assemble) {
				if (!cs->do_emm_reassembly(client, ep))
					return;
			} else {
				rdr_debug_mask(aureader, D_EMM, "processing raw emm");
			}
		}

		rdr_debug_mask_sensitive(aureader, D_EMM, "emmtype %s. Reader serial {%s}.", typtext[ep->type],
			cs_hexdump(0, aureader->hexserial, 8, tmp, sizeof(tmp)));
		rdr_debug_mask_sensitive(aureader, D_EMM, "emm UA/SA: {%s}.",
			cs_hexdump(0, ep->hexserial, 8, tmp, sizeof(tmp)));

		client->last = time(NULL);
		saveemm(aureader, ep);

		int32_t is_blocked = 0;
		switch (ep->type) {
			case UNKNOWN: is_blocked = (aureader->blockemm & EMM_UNKNOWN) == EMM_UNKNOWN; break;
			case UNIQUE : is_blocked = (aureader->blockemm & EMM_UNIQUE ) == EMM_UNIQUE;  break;
			case SHARED : is_blocked = (aureader->blockemm & EMM_SHARED ) == EMM_SHARED;  break;
			case GLOBAL : is_blocked = (aureader->blockemm & EMM_GLOBAL ) == EMM_GLOBAL;  break;
		}

		// if not already blocked we check for block by len
		if (!is_blocked) is_blocked = cs_emmlen_is_blocked( aureader, ep->emm[2] ) ;

		if (is_blocked != 0) {
#ifdef WEBIF
			aureader->emmblocked[ep->type]++;
			is_blocked = aureader->emmblocked[ep->type];
#endif
			/* we have to write the log for blocked EMM here because
			 this EMM never reach the reader module where the rest
			 of EMM log is done. */
			if (aureader->logemm & 0x08)  {
				rdr_log(aureader, "%s emmtype=%s, len=%d, idx=0, cnt=%d: blocked (0 ms)",
						client->account->usr,
						typtext[ep->type],
						ep->emm[2],
						is_blocked);
			}
			continue;
		}

		client->lastemm = time((time_t*)0);

		client->emmok++;
		if (client->account)
			client->account->emmok++;
		first_client->emmok++;

		//Check emmcache early:
		int32_t i;
		unsigned char md5tmp[CS_EMMSTORESIZE];
		struct s_client *au_cl = aureader->client;

		MD5(ep->emm, ep->emm[2], md5tmp);
		ep->client = client;

		for (i=0; i<CS_EMMCACHESIZE; i++) {
			if (!memcmp(au_cl->emmcache[i].emmd5, md5tmp, CS_EMMSTORESIZE)) {
				rdr_debug_mask(aureader, D_EMM, "emm found in cache: count %d rewrite %d",
					au_cl->emmcache[i].count, aureader->rewritemm);
				if (aureader->cachemm && (au_cl->emmcache[i].count > aureader->rewritemm)) {
					reader_log_emm(aureader, ep, i, 2, NULL);
					return;
				}
				break;
			}
		}

		EMM_PACKET *emm_pack;
		if (cs_malloc(&emm_pack, sizeof(EMM_PACKET))) {
			rdr_debug_mask(aureader, D_EMM, "emm is being sent to reader");
			memcpy(emm_pack, ep, sizeof(EMM_PACKET));
			add_job(aureader->client, ACTION_READER_EMM, emm_pack, sizeof(EMM_PACKET));
		}
	}
	if (emmnok > 0 && emmnok == ll_count(client->aureader_list)) {
		client->emmnok++;
		if (client->account)
			client->account->emmnok++;
		first_client->emmnok++;
	}
}
void WiiSave::writeBanner()
{
    m_writer->setEndianess(Stream::BigEndian);
    m_writer->setAutoResizing(true);
    m_writer->writeInt64(m_banner->gameID());
    m_writer->writeInt32((0x60a0+0x1200)*m_banner->icons().size());
    m_writer->writeByte((Int8)m_banner->permissions());
    m_writer->seek(1);
    m_writer->writeBytes((Int8*)md5_blanker, 16);
    m_writer->seek(2);
    m_writer->writeInt32(0x5749424E); // WIBN
    m_writer->writeInt32(m_banner->flags());
    m_writer->writeInt16(m_banner->animationSpeed());
    m_writer->seek(22);

    m_writer->writeUnicode(m_banner->title());

    if (m_writer->position() != 0x0080)
        m_writer->seek(0x0080, Stream::Beginning);

    m_writer->writeUnicode(m_banner->subtitle());

    if (m_writer->position() != 0x00C0)
        m_writer->seek(0x00C0, Stream::Beginning);

    WiiImage* bannerImage = m_banner->bannerImage();
    m_writer->writeBytes((Int8*)bannerImage->data(), bannerImage->width()*bannerImage->height()*2);

    // For empty icons
    Uint8* tmpIcon = new Uint8[48*48*2];
    memset(tmpIcon, 0, 48*48*2);
    for (Uint32 i = 0; i < 8; ++i)
    {
        if (i < m_banner->icons().size())
        {
            writeImage(m_banner->icons()[i]);
        }
        else
        {
            m_writer->writeBytes((Int8*)tmpIcon, 48*48*2);
        }
    }
    m_writer->save();
    delete[] tmpIcon; // delete tmp buffer;

    Uint8* hash = new Uint8[0x10];
    MD5(hash, (Uint8*)m_writer->data(), 0xF0C0);
    m_writer->seek(0x0E, Stream::Beginning);
    m_writer->writeBytes((Int8*)hash, 0x10);

    aes_set_key(sd_key);
    Uint8 data[0xF0C0];
    memcpy(data, m_writer->data(), 0xF0C0);
    Uint8  tmpIV[26];
    memcpy(tmpIV, sd_iv, 16);
    aes_encrypt(tmpIV, data, data, 0xF0C0);

    m_writer->seek(0, Stream::Beginning);
    m_writer->writeBytes((Int8*)data, 0xF0C0);
    m_writer->seek(0xF0C0, Stream::Beginning);
}
void CommandDispatcher (int32_t pProcNum, sLONG_PTR *pResult, PackagePtr pParams)
{
	switch(pProcNum)
	{
		case kServerInitPlugin :			
		case kInitPlugin :
			curl_global_init(CURL_GLOBAL_ALL);
			break;
			
		case kServerDeinitPlugin :
		case kDeinitPlugin :			
			curl_global_cleanup();
			break;			
			// --- PKCS
			
		case 1 :
			PEM_From_P12(pResult, pParams);
			break;
			
			// --- MISC
			
		case 2 :
			PICTURE_GET_RAW_DATA(pResult, pParams);
			break;
			
		case 3 :
			STACK_Get_available_size(pResult, pParams);
			break;
			
		case 4 :
			PROCESS_GET_LIST(pResult, pParams);
			break;
			
		case 5 :
			PROCESS_Get_id(pResult, pParams);
			break;
			
		case 6 :
			SYSTEM_Get_timestamp(pResult, pParams);
			break;
			
		case 7 :
			SYSTEM_Get_timestring(pResult, pParams);
			break;
			
		case 8 :
			SYSTEM_Generate_UUID(pResult, pParams);
			break;
			
		case 9 :
			SYSTEM_Get_unixtime(pResult, pParams);
			break;
			
		case 10 :
			STRUCTURE_Import_definition(pResult, pParams);
			break;
			
		case 11 :
			VOLUME_Is_remote(pResult, pParams);
			break;
			
		case 12 :
			VOLUME_Is_ejectable(pResult, pParams);
			break;
			
		case 13 :
			PATH_Get_known_folder(pResult, pParams);
			break;
			
		case 14 :
			PATH_From_user_selection(pResult, pParams);
			break;
			
			// --- JSON
			
		case 15 :
			JSON_Strip_white_space(pResult, pParams);
			break;
			
		case 16 :
			JSON_Parse_text(pResult, pParams);
			break;
			
		case 17 :
			JSON_Export_to_text(pResult, pParams);
			break;
			
		case 18 :
			JSON_CLOSE(pResult, pParams);
			break;
			
		case 19 :
			JSON_New(pResult, pParams);
			break;
			
		case 20 :
			JSON_GET_BOOL_ARRAY(pResult, pParams);
			break;
			
		case 21 :
			JSON_GET_CHILD_NODES(pResult, pParams);
			break;
			
		case 22 :
			JSON_GET_LONG_ARRAY(pResult, pParams);
			break;
			
		case 23 :
			JSON_Get_child_by_name(pResult, pParams);
			break;
			
		case 24 :
			JSON_Get_child_by_position(pResult, pParams);
			break;
			
		case 25 :
			JSON_Get_comment(pResult, pParams);
			break;
			
		case 26 :
			JSON_GET_TEXT_ARRAY(pResult, pParams);
			break;
			
		case 27 :
			JSON_GET_REAL_ARRAY(pResult, pParams);
			break;
			
		case 28 :
			JSON_Get_bool(pResult, pParams);
			break;
			
		case 29 :
			JSON_Get_real(pResult, pParams);
			break;
			
		case 30 :
			JSON_Get_long(pResult, pParams);
			break;
			
		case 31 :
			JSON_Get_type(pResult, pParams);
			break;
			
		case 32 :
			JSON_Get_name(pResult, pParams);
			break;
			
		case 33 :
			JSON_Get_text(pResult, pParams);
			break;
			
		case 34 :
			JSON_DELETE_ITEM_BY_NAME(pResult, pParams);
			break;
			
		case 35 :
			JSON_DELETE_ITEM_BY_POSITION(pResult, pParams);
			break;
			
		case 36 :
			JSON_SET_TYPE(pResult, pParams);
			break;
			
		case 37 :
			JSON_SET_NULL(pResult, pParams);
			break;
			
		case 38 :
			JSON_SET_COMMENT(pResult, pParams);
			break;
			
		case 39 :
			JSON_SET_NAME(pResult, pParams);
			break;
			
		case 40 :
			JSON_SET_TEXT(pResult, pParams);
			break;
			
		case 41 :
			JSON_SET_LONG(pResult, pParams);
			break;
			
		case 42 :
			JSON_SET_REAL(pResult, pParams);
			break;
			
		case 43 :
			JSON_Append_bool_array(pResult, pParams);
			break;
			
		case 44 :
			JSON_Append_real_array(pResult, pParams);
			break;
			
		case 45 :
			JSON_Append_long_array(pResult, pParams);
			break;
			
		case 46 :
			JSON_Append_text_array(pResult, pParams);
			break;
			
		case 47 :
			JSON_Append_text(pResult, pParams);
			break;
			
		case 48 :
			JSON_Append_long(pResult, pParams);
			break;
			
		case 49 :
			JSON_Append_real(pResult, pParams);
			break;
			
		case 50 :
			JSON_Append_bool(pResult, pParams);
			break;
			
		case 51 :
			JSON_Append_node(pResult, pParams);
			break;
			
		case 52 :
			JSON_SET_BOOL(pResult, pParams);
			break;
			
		case 53 :
			JSON_CLEAR(pResult, pParams);
			break;
			
		case 54 :
			JSON_Append_array(pResult, pParams);
			break;
			
		case 55 :
			JSON_Append_array_element(pResult, pParams);
			break;
			
			// --- ZIP
			
		case 56 :
			Unzip(pResult, pParams);
			break;
			
		case 57 :
			Zip(pResult, pParams);
			break;
			
			// --- Common Crypto
			
		case 58 :
			RSASHA256(pResult, pParams);
			break;
			
		case 59 :
			HMACMD5(pResult, pParams);
			break;
			
		case 60 :
			HMACSHA1(pResult, pParams);
			break;
			
		case 61 :
			HMACSHA256(pResult, pParams);
			break;
			
		case 62 :
			HMACSHA384(pResult, pParams);
			break;
			
		case 63 :
			HMACSHA512(pResult, pParams);
			break;
			
		case 64 :
			SHA384(pResult, pParams);
			break;
			
		case 65 :
			SHA512(pResult, pParams);
			break;
			
		case 66 :
			MD5(pResult, pParams);
			break;
			
		case 67 :
			SHA1(pResult, pParams);
			break;
			
		case 68 :
			SHA256(pResult, pParams);
			break;
			
			// --- cURL
			
		case 69 :
			_cURL(pResult, pParams);
			break;
			
		case 70 :
			cURL_Escape_url(pResult, pParams);
			break;
			
		case 71 :
			cURL_Unescape_url(pResult, pParams);
			break;
			
		case 72 :
			cURL_Get_version(pResult, pParams);
			break;
			
		case 73 :
			cURL_Get_date(pResult, pParams);
			break;
		case 74 :
			RSASHA1(pResult, pParams);
			break;			
	}
}
Example #30
0
SSCoreTablePtr CLeaderboard::SaveAndList( const std::string& tableName,
											const CScore& score, bool highest, 
											bool allowDuplicates, const std::string& mode,
											int perPage,const CustomData &customFilter )
{
	char IdString[50];
	sprintf_s(IdString,49,"%d",gPlaytomic->GameId());
	std::string url = kLeaderboardUrl1 + gPlaytomic->GetGameGuid() + kLeaderboardUrlSaveAndList +
		IdString + kLeaderboardUrl3;

	CPost postData;
	postData.AddText("url", gPlaytomic->GetSourceUrl().c_str());
	postData.AddText("table", tableName.c_str());
	postData.AddText("highest", highest ? "y": "n");
	postData.AddText("name", score.GetName().c_str());
	char buff[300];
	sprintf_s(buff,299,"%d", score.GetPoints());
	postData.AddText("points", buff);

	sprintf_s(buff,299,"%s%d",gPlaytomic->GetSourceUrl().c_str(), score.GetPoints());
	postData.AddText("auth", MD5(buff).hexdigest().c_str());

	CustomData customData = score.GetCustomData();
	sprintf_s(buff,299,"%d", customData.size());
	postData.AddText("numfields", buff);

	int fieldNumber = 0;
	CustomData::iterator it = customData.begin();
	for(;it != customData.end(); it++)
	{
		sprintf_s(buff,299,"%d", fieldNumber);
		std::string ckey("ckey");
		ckey += buff;
		std::string cdata("cdata");
		cdata += buff;
		std::string value = it->second;
		fieldNumber++;

		postData.AddText(ckey.c_str(), it->first.c_str() );
		postData.AddText(cdata.c_str(), it->second.c_str());
	}

	//list fields
	postData.AddText("mode", mode.c_str());
	sprintf_s(buff, 299,"%d", perPage);
	postData.AddText("perpage", buff);
	sprintf_s(buff, 299,"%d", customFilter.size());
	postData.AddText("numfilters", buff);

	
	if(customFilter.size() > 0)
	{
		int fieldNumber = 0;
		CustomData::const_iterator it = customFilter.begin();
		for(;it != customFilter.end(); it++)
		{
			sprintf_s(buff,299,"%d", fieldNumber);
			std::string ckey("ckey");
			ckey += buff;
			std::string cdata("cdata");
			cdata += buff;
			std::string value = it->second;
			fieldNumber++;

			postData.AddText(ckey.c_str(), it->first.c_str() );
			postData.AddText(cdata.c_str(), it->second.c_str());
		}		
	}
	
	CPlaytomicResponsePtr request(gConnectionInterface->PerformSyncRequest(url.c_str(),&postData));

	SSCoreTablePtr returnScores(new SSCoreTable);
	returnScores->sErrorCode = request->ResponseError();
	if(!request->ResponseSucceded())
	{
		returnScores->sSucceded = false;

		return returnScores;
	}
	returnScores->sSucceded = true;
	FData	scoreTable(Json::arrayValue);

	const FData& queryData = request->ResponseData();

	FData ScoreList;


	ScoreList = queryData.get("Scores", ScoreList);

	FData value;
	value = queryData.get("NumScores", value);
	returnScores->sScoreCount = value.asInt();
	for (size_t i = 0; i < ScoreList.size(); i++)
	{
		FData currentScore;

		currentScore = ScoreList[(int)i];

		value = currentScore.get("Name", value);
		std::string userName = value.asString();
		value = currentScore.get("Points", value);

		int points = value.asInt();

		value = currentScore.get("RDate",value);
		std::string relativeDate = value.asString();
        
        value = currentScore.get("SDate",value);
        std::string date(value.asString());

		value = currentScore.get("Rank", value);
		int rank = value.asInt();


		value = currentScore.get("CustomData", value);

		Json::ValueIterator it = value.begin();
		CustomData customData;
		for(; it != value.end(); it++)
		{
			customData.insert(std::make_pair(it.key().asString(), (*it).asString()));
		}

		returnScores->sScoreList.push_back(CScore(userName, points, date, relativeDate, customData, rank));
	}

	return returnScores;
}